question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,274,287 | 4,274,399 | Vim splits long string into several ones | Whenever i've tried to type something like :
void InsertVertices(const std::vector<Vertex> &vertices);
Vim automatically converts it to:
void
InsertVertices(const
std::vector<Vertex>
&vertices);
and here is my vimrc:
set wrapmargin=80
set wrap
" for google codestyle
syntax on
set shiftwidth=2
"set wrap
... | As far as I know textwidth must be 0 for wrapmargin to take effect. Maybe you could try explicitly setting your textwidth:
set textwidth=0
Or use textwidth instead:
set textwidth=80
|
4,274,386 | 4,279,182 | Making an undefined class as friend, and defining it later | Making an unknown friend
template<typename T>
class List
{
protected:
class a {
int x;
int y;
private:
friend class b; // <------------ Why this is not an error?
};
template <typename U > class b { //If that is not a error this should be an error
int z;
U y;
... | Yes your code is invalid! This is an interesting show of how templates can change meaning of code in subtle ways. The following code is valid:
class List
{
public:
class a {
typedef int type;
friend class b; // that's fine!
};
template <typename U > class b;
};
class b {
List::a::type an... |
4,274,506 | 4,274,518 | Where to search for free C/C++ libraries? | Where to search for free C/C++ libraries?
| try Sourceforge
avoid GPL, as they aren't really free and are spreading like a virus through the rest of your project
use LGPL
|
4,274,755 | 4,274,808 | Where should #include statements reside? | As a returning newbie to C++, I'm trying to sort the #include methodology.
I'm following a certain set of guidelines I detail below the following example. So far this has worked out for me (the entire project keeps compiling :) ), but I'm worried I may encounter problems in the future, therefore my questions are - is t... | These are the guidelines I personally follow :
Prefer forward declarations instead of includes whenever possible. In your case, ClassA contains a ClassB so a #include "ClassB.h" is required. Had the ClassB type only appear in the file by pointer or reference, a forward reference would have been sufficient
Make header ... |
4,274,763 | 4,274,836 | What does the [Note] in undefined behavior paragraph in C++ standard mean? | As user Tony points out there's a [Note] in paragraph 1.3.12 of C++ standard saying
permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment...
Doesn't this cont... | From §6.5.1 of Part 3 of the ISO/IEC Directives:
Notes and examples integrated in the
text of a standard shall only be used
for giving additional information
intended to assist the understanding
or use of the standard and shall not
contain provisions to which it is
necessary to conform in order to be
abl... |
4,274,787 | 4,274,856 | Execution time differences, are there any? | Consider this piece of code:
class A {
void methodX() {
// snip (1 liner function)
}
}
class B {
void methodX() {
// same -code
}
}
Now other way i can go is, I have a class(AppManager) most of whose members are static, (from legacy code, don't suggest me singleton ;))
class AppManager {
public:
s... | Now first of all, this is a concern so minuscule that you would never have to worry about it unless the functions are called thousands of times per frame (and you're doing something where "frames" matter).
Second, IF they are inlined, the code will be (hopefully) optimized so much that there is no sign whatsoever of th... |
4,274,828 | 4,274,874 | How should I do this explicit specialization? | Is following design possible?:
template <typename T>
class Test{
public:
template <typename Z>
void doSomething();
//rest of things
private:
T obj;
//some things
};
Now if it was possible I'd do some explicit specializations for doSomething so that at the end I'd have some versions like below:
void doSomet... | In order to explicitly specialize doSomething you have to also explicitly specialize Test.
From 14.7.3/18 :
In an explicit specialization
declaration for a member of a class
template or a member template that
appears in namespace scope, the member
template and some of its enclosing
class templates may remain... |
4,274,870 | 4,274,897 | Could not understand error message when converting code from C to C++ | I am converting a c program into c++, and I encountered these error message:
error on line 57:
error: invalid conversion from ‘int*’ to ‘socklen_t*’
error: initializing argument 3 of ‘int accept(int, sockaddr*, socklen_t*)’
My code at line 57 is:
connected = accept(sock, (struct sockaddr *)&client_addr,&sin_size);
i ... | Try:
connected = accept(sock, (struct sockaddr *)&client_addr, (socklen_t*)&sin_size);
sin_size is obviously an int and accept expects a socklen_t*.
|
4,275,040 | 4,275,190 | Create an iostream using boost asio specifying ip and port | I have a problem concerning boost asio libraries. I successfully tried to create a socket between a client and a server, this involves creation of resolvers in order to specify ip and port to the server (the server only requires port) and other objects, but, most importantly, it is necessary to use write and read_some ... | I've written a client/server system using Boost.Asio. The source is available on GitHub: Client.cpp and Server.cpp. Using Boost.Serialization together with Boost.Asio allows me to send arbitrary datastructures over the wire. I must say it is quite impressive!
|
4,275,174 | 4,275,241 | Is boost::variant rocket science? (And should I therefore avoid it for simple problems?) | OK, so I have this tiny little corner of my code where I'd like my function return either of (int, double, CString) to clean up the code a bit.
So I think: No problem to write a little union-like wrapper struct with three members etc. But wait! Haven't I read of boost::variant? Wouldn't this be exactly what I need? Thi... | Boost.variant is not that complex, IMHO. Yes, it is template based, but it doesn't use any really complex feature of C++. I've used quite a bit and no problem at all. I think in your case it would help better describing what your code is doing.
Another way of thinking is transforming what that function returns into a m... |
4,275,275 | 4,275,490 | Passing messages between processes using message queues | I have a requirment to have communication between two processes using message queues. One process sends the request to another process and other process sends response.
For example one of the request is list all the filenames opened by the process. I have made interface structure as
#define LIST_NAMES 1
#define LI... | You could make a wrapper over mq_send() having char buffer allocated.
Every message you send will be serialized into this buffer and then you will pass it to mq_send with appropriate length - sizeof(int) + sizeof(long) + strlen(pRecvData).
The receiver will read this data and deserialize it into sFileStruct.
IMHO using... |
4,275,465 | 4,275,503 | Template linking problem C++ | I have a template class definition that needs to be in the cpp file. Adopting from http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13, I did something like this:
// File "foo.cpp"
#include <iostream>
#include "foo.h"
template<typename T> void foo()
{
std::cout << "Here I am!\n";
}
template void f... | You should be able to instantiate foo for each type you need.
template void foo<int>();
template void foo<double>();
template void foo<std::string>();
This is somewhat onerous, which is the reason many libraries tend to provide template function implementations in header files, so that any instantiation can be availab... |
4,275,526 | 5,515,344 | Calling IB API from Python | IB = Interactive Brokers
There seem to be two main choices
SWIG
Boost.Python + Py++
I understand the relative merits or demerits of using these two methods to some extent. But almost all discussions (in SO) talk about which of these tools would be better for a complex task. What I want to ask is, which of these two s... | IBpy is a great solution it's a wrapper built on the java version of the API.
http://code.google.com/p/ibpy/
|
4,275,587 | 4,275,620 | explicitly storing items in a struct | I wanted to create a file which has all the KeyPairs I need to use in a program. However, I figured it would be better to have it embedded in the code, so instead, I want to put it in a struct. For example, how do I put this items explicitly in a struct?
{Qt::Key_0, "Win1"},
{Qt::Key_1, "Win2"},
{Qt::Key_2, "Win3"}... | Just declare the struct, and initialize it:
const struct
{
Qt::Key mKey;
const char* mKeyName;
} key_names[] = {
{Qt::Key_0, "Win1"},
{Qt::Key_1, "Win2"},
{Qt::Key_2, "Win3"},
{Qt::Key_3, "Win4"},
{Qt::Key_4, "Win5"},
{Qt::Key_5, "Win6"},
{Qt::Key_6, "Win1"},
{Qt::Key_7, "Win7"},
{Qt::Key_8, "Win3"},
{Qt:... |
4,275,602 | 4,283,548 | Boost Statechart vs. Meta State Machine | Apparently boost contains two separate libraries for state machines: Statechart and Meta State Machine (MSM). The taglines give very similar descriptions:
Boost.Statechart - Arbitrarily complex finite state machines can be implemented in easily readable and maintainable C++ code.
Meta State Machine - A very high-perfo... | As there seems to be much interest, please allow me to give my (obviously biased) opinion, which should therefore be taken with a grain of salt:
MSM is much faster
MSM requires no RTTI or anything virtual
MSM has a more complete UML2 support (for example internal transitions, UML-conform orthogonal regions)
MSM offers... |
4,275,684 | 4,568,981 | RWDBReader Cannot read more than 255 characters | We're using Rogue Wave tools for our database operations, writing in C++. When we try to read the results of a simple SQL query, like:
RWDBResult resParam = VimerParamTblSlc.execute (pConn);
RWDBTable resultParam = resParam.table ();
RWDBReader rdrParam = resultParam.reader ();
if (rdrParam())
{
// getting the r... | We learn that it was a version problem with the adaptive server of Sybase and not RogueWave's fault. You need both the adaptive server and Open Client of version 12.5(or later).
|
4,275,921 | 4,275,957 | getting the number of elements in a struct | I have a struct:
struct KeyPair
{
int nNum;
string str;
};
Let's say I initialize my struct:
KeyPair keys[] = {{0, "tester"},
{2, "yadah"},
{0, "tester"}
};
I would be creating several instantiations of the struct with different sizes. So for me... | If you're trying to calculate the number of elements of the keys array you can simply do sizeof(keys)/sizeof(keys[0]).
The point is that the result of sizeof(keys) is the size in bytes of the keys array in memory. This is not the same as the number of elements of the array, unless the elements are 1 byte long. To get ... |
4,276,026 | 4,276,043 | How to write a QString on several lines? | Do you have a better way to do that ?
QString str("I am a long long long"
+ QString("long long long")
+ QString("long QString") );
I don't like all this QString.
| In C++ string literals are automatically concatenated when placed next to each other.
QString str("I am a long long long"
"long long long"
"long QString");
|
4,276,082 | 4,276,213 | Resetting an ostream, C++ | I have 2 different ostreams, one of them cerr, using the same streambuffer, I have some libraries in that might have modified cerr somehow,(flags? format modifiers?).
cerr.rdbuf(&mystreambuffer);
ostream teststream(&mystreambuffer);
cerr << "This " << " is " << " a " << " test";
teststream << "This " << " is " << " a ... | Try std::cerr.unsetf( std::ios_base::unitbuf );. That flag is on for cerr by default.
|
4,276,207 | 4,276,239 | Is C/C++ bool type always guaranteed to be 0 or 1 when typecast'ed to int? | Many compilers seem to be keeping only 0 or 1 in bool values, but I'm not sure this will always work:
int a = 2;
bool b = a;
int c = 3 + b; // 4 or 5?
| Yes:
In C++ (§4.5/4):
An rvalue of type bool can be
converted to an rvalue of type int,
with false becoming zero and true
becoming one.
In C, when a value is converted to _Bool, it becomes 0 or 1 (§6.3.1.2/1):
When any scalar value is converted to
_Bool, the result is 0 if the value compares equal to 0; othe... |
4,276,238 | 4,276,335 | removing memory leaks in c++ and GNU scientific library code | double a[] = { 0.11, 0.12, 0.13,
0.21, 0.22, 0.23 };
double b[] = { 1011, 1012,
1021, 1022,
1031, 1032 };
double c[] = { 0.00, 0.00,
0.00, 0.00 };
gsl_matrix_view A = gsl_matrix_view_array(a, 2, 3);
gsl_matrix_view B = gsl_matrix_vie... | The compiler will take care of those matrices. Unless you use malloc()/new[] or any function that uses malloc()/new[] and gives you ownership of the allocated memory there're no chances to leak memory.
If you asked about gsl_matrix_view_array() - the documentation says that the return value is a pointer to a view in th... |
4,276,406 | 4,278,173 | Are there any refactoring tools for Emacs C++ Programming? | Just like eclipse does, extracting function, renaming a variable, and so on
| The only answer seems to be xrefactory from http://www.xref.sk/xrefactory/main.html
|
4,276,493 | 6,439,456 | C++ style question: what to #include? | consider this translation unit:
#include <map>
#include <string>
int main()
{
std::map<std::string, std::size_t> mp;
mp.insert(std::make_pair("hello", 42));
}
There are two things in this translation unit that are bothering me, and they are
std::size_t
std::make_pair
I have just assumed that <cstddef> and <ut... | In the first case, I probably wouldn't but I should, if I want my code to be properly portable. There's no requirement that map::size_type is size_t, so there's no necessity for <map> to include a definition of size_t. For that matter, size_t can be a type alias rather than a distinct type, so even if size_type is size... |
4,276,666 | 4,276,706 | BGL: How do I store edge_descriptors and vertex_descriptors efficiently? | So after my circular dependency problem with the BGL was solved I've come to another obstacle.
I'm currently using an adjacency-list to model my graph. Bundled properties for both nodes and edges are applied to store some information in the graph. So I have something like this:
class Node {
int x, int y // position... | Vertex and edge descriptors take a very small size.
Vertex descriptors are numbers.
Edge descriptors are a small structure containing source and target vertex descriptors, and a pointer to internal data attached to edge descriptors.
Therefore the answer to your question is that you can use them in vectors. It won't con... |
4,276,691 | 4,276,722 | Undefined reference to extern class? | When using extern on classes it is giving me undefined reference, but when I make the function I'm calling from that class "static" it works fine.
Is there anyway to do it without using a static member function?
My test code:
#include <iostream>
class MyClass
{
public:
void print() { std::clog << "print()... | Instantiate an instance first, and make sure that you have a non-extern definition of g_myClass among your object files.
|
4,276,772 | 4,277,149 | Why was argument dependent lookup invented? | Why was argument dependent lookup (ADL) invented? Is it just so we can write cout << stuff instead of std::operator<<(cout, stuff)? If that is the case, why wasn't ADL limited to operators instead of all functions?
Could the introduction of ADL have been prevented if C++ had had some other way to do generic output of b... | ADL was invented to allow the Interface Principle:
The Interface Principle
For a class X, all functions, including free functions, that both
"mention" X, and
are "supplied with" X
are logically part of X, because they form part of the interface of X.
Check out Herb Sutter's excellent Guru of the Week on the topic.
|
4,276,794 | 4,276,885 | static keyword in h file and internal linkage | Yet another static question.
I have read the following:
What are static variables?
file scope and static floats
http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
And I still fail to understand the following behavior:
I have one h file:
// StaticTest.h
#include <stdio.h>
static int counter = 0;
struct A {
A... | If StaticTest.h is shared between difference source files then you will get undefined behaviour.
If you define a class or inline functions in different translation units then their definitions must be the same (same sequence of tokens) and, crucially, any identifiers must refer to the same entity (unless a const object... |
4,276,820 | 4,276,848 | Does private mean different things in C++ and C#? | I was wondering why C# doesn't allow private virtual functions and ran across the aptly named Why are private virtual methods illegal in C#?
In the accepted answer Eric Lippert (who probably knows what he's talking about...) said:
If you desire to restrict the ability to override the method in non-nested derived clas... | It sounds like you want the C++ world of being able to override but not call; then no: you can't do that in C#. The other way around is fine, though - either don't mark it virtual in the first place, or mark it sealed if it is already virtual.
|
4,277,220 | 4,277,248 | union in C++ and non-default constructible objects | I have a situation in my program where I need to do some conversion from strings to various types and obviously the outcome can only be ever one type. So I opted to create a union and called it variant, as such:
union variant
{
int v_int;
float v_float;
double v_double;
long v_long;
boost::gregoria... | Use boost::variant or boost::any. Union is not a solution when you have to combine non-PODs.
|
4,277,407 | 4,277,699 | Speed Comparison: C++ vs Objective C |
Possible Duplicate:
Objective-C vs C++
It is known that it is possible to write applications using C++ on Apple iOS platform, which can be especialy useful, when porting application.
Using C++ brings some obstacles comparing to Objective C in iOS. Apart from these obstacles, how is it with speed?
Are C++ application... | This really isn't something that can be answered in general as it really depends on how you use the language features. Both languages will have things that they are fast at, things that they are slow at, and things that are sometimes fast and sometimes slow. It really depends on what you use and how you use it. The onl... |
4,277,422 | 4,280,265 | Beginner: How to use the Pantheios logging API library as a replacement for #ifdef DEBUG? How to def SEVLEVEL? | i want to log a lot of events in a dynamically search-algorithm (e.g. information about convergence to global optimum). This logging should have a switch to turn it off/on. Now there are a lot of possibilities to achieve that:
implement a log-version and a non-log-version of the algorithm -> redundancy
use macros -> u... |
Is linking to "fe_all" already some kind of decisions which level is logged ad which level isn't?
Short answer: yes.
fe.all enables all severity levels: "all" meesages are logged.
If you want better control, try fe.simple. By default it switches on everything in debug builds and everything except DEBUG and INFO in re... |
4,277,477 | 4,277,523 | Is a namespace required when referring to the base class | I have code like this:
namespace N {
class B {
public:
virtual void doStuff(B *) = 0;
};
}
// not in a namespace
class Derived : public N::B {
public:
void doStuff(B *); // Should this be N::B, or is B ok?
};
Do I need the namespace qualifier where Derived refers to it's base class? ... | Inside the class definition B is OK. That's the so-called injected class name.
This also refers to templates (not counting dependent bases). E.g.
template <class T> class B{};
template <class T> class C: public B<int>
{
void f(B* p) {} //same as B<int>* p
void f(C* p) {} //same as C<T>* p
};
In general the base ... |
4,277,562 | 4,277,585 | #include boost without using libs linux | The problem: At the moment im compiling on Ubuntu but my server is running Fedora/Redhat. Ubunutu uses boost 1.42 and linux latest at this very moment is 1.41. So what i decided was to download the boost lib and put it in the folder of my workspace
Here is the directory structure
/workspace
/myprogram
/src
... | No need to include using full path, if you use gcc just specify the correct include path and link path
gcc -I../../boost_1_42_0/ myprogram.cpp -L../../boost_1_42_0/lib -lboostXYZ
Thus, all #include <boost/...> headers and libs will be first searched in your local boost.
Edit
Following the question in the comment.
By d... |
4,277,597 | 4,278,138 | unordered_set of TCHAR* requirements? | I want to use data structure that serves like .Net HashSet, I tried to use unordered_set with the default hashing method and custom comparer as follows:
struct comparer
{
bool operator()( const TCHAR* first,const TCHAR* second) const
{
return _tcscmp((TCHAR*)first,(TCHAR*)second) == 0... | Assuming that hash here is std::hash, there is no specialization of std::hash for char* or wchar* other than the generic specialization for any pointer type, that hashes based on the pointer value.
So, if you want to use TCHAR* as a hash key, with the hash based on the string contents instead of the pointer value, you'... |
4,277,810 | 4,277,842 | boost::shared_ptr and dynamic cast | I have a problem using a shared_ptr of a base class, I can't seem to be able to call the derived class's methods when dereferencing it. I believe code will be more verbose than me:
class Base : public boost::enable_shared_from_this<Base>
{
public:
typedef boost::shared_ptr<BabelNet> pointer;
};
class Derived : ... | see static_cast with boost::shared_ptr?
you'll need to use dynamic_pointer_cast to get the appropriate shared_ptr instantiation. (corresponding to a dynamic_cast)
|
4,277,866 | 4,277,915 | C++: Tool to reduce compile-time dependencies automatically | After reading about the pimpl idiom I was horrified!
Isn't there a tool out there that can inspect a .h/.cpp file and deduce what dependencies could be waivered?
| Sorry, but no there isn't. C++ still relies on preprocessing source files, very mechanical. Large-scale C++ development is all about reducing the dependencies. In my opinion, C++ is simply not suitable for those kinds of tasks.
|
4,277,884 | 4,277,950 | Dealing with array size | I happened to ask myself a question about arrays in c++.
Well, we all know that arrays are fixed collections of something, I say fixed because it is necessary to declare array length when defining arrays.
Well, let's consider an example:
char myarray[10] = {'\0'};
int sz = sizeof(myarray); // It is supposed to be 10
W... | void dosome(mystruct* arr) {
int elements = sizeof(arr)/sizeof(mystruct);
for (int i = 0; i < elements; i++) {
// Do something hoping no overflow will ever occur
}
}
What type does arr have in this example? mystruct*! And it's size is most likely 4 or 8. If you want to pass statically/automatically allo... |
4,278,024 | 4,278,749 | Very Simple C++ Web Crawler/Spider? | I am trying to do a very simple web crawler/spider app in C++. I have been searching using Google for a simple one to understand the concept. I found this:
spider_simpleCrawler
However, it is complicated to understand for me, since I started learning C++ about 1 month ago.
This is, for example, what I'm trying to do:
... | All right, I'll try to point you in the right direction. Conceptually, a webcrawler is pretty simple. It revolves around a FIFO queue data structure which stores pending URLs. C++ has a built-in queue structure in the standard libary, std::queue, which you can use to store URLs as strings.
The basic algorithm is p... |
4,278,098 | 4,278,111 | Can I loop through (public) attributes of a C++ class? | I found the answer for both C Structs and C# classes but came back empty-handed concerning C++.
EDIT : In C, you can't.
In C# it's the GetProperties() method.
The context: I have a C++ class with public attributes (let's say a Point with X, Y, Z). I want to send these attributes via UDP to a Java client. My idea was t... | There is no reflection in C++. So, the answer is, you can't :)
|
4,278,166 | 4,279,370 | Reducing thousands of compiler warnings | I have just started working with C++ code compiled in Visual Studio 2008. The default warning level on the project was set to 3 and there were no warnings. I turned this up to level 4, and it turns out that there are about 35000 warnings in our code. The majority of these warnings are unreferenced formal parameters, wh... | You could make two separate build configurations, one showing warnings level 3, and one shows level 4 as well. Then when you're not working on fixing warnings, use the level 3 configuration. If you do go down this route, you might want to look into using property sheets, so you can reuse as much as possible of the conf... |
4,278,168 | 4,278,309 | Declaring variables inside C switch/case | Well, this is not actually a question..
I have just occasionally found out that there's an interesting way to declare local variables inside a switch/case block. Instead of using braces inside every case block, you can write:
switch (action) {
int res;
int value;
case ACTION_OPEN:
res = open(...);
...
break;
... | Any standards-conforming C or C++ compiler will allow this . Even an old-fashioned (pre-ISO C99) C compiler will allow this, but only because the variable declarations are at the start of a block/compound statement (denoted by {}).
Note that what follows a switch is almost a normal statement, except for the possibility... |
4,278,307 | 4,278,345 | C++ designing containers and managing list return | I am developing a class which acts as a container for another class. In the container class I must implement a method to get all elements in the collection. My container class uses a std::deque.
Should I return a reference to the deque?
Should I return a copy of the deque? (my god tell me this is not the answer... :) )... | The best practice IMHO is to use the iterator design pattern and return iterators
As far as your particular example is concerned I would do something like this:
class myContainer
{
public:
typedef std::deque<X> actual_container_type;
typedef actual_container_type::iterator iterator;
typedef actual_container_t... |
4,278,350 | 4,278,397 | Resources for C++ programmer to learn JS | I am proficient in C++, I dont know Java Script and want to learn JS, What should be the way/process for me? I know basic html, CSS.
| Check out the one and only JavaScript Guide from MDC:
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide
Besides that, forget everything you know about C++ it won't help you in any way. JavaScript is a completely different beast on its own.
It will take a lot of type to learn all the quirks of the language and ... |
4,278,356 | 4,278,417 | Problems out of my machine: how to debug outside a dev environment? | I'm developing an application in 3D in a win 7 64bits machine, in visual C++ 2008. All runs correctly. When I check this application in a clean machine in a VMWare virtual machine with XP 32bits (hardware 3D activated) or in a machine of a friend of mine, the application fails.
The behavior of the application is diffe... | If its on the same network you can you the remote debugger ! But you may first want to check if its not a 64bit app on a 32bit OS.
|
4,278,495 | 4,278,539 | Delete NULLs from std::string | I'm using a third party code which has its own implementation for std::ostream operator<<, to handle the third party's type.
I'm using stringstream for this output - like:
string ToString(const thrdPartyType& structure)
{
stringstream outputStream;
outputStream<<structure;
return outputStream.str();
}
...
string str = ... | Are you looking for a workoround like this?
string ToString(const thrdPartyType& structure)
{
stringstream outputStream;
outputStream << structure;
stringstream workaround;
while(! outputStream.eof ) {
char t;
outputStream >> t;
if(t != '\0')
workaround << t;
}
return workaround .str();... |
4,278,602 | 4,278,803 | Does the message system in Objective C rely on the kernel message system? | I don't really understand how ObjC can efficiently rely on messages. Does this mean a kernel such as mach has to be designed with this idea ?
Objective C seems like a good language, but I can't find it easier to grasp than C++.
How is a message system built in a language an advantage ?
| The messaging in the Objective-C is not directly related to the messaging in the mach kernel. It's implemented as a highly-tuned function called objc_msgSend. The call
[obj messageWithX:x andY:y];
is translated to the C call
objc_msgSend(obj,@selector(messageWithX:andY:),x,y);
objc_msgSend is written directly in as... |
4,278,723 | 4,336,037 | A qt widget with fully transparent background | I need to create a qt widget, which will act as a parent for some other widgets, and which will order them.
Now, the question is how do I make it's background fully transparent?
I thought to do it like this :
struct Imp
{
Imp( QWidget *parent ) : thisWidget( new QWidget( parent ) )
{
thisWidget->setAttribute( Q... | By default in Qt4, a QWidget will draw nothing for its own background, and only its children will be drawn. If you want to override that, you specifically have to tell the widget to draw its background via one of its properties. Note that some widgets derived from QWidget will automatically draw backgrounds.
|
4,278,807 | 4,278,965 | Does "default" switch case disturb jump table optimization? | In my code I'm used to write fall-back default cases containing asserts like the following, to guard me against forgetting to update the switch in case semantics change
switch(mode) {
case ModeA: ... ;
case ModeB: ... ;
case .. /* many of them ... */
default: {
assert(0 && "Unknown mode!");
return ADummyValue();
}
... | If your compiler is MSVC, you can use __assume intrinsic : http://msdn.microsoft.com/en-us/library/1b3fsfxw(v=VS.80).aspx
|
4,278,814 | 4,278,894 | Do a infinite loop while downloading a file in c++? | I want to download a html file, by using this bash command
system("wget -q -E -O sample.html http://www.XXX.com");
sometime the file might huge, so I was thinking to do an infinite loop until the file is downloaded. Is it possible? If yes, how to do it?
Main Objective:
Download the html file, then proceed with the re... | system() will block until the command has finished executing. You don't have to do anything special to wait for it.
|
4,278,896 | 4,281,147 | FFmpeg: How to control console output while reading from RTSP? | So I created simple Consol app: FFmpeg RTSP Video stream reader (using only general FFmpeg C API) But while ffmpeg reads from RTSP it shows lots of info. I did not asked for if... At least not all of it... So how can I filter what ffmpeg is outputing? I mean in all he talls user-developer there is only one important li... | Use av_log_set_callback, to set your function as callback:
static void avlog_cb(void *, int level, const char * szFmt, va_list varg) {
//do nothing...
}
av_log_set_callback(avlog_cb);
or, you may also use
av_log_set_level(AV_LOG_ERROR);
to print error messages only.
|
4,278,900 | 4,278,948 | Binary stream or something like this to save class like std::vector to a file? | I'm not good in IOstream library since I have accustom to stdio and stuff life this, however I got a problem I hoped to be solved in IOstream but I find that it probably not. So I'm quite new to standard C++ libraries but quite well with C++ OOP/Classes and so on.
So I can't use code like
printf (stream, "...", C);
if... | You're looking for the term "serialization", and you might want to use the Boost::Serialization library for that purpose.
|
4,278,969 | 4,282,240 | Boost: how to create a thread so that you can control all of its standard output, standard errors? | I create a win32 console app in C++. I use some API (not mine, and I can not modify its sources). It Is written so that it writes some of its info onto console screen not asking... each time I call it (48 times per second) So I want to put it into some thread and limit its output capabilities, but I need to get notifie... | That feature does not exist in Boost. You can, however, use _dup2 to replace the standard out descriptor:
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <io.h>
#include <iostream>
#include <windows.h>
int main()
{
HANDLE h = CreateFile(TEXT("test.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE... |
4,278,987 | 4,279,021 | C++ - Overuse of virtual methods? | Recently I was given a task where I had to implement something similar to the following:
There are some animals with certain attributes, such as:
Dog1: name: tery, color:white, fav drink: grape juice
Dog2: name: chiva, color:black, fav drink: lemonade
Bird1: name: tweety, canfly: yes, cansing: no
Bird2: name: parry... | Of course 'canFly' is a valid property for a dog, it's just going to return false.
There's no point in having canFly at all if you only implement it when it needs to be true. In your example, by the time you've done your c-style case to a flying animal, then you've already committed to the type of animal, at which poi... |
4,279,072 | 4,279,146 | Static cast in middle of inheritance chain | Suppose we have:
class Component : public QGraphicsItem {
...
virtual void paintMe() = 0;
virtual void doSomething();
virtual bool isComposite() const { return false; }
}
class Composite: public Component {
...
void addChildren(Component *);
void removeChildren(Component *)
bool isComposite(... | The simple answer is: yes, if you know it is something, you can static_cast to it safely.
|
4,279,123 | 4,295,832 | Backtrace on sh4-linux returns one function | I'm trying to print call stack from within a program. Unfortunately, call to glibc backtrace() returns me always only one record - address of current function. I'm working on sh4-linux, which probably causes the problem. I had no problems in printing it on x86 architecture.
Example code:
#include <string>
#include <ios... | Try removing "stackSize = 1;"
|
4,279,164 | 4,279,258 | C++:boost file system to return a list of files older than a specific time | I am using the Boost::FileSystem library with C++ running under Linux platform and I have a question following:
I would like to have a list of files which are modified older than a given date time. I don't know whether the boost::FileSystem offer such a method as:
vector<string> listFiles = boost::FileSystem::getFiles(... | Boost::filesystem doesn't offer a function exactly like that. But you can use this:
http://www.boost.org/doc/libs/1_45_0/libs/filesystem/v3/doc/reference.html#last_write_time
as a basis to write your own. Here is some sample code using last_write_time:
#include <boost/filesystem/operations.hpp>
#include <ctime>
#includ... |
4,279,200 | 4,279,265 | Read file and extract certain part only | ifstream toOpen;
openFile.open("sample.html", ios::in);
if(toOpen.is_open()){
while(!toOpen.eof()){
getline(toOpen,line);
if(line.find("href=") && !line.find(".pdf")){
start_pos = line.find("href");
tempString = line.substr(start_pos+1); // i dont want the quote
... | I'd advise against trying to parse HTML like this. Unless you know a lot about the source and are quite certain about how it'll be formatted, chances are that anything you do will have problems. HTML is an ugly language with an (almost) self-contradictory specification that (for example) says particular things are not ... |
4,279,264 | 4,279,313 | Is reading an indeterminate value undefined behavior? | The question arose in the comments of an answer to the question Is C/C++ bool type always guaranteed to be 0 or 1 when typecast'ed to int?
The code in question allocates a (local) array of bool without initializing their value.
const int n = 100;
bool b[n];
Clearly the values in b are indeterminate.
Some of the comm... | yes, formally an rvalue conversion of indeterminate value is UB (except for unsigned char, originally i wrote "and variants" but as i recall the formal caters to 1's complement signed char where possibly minus 0 could be used as trap value)
i'm too lazy to do the standard paragraph lookup for you, and also to lazy to c... |
4,279,532 | 4,279,588 | Methods of storing application data/settings without the registry? | I need some methods of storing and getting data from a file (in WIN32 api c++ application, not MFC or .NET)
e.g. saving the x, y, width and height of the window when you close it, and loading the data when you open the window.
I have tried .ini files, with the functions -- WritePrivateProfileString and ReadPrivateProfi... | TinyXML is a popular and simple XML parser for C++.
Apart from that, you can really use any format you want to store your settings, though it's considered good practice to keep settings in text format so that they can be hand-edited if necessary.
It's fairly simple to write your own functions for reading/writing a file... |
4,279,647 | 4,279,673 | Problem with bash(system->wget) command in c++ | here is my code:
string line;
ifstream toOpen;
toOpen.open("allfiles.txt", ios::in);
int fileCounter=0;
if(toOpen.is_open()){
while(!toOpen.eof()){
getline(toOpen,line);
string dl = "wget -q -E -O superman/" + href[0] + " " + line;
//cout << dl << endl;
fileCounter++;
syste... | The function 'system' takes a 'const char *' as argument but you gave it an std::string. Try
system(dl.c_str());
|
4,279,742 | 4,279,870 | Card and Deck: Problem linking classes (environment issues?) | EDIT: I removed the main from Card.cpp, and run
C:\cpp>g++ Deck.cpp Card.cpp
C:\cpp>g++ Deck.cpp Card.cpp
In file included from Deck.h:8:0,
from Deck.cpp:1:
Card.h: In member function 'Card& Card::operator=(const Card&)':
Card.h:13:12: instantiated from 'void std::vector<_Tp, _Alloc>::_M_insert_aux(... | Did you try specifying both modules on the command line?
g++ -o deck.exe deck.cpp card.cpp
Edit: Also, using constants that start with _ or __ is technically illegal. For include-guards, I prefer to use the form MODULE_H
|
4,279,775 | 4,280,540 | Facet.narrow() uses default character where it shouldn't in utf-8 | I have following code:
#include <iostream>
#include <string>
#include <locale>
#include <algorithm>
using namespace std;
int main()
{
locale loc("cs_CZ.utf-8");
std::wstring Str = L"aaěščřžýáíéaa";
std::string Str2;
const ctype<wchar_t> &ct = std::use_facet<std::ctype<wchar_t> >(loc);
for(std::wstring::const_ite... | I beleive codecvt facet should do the trick. Ctype can only handle single byte encodings while you are trying to convert into multibyte one. Doesn't return type of ctype::narrow() method bother you?
|
4,279,825 | 4,318,399 | speex decoding going wrong | I'm using speex to encode some audio data and send it over UDP, and decode it on the other side.
I ran a few tests with speex, and noticed that if I decode a packet straight after I encoded it, the decoded data is in no way close to the original data. Most of the bytes at the start of the buffer are 0.
So when I decode... | I found the reason the encoded data was so different. There is the fact it's a lossy compression as Paulo Scardine said, and also that speex only works with 160 frames, so when getting data from portaudio to speex, it needs to be by "packets" of 160 frames.
|
4,279,839 | 4,279,947 | how to generate a stream of raw data? | Tools:
OS: Win XP,
MSVC++
The problem is that I want to generate some "raw data" stream, by that I mean a stream of random 1s and 0s, next I want to send this genrated stream over udp sockets.
any ideas on how to generate that stream?
I hope I was clear in my question and thanks in advance
| Since you're using UDP, you're not really going to get a "stream", because UDP is not a stream-oriented protocol like TCP. You can generate lots of random UDP packets, however. Just generate random integers with rand() or whatever and send them over UDP.
|
4,279,846 | 4,286,551 | how to create database in c++ | need your advice what to use... I have a task. Create an application, where u could see the list of current employers, plus buttons remove add employer...
Should I use database or somehow can read just information from file....
| One of the greatest advice of programming I could give you is K.I.S.S. (Keep It Simple Silly/Stupid).
Don't raise the complexity of the program unless you need to. Use the most simplest approach that merits the application. Darioo's comment sums it up.
For your purposes, if you need to persist your data then use a t... |
4,280,017 | 4,280,078 | Is there an equivalent to C++ member function pointers in Java? | Before you mark as a dup, yes I've seen Function Pointers in Java, and no, it didn't really answer my question, basically because I'm pretty new to Java, so I didn't really understand allot of the answers.
This is kind of some mashed up Java / C++, is there any reasonable way to do this in Java?
public class Foo {
... | No, there is simply no such thing in Java as a Function. There are only Objects and methods which are wholly owned by objects and subordinate to them. The object is your lord and master in java, nothing happens but through his will.
You can implement a sort of java-delegation by making your objects implement delegate... |
4,280,075 | 4,280,089 | QT function templates | How can I use function templates so that the following method works for any passed vector?
class MyClass
{
public:
static void method(Vector &aVector);
};
void MyClass::method(Vector &aVector)
{
...
}
I tried the following, but I get this error message:
collect2: ld returned 1 exit status
c... | template<class T> static void method(Vector<T> &aVector);
|
4,280,163 | 4,280,594 | Read 1 line from istream to string stream without temporary variable in C++? | Is is possible to read one line from input stream and pass it to string stream without using temorary string variable in C++?
I currently do the reading like this (but I don't like the temporary variable line):
string line;
getline(in, line); // in is input stream
stringstream str;
str << line;
| Like @Steve Townsend said above, it's probably not worth the effort, however if you wanted to do this (and you knew beforehand the number of lines involved), you could do something like:
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
template <ty... |
4,280,249 | 4,280,290 | What is special about the abstract class mechanism in C++? | I have question that bothers me for few days.
Abstract class is a special type of class that we cannot instantiate, right?. (Which is denoted/specified by giving a "= 0" to at least one method declaration, which looks like an afterthought).
What are the extra benefits that the abstract class mechanism brings to C++... | According to the wikibooks section on abstract classes:
It's a way of forcing a contract between the class designer and the users of that class. If we wish to create a concrete class (a class that can be instantiated) from an abstract class we must declare and define a matching member function for each abstract member... |
4,280,520 | 4,280,676 | Symbol Lookup Error: Combining Executable and Library on 64bits | I want to make a dlopen on a library that uses executable's symbols. I'm compiling gdl-0.9 on a 64bits system and I'm building a library that gdl will use dlopen. The problem is that the library uses gdl code which will be at the executable and, even though I used the -Wl,--export-dynamic flag, the program crashes and ... | _ZN4EnvT6NParamEj is EnvT::NParam(unsigned int)
_ZN4EnvT6NParamEy is EnvT::NParam(unsigned long long)
So you should start with looking at how you include declaration of EnvT. You need to look at what type of an argument of NParam and find where it's redefined.
|
4,280,568 | 4,282,577 | for loop is not working right | i have this loop that checks two objects. The problem with it, is that it only checks the first one but it doesn't check the others... When my loop check the first object for picking it says if it has been picked or not, but when it loops again to check the second object it says it has not been picked, even when it w... | I think that you have to reset the value of the rayPos and rayDir structures, because you change the initial values inside the loop:
for(int i=0; i<=1; i++)
{
matWorld=entity[i]->s;
// Use inverse of matrix
D3DXVECTOR3 rayPos((float)pt.x, (float)pt.y,0); // near-plane position
D3DXVECTOR3 rayDir((float)... |
4,280,675 | 4,280,725 | How to make a call to a subclass's member from a base class reference in polymorphic hierarchy | I am currently writing a program that models various types of numbers and manages them polymorphically in a Set object (already written and tested). My inheritance relationship is this:
Multinumber (all virtual functions, virtual class)
inherited by Pairs, Complex, Rational
The subclasses all have mostly the same funct... | I think you'll have to cast. Try this:
Multinumber& Complex::operator=(const Multinumber &rhs){
const Complex & _rhs = dynamic_cast<const Complex &>(rhs);
imag=_rhs.imag;
real=_rhs.real;
return *this;
}
|
4,280,697 | 4,280,770 | Qt - getting "warning: format not a string literal and no format arguments" | Keep getting warnings on lines like these
qDebug("An error occured while trying to create folder " + workdir.toAscii());
workdir being QString()
warning: format not a string literal and no format arguments
| That should probably be:
qDebug("An error occured while trying to create folder %s", workdir.constData());
since qDebug takes const char* as first argument.
|
4,280,783 | 4,305,202 | Poor performance with DrawText on Win7 x64 | I noticed in an MFC application I'm developing that while dragging the scroll bar to smoothly scroll down the document, the framerate drops to choppy levels when a block containing about a paragraph of text is on screen, but silky smooth when it's offscreen. Investigating the performance, I found the single CDC::DrawT... | Drawing the text at every refresh is wasteful. Use double buffering, that is, draw in an offscreen bitmap and just blit it to the screen. Then, for scrolling, just copy most of the bitmap up or down or sideways as necessary, then draw only the invalidated area (before blitting the result to the screen).
If even that tu... |
4,280,895 | 4,280,964 | Is it possible to write a truly generic disk-baked B+Tree implementation? | I wrote a generic in-memory B+Tree implementation in C++ few times ago, and I'm thinking about making it persistent on disk (which is why B+Tree have been designed for initially).
My first thought was to use mmap (I'm under Linux) to be able to manipulate the file as normal memory and just rewrite the new operator of m... | As far as I know, there are three (somewhat) easy ways to solve this.
Approach 1: write a std::streambuf that points to some pre-allocated memory.
This approach allows you to use operator<< and use whatever existing code already exists to get a string representation of what you want.
Pro: re-use loads of existing code... |
4,281,034 | 4,285,971 | How to let user select a video recording device (web-cam) with OpenCV? | So what I need is something like capture devices list.
And some function to get from user on which device he wants to stream.
How to do such thing with openCV in win32 C++ console application?
| Try using some OS functions to enumerate webcams. It might take some work, but this approach will guarantee that you get a list every time (unlike the OpenCV hack, which sometimes doesn't work, for some reason).
|
4,281,080 | 4,281,130 | Managing Templates on Member Functions | class myclass {
// Definitions of cotrs and dtor...
// ...
// Defining a method of mine that needs a template
template < typename T >
void dosome(T& par);
}
What to do in implementation in cpp file?
I thought ti was good this:
template <typename T>
void myclass::dosome< T >(T& par) {
// My code
}
Bu... | The syntax is the one used for functions:
template<typename T> void myclass::dosome(T &par) {
// ...
}
However, normally you should include template definitinos in the header.
|
4,281,149 | 4,281,211 | Best way to get data from text (char *) | Hey,
I'm sending messages via TCP and UDP from clients to the server while the server written in C++. I'm wondering what would be the best, must secure way to send, for example, if I want to send login data: email, password and IP. What would be the best way to send it in a message ang read the data in the server, whil... | As another poster stated, don't worry about C++; use SSL or TLS. This means you will need to acquire a certificate for the server, and that will cost you between $50 and $1500 dollars if you get a commercial one, or you can make your own from a intranet certificate authority that you establish yourself.
This measure w... |
4,281,360 | 4,281,367 | In linux how can I tell if I'm linking to a static or dynamic library? | I have a static and a dynamic library with the same name: libclsocket.a and libclsocket.so When I specify what library I want to link to i simply enter -lclsocket as the library. My program complies and runs perfectly fine, but what library am I using? the static library or the dynamic library? I want to give my friend... | You can try running ldd on the executable and seeing if the accompanying .so is being detected as required in the list of dependencies.
ldd man page is here.
|
4,281,366 | 4,282,322 | What is the difference between a reference and a pointer? | Could someone please explain the difference to me in very small words? I have never understood this and am very confused in my current project. What I am trying to do is fix this code:
const Multinumber& Pairs::operator+(const Multinumber &rhs) const
{
const Pairs &_rhs = dynamic_cast<const Pairs &>(rhs);
Pairs... | You do seem very confused :) Ok, so:
Essentially, a pointer is just a variable that stores the address of another variable. For instance, suppose I have an int called i, I can store its address in a pointer p:
int i = 23;
int *p = &i; // p has type int* (pointer to int) and stores &i (the address of i)
If I then wa... |
4,281,659 | 4,282,185 | C++ Linker fails because I add a throw | Well, it's really strange what's happening to me, but I'll try to make it clear.
I have a class and in one method I decide to put a throw (in hpp definition and in cpp implementation).
so I have my method that can throw a std::exception.
Here no problem.
I create an exception of mine:
class MyException : public std::ex... | I think the OP code should give a compilation error as it is ill-formed and not in the zone of UB (which may explain linker error which is surprising here).
I guess the problem is your declaration.
const char what() const throw();
The return type 'const char' in your class is not covariant with the one in the base cla... |
4,281,767 | 4,281,861 | Simple C++ OpenSSL code crashing | I'm working through a tutorial on using OpenSSL and when I try something rather basic
it seems to crash. Any idea what I'm doing wrong?
#include <openssl/ssl.h>
int main(int argc, char* argv[])
{
SSL_load_error_strings();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
SSL_CTX * ctx = SSL_CTX_... | It might be because you didn't call SSL_library_init().
|
4,281,887 | 4,282,025 | Setting _HAS_ITERATOR_DEBUGGING=0 in project settings (sometimes) has no effect | I have a Visual Studio 2008 solution with a number of projects that all define _HAS_ITERATOR_DEBUGGING=0 in the Preprocessor Definitions setting in project files. But this only seems to work on some of the projects, while others still get compiled with iterator debugging enabled.
I have checked every file in the soluti... | One thing that bites me every now and then is that project settings can easily become different between different configurations (Release vs. Debug for example). Make sure the setting is there or the configuration you're building. And of course that the define is spelled correctly...
For the projects that are having ... |
4,281,904 | 4,281,917 | error: "initializer expression list treated as compound expression" | I'm having an issue compiling the beginnings of a basic password protected file program, I'm getting the above error on line 11, (int login(username,password)). Not sure what's going on here, so it'd be nice if someone could shed some light on the situation.
#include <conio.h>
#include <iostream>
#include <string>
usi... | int login(username,password);
{
should be
int login(string username,string password)
{
|
4,282,014 | 4,282,024 | C++ Abstract class can't have a method with a parameter of that class | I created this .h file
#pragma once
namespace Core
{
class IComparableObject
{
public:
virtual int CompareTo(IComparableObject obj)=0;
};
}
But compiler doesn't like IComparableObject obj param if the method is virtual pure, while
virtual int CompareTo(IComparableObject obj) {}
It's ok, h... | You are trying to pass obj by value. You cannot pass an abstract class instance by value, because no abstract class can ever be instantiated (directly). To do what you want, you have to pass obj by reference, for example like so:
virtual int CompareTo(IComparableObject const &obj)=0;
It works when you give an implemen... |
4,282,131 | 4,282,137 | what about a mem leak in a child process | Im on unix platform.
The memory of a process with a memleak is cleaned at process termination.
What about a process, that has spawned a child, where the child has a memleak.
Will the leaked memory be cleaned up at childprocess termination? Or will this memory now stick with the parent process.
Thanks
| The memory allocated by the child process exists only in the child process's virtual address space, not the parent's. It will be freed as soon as the child process terminates or replaces itself with a new program image via one of the exec family of functions.
This is in contrast to threads, which share a common virtual... |
4,282,267 | 4,282,279 | How to only copy the exact index element from a string array? | I am working on this code, and got confused..
How to only get the 10th element and above only to be copied into the buffer?
For example, I have this string "http://www.google.com". I don't want the "http://www." part to be copied inside my testDest buffer.
char testDest[256];
char *p= _com_util::ConvertBSTRToString... | You shouldn't do this by counting. What if the next address is https://www. or if the link doesn't even have a www in it? For things like this, your best friend is "Pattern Matching".
But if you really know what you're doing, just let your for-loop begin at 10 instead of zero:
for (int i = 9; i <= strlen(p); i++)
{
... |
4,282,404 | 4,282,596 | C++ Functor Callback Setup | Im following Lars Haendel's Functor tutorial on newty.de to setup a callback system. I am a bit confused however and I am hoping someone can assist me.
Here is my Functor template
#include <igameevents.h>
// Abstract Base Class (Functor)
class TBaseCallback
{
public:
// two possible functions to call member funct... | Most people don't understand inheritance. Generally, derived classes are implementation details. The only time you utter their names are to construct them. Furthermore, virtual functions in a base should be private and pure, and should be completely inaccessible in derived classes, it's a design bug in C++ that this is... |
4,282,497 | 4,299,335 | Need help with 2D textures on CUDA. Not getting the expected value for the indexes I want | I have two matrices (A and B), 2-dimensions. And i think i'll speed up a bit if instead of putting it into global memory and access via pointers, i put them into textures 2d and use it. The matrices aren't that big, and different positions are read by different threads.
So right now my code is using global memory, and ... | Sorry 2D textures in CUDA can be a pain. I have a simple code thats only about 150 lines. I posted it on the nvidia forums. I believe you may need one of the sdk libraries to compile. I haven't had too much luck with textures for more complicated operations. I hope this helps you, it should compile for you.
|
4,282,578 | 4,282,634 | Exception specifications when deriving from std::exception in C++11 | I have an exception class as follows:
#include <exception>
struct InvalidPathException : public std::exception
{
explicit InvalidPathException() {}
const char* what() const;
};
const char*
InvalidPathException::what() const {
return "Path is not valid";
}
When compiling under GCC 4.4 with -Wall -std=c++0x
... | Empty throw specifications are useful, as they actually enable compiler optimizations at the caller's site, as Wikipedia knows (I don't have a technical quote handy).
And for reasons of optimization opportunities, nothrow-specifications are not deprecated in the upcoming standard, they just don't look like throw () any... |
4,282,662 | 4,282,818 | Template + Friend (a deadly combination) |
Possible Duplicate:
Making an undefined class as friend, and defining it later.
I have the following code
template<typename T>
class A
{
class B;
B b;
};
int main()
{
return 0;
}
The code doesn't emit any error because A is not instantiated. Am I right?
But have a look at the seco... | Regarding you second code snippet ...
template<typename T>
class A
{
protected:
class a
{
int x;
int y;
private:
friend class b;
};
template <typename U > class b
{
int z;
U y;
};
};
int main()
{
... |
4,282,773 | 4,282,785 | Cross-platform way of yielding a thread in C/C++? | In C and C++ is there a cross-platform way of yielding a thread?
Something like sched_yield() or Sleep(0)?
Does SDL_Delay(0) always yield or will it return immediately in some implementations?
| Given that neither C nor C++ (up to C++98) has "threads," there is no fully cross-platform way for a thread to yield.
In C++0x, there is a function std::this_thread::yield() that can be called to yield. That will be the portable way for a thread to yield, once people start using the C++0x threads library.
|
4,282,826 | 4,282,928 | change icon of a dialog | i am recently editing an open source project in visual c++ 2010 , i don't know much about vc++ ,(i have only 5 days of experience in c++), with my little knowledge i am changing some user interface of the project
there is only one icon in my project ,the apps shows the main icon as icon , at the same time i want to m... | You need to find the dialog procedure of the dialog you're interested in, and in the WM_INITDIALOG message handler (you need to add it if it's not already present) use WM_SETICON to set the icon:
// hIcon is your icon handle
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BI... |
4,282,866 | 4,282,882 | Overloading Pointer objects | Hi
how do I overload pointer objects . I tried it doesnt work out . can anyone help me.
CMyClass *InstancePtr = new CMyClass;
Myclassptr = MapObject->second; // returns *CMyclass
//overlaod Assignment operator ...
InstancePtr = Myclassptr;
//////////////////////////////////////////////////////
CMyClass * CMyClass... | You cannot overload operators for pointer type objects.
You can only overload an operator where at least one of the operands is of class type or enum type.
Since an overloaded assignment operator must be implemented as a non-static member function, it can only be overloaded where the left-hand side operand is of cl... |
4,282,961 | 4,282,998 | how to call C# from c++ | I am wondering what's the way to call a c# class method from C++(Native, not C++ CLI) code? Need simple and elegant way
| Turn your C# assembly into a COM visible one and use COM interfaces. That is the only way to make it work beside self made IPC as far as I know. The problem comes from the .NET environment under which the .NET assembly must run and C++ runs under its native C++ environment.
The only way of communicating is either an IP... |
4,282,982 | 4,407,017 | List of internet explorer add-ons | How can I get list of all IE add-ons programatically using c/c++?
And after that I want to disable and enable them....Any kind of help is greatly appreciated.
| guys I have found a way how to do this.
Open "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Toolbar". This 'Toolbar' key contains CLSID of all the toolbars installed. Now you need to extract the name of toolbar in 'Default' value name of key. If you did not get name under this then query "HKEY_LOCAL_MACHINE\S... |
4,283,080 | 4,283,116 | Data flow analysis for C++ program | I need to do some data flow analysis for C++ programs. Any open source tools that anyone can suggest?
| try to evaluate if gcc and the intermediate front-end code transformation into GIMPLE or GENERIC (intermediate languages for workflow analysis for the code optimizer) fit for your purpose. This is fully free and open source. I just cannot tell you how exactly to output this tree representation but there are many gcc ma... |
4,283,091 | 4,283,102 | C++ assert() fails without giving any error message, or line where it failed | I am having a strange problem in my code. I have many asserts scattered around the code and all have been working fine. Whenever an assert failed I got a message giving me line number of where the failure happened.
Today I wrote another assert in a function which loads a file. Just wanted to make sure that the fie ex... | You most likely have FUBAR'ed the stack somewhere before the assert executes.
|
4,283,307 | 4,283,362 | Does initializer list suppress the call to constructor? | If I declare a class with default constructor and define a instance of this class with initializer list as below, will the default constructor be called for this definition? And why been called or not been called?
class Sample
{
// this should be any aggregate type in c++
};
int main()
{
Sample s = {0};
return 0;
... | The Standard says ($8.5/14)
The semantics of initializers are as follows. The destination type is the type of the object or reference being initialized and the source type is the type of the initializer expression. The source type is not defined when the initializer is brace-enclosed or when it is a parenthesized li... |
4,283,435 | 4,283,466 | A variable set inside BOOST_FOREACH-loop is invalid outside loop, why? | BOOST_FOREACH invalidates a weak_ptr that resides as a member in the class GroupMember, please help me understand why.
The code below explains the error:
class GroupMember
{
bool logInState;
boost::weak_ptr<CUser> wpUser;
};
GroupMember::iterator it;
BOOST_FOREACH(EachLevel aLevel, levels)
{
if(aLevel.exist(spU... | You assumed that BOOST_FOREACH is implemented like in your second code snippet, which is a wrong assumption.
Second, in your BOOST_FOREACH you iterate by value. Try by reference:
BOOST_FOREACH(EachLevel& aLevel, levels)
and see if it works.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.