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
5,633,695
5,633,711
SmartPointer : cast between base and derived classes
Say you have a function like this : SmartPtr<A> doSomething(SmartPtr<A> a); And classes like this : class A { } class B : public A { } And now I do this : SmartPtr<A> foo = new B(); doSomething(foo); Now, I would like to get back a SmartPtr<B> object from doSomething. SmartPtr<B> b = doSomething(foo); Is it p...
Instead of doing that, you can do this : B *b = dynamic_cast< B* >( doSomething.get() ); but you have to check if b is NULL.
5,633,784
5,633,833
Input from stream to enum type
How to input from stream to enum type? I can do it so unsigned int sex = 0; stream >> sex; student.m_bio.sex = static_cast<Sex>(sex); Otherwise?
inline std::istream & operator>>(std::istream & str, Sex & v) { unsigned int sex = 0; if (str >> sex) v = static_cast<Sex>(sex); return str; } If you want to ensure that the value is valid, you can do something like this: enum Sex { Male, Female, Sex_COUNT }; inline std::istream & operator>>(std...
5,634,038
6,275,612
Using libmms with Objective-C
I've been looking for a few days around the internet for tutorials or examples on how to use libmms. There seems to be none, which is strange for a lib thats seems to be widely used. LibMMS is a common library for parsing mms:// and mmsh:// type network streams. http://sourceforge.net/projects/libmms/files/libmms/0.6.2...
Simplest version I can think of: // wherever these NSStrings come from in the app, we can use them NSString *mmsURL = @"mms://123.30.49.85/htv2", *mmsHostname = @"123.30.49.85", *mmsPath = @"/htv2"; NSInteger port = 1755; mms_t *mms = mms_connect(NULL, NULL, [mmsURL cStringUs...
5,634,058
5,634,105
Programmatically mounting a FAT32 filesystem with UTF8
How can I mount a FAT/FAT32 device using "mount()" function (from "mount.h", see "man 2 mount") in a way that it will be mounted UTF8? This is the relevant code I use to mount it 'til now: mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, ""); Thanks, Nicola
The last argument to the mount command is a string interpreted by the file system driver in the kernel. It is the same you would pass to the mount shell command. For UTF8 I believe the string should be: mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "iocharset=utf8");
5,634,064
5,635,208
Compiler Warning C4251: Problem exporting a class in a *.dll
EDIT: Forgive my noobish-ness, I haven't ever implemented a wrapper .dll before! :S I've been tinkering a bit with some of the recently released Kinect Sensor hacks (namely OpenKinect and OpenNI) and I'm now trying to wrap the functionality in a *.dll for use in various "test" programs that I hope to write. So far I've...
Since you want to hide the fact you are using xn namespace in your implementation, you should not put that in the library header file. The simplest way to solve this problem is to use the pimpl idiom.
5,634,279
6,130,995
TCP packet simulation + omnet
Lets say that I have a function todo() and I want to implement this function on a packet sent from a node to a destination among all the routers. So I want that the packet goes through TCP via ethernet(could be anything) and while going I want to process the packet by calling todo() on it. I am trying to simulate this ...
Your question is little confusing. Routers process IP packets. They dont care about the payload, which might contain a TCP segment. You have a scenario like this: Client -> Router -> Server So the Client will create on L7 a packet and gives it to TCP module. There you can add your function. For example in the sendToI...
5,634,378
5,634,443
C++ arguments changing while running
I've a very simple function that should read a txt file and return all lines by one vector of the type string. I've stepped trough it quite a few times with the debugger and the only thing i've noticed is that the value of "fileName" changes on the line of the ifstream declaration. What am i doing wrong?? Thx. vector<s...
My bet would be that you get your filename from a function which returns a pointer to a local variable, e.g. something like this: char * getFilename() { char Filename[100] = "/foo"; return Filename; } The above isn't valid - Filename contents are on stack, and will be invalidated when getFilename() returns. vector<...
5,634,565
5,634,616
Temporaries problem in C++
I have this piece of code that prints the content of a directory using Boost.Filesystem: class Shell { private: const string& command; const path& firstPath; const path& secondPath; public: // constructor Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): comman...
Shell shell("ls", Path); // BAD - just happens to work as you expected. Undefined Behavior - Anything can happen, including acting like you expect. The memory allocated by the temporary just happened to not be overwritten in your case.
5,634,637
5,634,750
Private inheritance: name lookup error
I have the following code example that doesn't compile: #include <stdio.h> namespace my { class base1 { // line 6 }; class base2: private base1 { }; class derived: private base2 { public: // The following function just wants to print a pointer, nothing else! void p...
The section you're looking for is 11.1. It suggests using ::my::base1* to work around this: [ Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than th...
5,634,743
5,739,278
Non client painting on aero glass window
Now Im customizing title bar of my application. My aim is to add one extra button on title bar. Im my previous question people have adviced me the way I can customize non client area. Thats works perfectly except one small thing - glowing! I can draw glowing in nonclient area but I cannot make it spreads out of the wi...
Skype cheats it, and has a little sliver along the top of their window; where they can draw it. You can see it with Process Explorer to SpyXX: See also MSDN: Custom Window Frame Using DWM
5,634,996
5,635,794
Which COM smart pointer classes to use?
I'm confused by the choices for COM smart pointers classes for C++ programming: There's three four I'm aware of: CCOMPtr from ATL _com_ptr_t from the MS Com Support Classes TComInterface (because I'm using C++Builder 2009) CCOMQIPtr, (which I'd previously forgotten) I've read about the error vs. exception handling di...
If you are using the type-library import stuff, it will generate code based upon _com_ptr_t and the related COM Support Classes. Go ahead and use those if you are just using stuff from those libraries. If you are writing ATL-based code, then use CCOMPtr and the other ATL-based classes. Things may get ugly if you need ...
5,635,086
5,636,331
C++ socket option reuse port
I have a problem with a c++ socket. I'm using CAsyncSocket from MFC that i want to join a multicast group. Also I need to have multiple listener on this group and here is where i get in trouble. I found some examples on the web but it doesn't seems to work. Here is my code: //create socket on port 17233 BOOL bRet ...
You should be able to separate the creation of the socket from the binding, create the socket using Socket, eg. BOOL bRet = Socket(SOCK_DGRAM, FD_READ); Then bind it with Bind after setting the sockopt BOOL bMultipleApps = TRUE; bRet = SetSockOpt(SO_REUSEADDR, (void*)&bMultipleApps, sizeof(BOOL), SOL_SOCKET); bRet = ...
5,635,212
5,702,316
Detect the the vtable index/ordinal of a specific virtual function (using Visual C++)
Further to my question: Detect the the vtable offset of a specific virtual function (using Visual C++): Given: struct A { virtual void a() {} virtual void b() {} virtual void c() {} }; How can I write a function in Visual C++ (probably non-portable), such that: int x = GetVtableIndex(&A::a); //returns 0 int...
Inspired by imre's and Ivan's answer, I think this can be completely solved: template <class T, typename F> int VTableIndex(F f) { struct VTableCounter { virtual int Get1() { return 1; } virtual int Get2() { return 2; } virtual int Get3() { return 3; } virtual int Get4() { return...
5,635,215
5,635,352
c++ file descriptor (sockets) isopen()?
In C++, is there a way to check if a file descriptor is still open, long after it was initially opened?
You can use fcntl with the F_GETFL to get if the fd is valid or not.
5,635,294
5,635,333
Redeclaration of variable
When I run Setup() I expect to see a 't' in my console, followed by multiple 'x' characters. However it returns just multiple 't' chars. It's like my retrn never gets overwrited. Please see codesample below: class Returner { public: Returner(){} char test() { } }; class TReturner: ...
I can't 100% explain that behaviour - I'd expect you wouldn't get any characters printed as it'd be using Returner::test - but if you're overriding a function in C++ you need to declare it virtual in the base class: class Returner { public: Returner(){} virtual char test() { } }; Without test...
5,635,397
5,637,785
Capturing OpenMP exceptions with SetUnhandledExceptionFilter
I have an exception handler set up using SetUnhandledExceptionFilter, which works fine. However, if I throw an exception from within OpenMP code, I get the standard "the application crashed" window and the handler is not called -- however, I can attach a debugger just fine and see that the call stack is ending with _Cx...
Interesting. Going out on a limb, I'll wager that the OpenMP concurrency runtime doesn't honor the SetUnhandledExceptionFilter (which will work for "standard" threads), and isn't integrated into this feature of Structured Exception Handling. Note this warning from the MSDN page on Exception Handling in the Concurrency...
5,635,410
5,635,493
Simple Word Wrap Function Last Line Problem
I have a function that takes a long string and breaks into smaller strings and adds them to an array so that they can be outputted in a nicer looking paragraph. It works fine except for the last line doesn't output. How would I get it to output? Here's the code: void WordWrap(string inputString, string formatedAr[], co...
You only write into formatedAr when adding a character would make the current line too long. You also need to write the remnant into formatedAr when you've finished parsing the input string. Try putting formatedAr[word] = outLine; after the for loop finishes.
5,635,450
5,635,531
C++ macros with define or inline?
Possible Duplicate: Inline functions vs Preprocessor macros Inline functions were introduced in C++ to replace C style macros (#define macroname...), still, I see lots of C++ code using old C style macros rather than inlined functions, are inlined function inferior to old C style macros?
I would say macros are inferior to inlined functions. Inlined functions are type safe and macros are not. That's the big advantage of them. The compiler is helping you make better code. With that said, there are a few things that macros can do that functions cannot. There are not many of these things though... I believ...
5,635,568
5,635,608
C++ : const reference to local object
const std::string s1 = "abc"; const std::string & s2 = "abc"; Is the definition of s2 legal? If so, what is the difference between between s1 and s2? Thanks.
Yes, s2 is legal. s2 is bound to a temporary std::string - extending the temporaries lifetime. s1 isn't a temporary, it's a named variable. See 12.2/5: The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a...
5,635,683
5,635,740
openGL texture mapping
Hey, I am creating a game using openGL in c++ when I try and map a texture to an object it changes the colour of everything else I have drawn eg everything goes a transparent red or green.. glEnable (GL_TEXTURE_2D); Bitmap image; image.loadBMP ("Texture.bmp"); glGenTextures(1, &m_TextureID); glBindTex...
You need to disable texture mapping for your other objects if you don't want them to be textured. glDisable(GL_TEXTURE_2D); glBegin(GL_QUADS); ...
5,635,700
5,635,738
C++ error unexplained: error: expected initializer before '&' token
i know there's a few other posts like this, but i've been on this single error for over an hour now and can't figure it out. here's the code that's giving trouble istream& operator>>(istream& in, UndirectedGraph& g) { int numVerticies; in >> numVerticies; g = UndirectedGraph(numVerticies); for(int i = ...
This: void UndirectedGraph::istream& operator>>(istream& in, UndirectedGraph g) doesn't make sense! You probably want: istream& operator>>(istream& in, UndirectedGraph g) Having said that, you don't seem to be returning anything in your function definition.
5,635,750
5,635,824
overloading constructors with friend classes
I have a class that uses either a static list (firstFriend in the example) or a dynamic list (secondFriend in the example) for initialization. The list functionality I didn't want to write for the example because it is not important. The key problem is that the firstFriend and the secondFriend are, well, friends. The c...
If both constructors have exactly same code, then you can write a constructor template as: template<class FriendType > target(const FriendType &) { // Some nice initialization of the TargetData. } If there is a little difference, but most of the code is same, then you can write an init template function, and cal...
5,635,815
5,767,563
Helloworld in symbian
I am a j2me developer but now I have to develop an application for Symbian in C++. I am completely new to it. I installed Perl, Symbian S60 5th edition and Carbide.c++, and started to create the 'helloworld' application as guided in this documentation: http://library.forum.nokia.com/index...6502C151E.html. I get 2 erro...
Open your build file, comment the line after PRJ_MMPFILES. This happens because application help fine is not defined.
5,635,927
5,731,321
How to make Dllimport correctly in c#?
ive had some problems building a correct .dll from a c++-project to my c#-project. I played around with the c++-project-properties and got a .dll file which i can add and refer to in my c# web-project. I use Dllimport to make a function call to the .dll like this: [DllImport("Filename.dll", CharSet = CharSet.Ansi)] sta...
After some time changing the settings back and forth i noticed that the data i had to start with was the same data i had after a decrypt and an encrypt. So I realized that the encryption/decryption was working. The problem was the data. When i had the correct data i got the correct output! This is the end setup im stu...
5,636,100
5,636,153
JNI system.loadlibrary problem - native C++ dll using C library
I have a pretty annoying compiling problem. I am trying to do a System.loadlibrary on a C++ DLL in VS2010, which in turns uses a C DLL compiled in VS2008. The error I am getting is: java.lang.UnsatisfiedLinkError: The application has failed to start because its side-by-side configuration is incorrect This occurs whenev...
You should try and use the dependency walker on your DLLs. From the side-by-side error I assume that one of the c runtime redist packages or one of the noredist packages is missing. But the dep walker should show you this. If this does not help you can get some more information from the event log of Windows since side ...
5,636,248
8,248,249
Calling C++ cocoa touch static library from iphone app
I have developed a very simple C++ based cocoa touch static library and a simple touch based application which includes this library. The application gives compilation error "Undefined symbol" corresponding to the librarie's function being called. ld: symbol(s) not found. But if I make C based cocoa touch static libra...
The library has .cpp and .h source code, and test application had .m files. It was giving compilation error. To fix this , I just changed file extension of .m files to .mm in my test application. And it compiled, linked and ran successfully. Thanks
5,636,289
5,636,313
overloaded method not seen in subclass
Possible Duplicates: C++ overload resolution Why does an overridden function in the derived class hide other overloads of the base class? Why the following example: class A { public: void f(int x){ } }; class B : public A { public: void f(float a, int b){ } }; int main(){ B *b = new B; ...
Essentially, you are not overloading the base class method; by redefining method f, you are hiding the base class method. You can prevent this by including it explicitly into the child class scope the following: class B : public A { public: using A::f; void f(float a, int b){ } };
5,636,334
5,636,533
Singleton initialization
I implemented the Singleton design pattern in my code. Suppose it is: class Singleton { Singleton () {} static Singleton* s; public: static Singleton* Get () { if (!s) s = new Singleton (); return s; } }; What puzzles me is the 'initialization' of this pattern. In the .cpp I put: SingletonPointer...
Static fields must have definitions besides their declaration. The declaration usually goes in the class declaration in the .h file, while the definition almost always goes in the .cpp file. The definition of static variables is a must, since they must be initialized to something. But even though the definition is outs...
5,636,712
7,706,631
Can ColumnSize argument of ODBC SQLBindParameter be strlen(param) + 1 for SQLCHAR type parameter?
The example for SQLBindParameter function at http://msdn.microsoft.com/en-us/library/ms710963(v=vs.85).aspx passes the size of the character array as the ColumnSize argument (6th argument) when the C type is SQL_C_CHAR. Quoting parts of the examples from that page: SQLCHAR szEmployeeID[EMPLOYEE_ID_LEN]; SQL_DATE_STRUCT...
The answer to this question is "Yes".
5,636,729
5,636,814
Using "umlauts" in C++ code
Possible Duplicate: C++ source in unicode I just discovered this line of code in a project: string überwachung; I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine ...
GCC complains on it: codepad : error: stray '\303' in program The C++ language standard itself limits the basic source character set to 91 printable characters plus tabs, form feed and new-line, which are all within ASCII. However, there's a nice footnote: The glyphs for the members of the basic source character set...
5,637,019
5,637,866
Enumerating the available keyboard layouts in Windows
Is it possible to enumerate all the currently available keyboard layouts. By available I mean the user can switch to them by pressing Alt+Shift (or whatever his chosen shortcut is), i.e. they are in the Language Bar's menu. Alternatively, checking if a specific layout is available in the Language Bar would also be us...
The function GetKeyboardLayoutList seems get most close information to what you need. The returned information is the array of HKL, the HANDLE has values like 0x04070407 - German 0x04110411 - Japanese 0x04190419 - Russian 0xe0200411 - Japanese If you have for some language more as one input methods or more as one layo...
5,637,132
5,648,571
Front-end/Back-end design: how to absolutely dissociate the back-end from the front-end?
My question is: (is the above|what is) the right way to create a non intrusive front-end? I am explaining my problem with a simplified example. I have a back-end implementing a binary tree: // Back-end struct Node { Label label; Node* r, l; }; I would like now to implement the front-end to print the tree graphical...
I finally found an "elegant" solution with the decorator design pattern. This pattern is used to extend an object without changing its interface. GNode decorates/extends Node: template <class T> struct GNode : public T, public Drawable { virtual void accept(Visitor& v); // override Node::accept() } As you can see, i...
5,637,153
5,637,332
CEdit::GetLine() windows 7
I have the following segment of code where m_edit is a CEdit control: TCHAR lpsz[MAX_PATH+1]; // get the edit box text m_edit.GetLine(0,lpsz, MAX_PATH); This works perfectly on computers running Windows XP and earlier. I have not tested this in Vista, but on Windows 7, lpsz gets junk unicode characters inserted int...
Since you're using MFC, why aren't you taking advantage of its CString class? That's one of the reasons many programmers were drawn to MFC, because it makes working with strings so much easier. For example, you could simply write: int len = m_edit.LineLength(m_edit.LineIndex(0)); CString path; LPTSTR p = path.GetBuffer...
5,637,160
5,637,921
Guarding resources with Singleton?
I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge: Under no circumstance will there be more than one camera (the camera API...
You can read anything, sooner or later. Regardless of what the some people say, there's no fundamental reason against using a singleton in the appropriate cases_. In your case, I have serious doubts, at least the way you describe it. Regardless of the API of the camera maker (which is probably in C), your client cod...
5,637,249
5,639,181
Which OpenGL version is most stable and currently used?
I've been thinking of making an additional wrapper for my project to use OpenGL rather then Allegro. I was not sure which OpenGL version to go for since I know that some computers cannot run recent versions such as v4.4. Also, I need a version which compiles no problem in Linux, Windows, Mac.
You'll want to look at what kinds of graphics cards will be available on your target systems and bear some details in mind: OpenGL up to 1.5 can be completely emulated in software in real time on most systems. You don't necessarily need hardware support for good performance. OpenGL 1.4 has universal support. Virtually...
5,637,380
5,637,420
Keeping track of boolean data
I need to keep track of n samples. The information I am keeping track of is of boolean type, i.e. something is true or false. As soon as I am on sample n+1, i basically want to ignore the oldest sample and record information about the newest one. So say I keep track of samples, I may have something like OLDEST 0 0 ...
Sounds like a perfect use of a ring buffer. Unfortunately there isn't one in the standard library, but you could use boost. Alternately roll your own using a fixed-length std::list and splice the head node to the tail when you need to overwrite an old element.
5,637,425
5,637,695
Camera connection and disconnection catch
Hey guys, I'm using OpenCV with the C++ API, and in order for my project to be more reliable I need a certain camera connection\disconnection handling. I have searched for how-to's, but I could only find answers that require an ugly hack in order to do so. Can you suggest a cleaner way to do it? Thnx
Detecting camera connection/disconnection might require some tricks. I suggest that you start another thread to check the success of cvCreateCameraCapture() in a loop, while your application is running. Something like the following: while (run_detection_thread) // global variable controlled by the main thread { CvCap...
5,637,559
5,637,913
Error linking libboost_system in Visual C++
I have a problem using boost.asio. I use Windows XP and Visual Studio 2005 I followed these steps: I downloaded the latest version (http://sourceforge.net/projects/boost/files/boost/1.46.1/) of W: \boost_1_46_1 I set the environment variable INCLUDE : W:\boost_1_46_1 In the properties of my project (VS->tools->Options...
The boost::asio library needs to be built. ( Many other boost 'libraries are headers only and do not need to be built ). Building it yourself is a small challenge. Better to use the pre-built binary installer which is here Once you have the built libraries, one way or another, you have to tell the linker where they a...
5,637,561
5,637,618
How to silence 'The last statement should return a value' warning?
Sun Studio 12.1 prints the warning Warning: The last statement should return a value. frequently for functions like that: int f() { /* some code that may return */ // if we end up here, something is broken throw std::runtime_error("Error ..."); } It is perfectly clear that we do not need a return value at the ...
Can you reorganize the code in the function in such a way (hopefully more logical as well) that the normal path happens at the end of the function so that a return can be used, and the exceptional path happens earlier, NOT as the last statement? EDIT: If reorganizing the function really doesn't make sense, you can alwa...
5,637,679
5,637,862
Default argument in the middle of parameter list?
I saw a function declaration in our code that looked as follows void error(char const *msg, bool showKind = true, bool exit); I thought first that this is an error because you cannot have default arguments in the middle of functions, but the compiler accepted this declaration. Has anyone seen this before? I'm using GC...
That code would work if in the very first declaration of the function, the last parameter has default value, something like this: //declaration void error(char const *msg, bool showKind, bool exit = false); And then in the same scope you can provide default values for other arguments (from right side), in the later de...
5,637,772
5,639,357
Zoom QGraphicsItem to fit QGraphicsView
I am trying to create a QGraphicsView that will allow someone to scale the current QGraphicsItem to fit the size of the QGraphicsView window. I have overridden QGraphicsItem to create a custom version, and I implemented some methods so it knows how much it has been scaled (which is always proportional to the original,...
First of all, QGraphicsItem::boundingRect() returns a copy of the rect. Changing it has no effect on the actual item. To change an item's geometry, you need to override that function and return a different rect. And call prepareGeometryChange() when you actually change it. Now, if all you want is to fit the item in QGr...
5,637,787
5,638,500
Archive/Serialize Objective-C Object with C++ Instance Variables
I am using OpenCV static library in Objective-C to do some image processing, and although my app is working quite well, on the device itself it is rather slow. A large chunk of the processing can actually done beforehand, so I have decided I will serialize this data and just load that up when the app starts instead. Th...
Objective-C's serialization code is not going to know how to archive your C++ classes. You're going to need to explicitly write code to do that. Assuming "description" is the CvSeq* in the above code, you will need to write methods that convert from CvSeq to something that Cocoa knows how to archive. An NSString is p...
5,637,819
5,637,966
C++: Cloud computing library: is there such a library where I don't need to write much network stuff?
I want my server app to be able to send data to be processed by a bunch of various clients, and then have the processed data returned to the server. Ideally, I'd have some call like some_process = send_to_client_for_calculating(connection, data) I just need to be able to send a bunch of data to a client, tell the clien...
I'm shocked no one has thrown it out there... how about boost::asio.
5,637,999
5,638,093
c++ vectors and pointers
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of th...
You've created the vector and initialized it to contain 20 items. Those items are being default initialized, which in the case of a pointer is a null pointer. The program is having trouble dereferencing those null pointers. One piece of advice is to not worry about what's most efficient until you have a demonstrated pr...
5,638,321
5,638,651
Why child process returns exit status = 32512 in unix?
In my program I'm executing given command and getting result (log, and exit status). Also my program have to support shell specific commands (i.e. commands which contains shell specific characters ~(tild),|(pipe),*). But when I try to run sh -c ls | wc in my home directory via my program it failed and its exit status w...
execvp takes a path to an executable, and arguments with which to launch that executable. It doesn't take bourne shell commands. ls | wc is a bourne shell command (among others), and it can't be broken down into the path to an executable and some arguments due to the use of a pipe. This means it can't be executed using...
5,638,323
5,638,357
Modifying a data structure while iterating over it
What happens when you add elements to a data structure such as a vector while iterating over it. Can I not do this? I tried this and it breaks: int main() { vector<int> x = { 1, 2, 3 }; int j = 0; for (auto it = x.begin(); it != x.end(); ++it) { x.push_back(j); j++; cout << j << " ....
Iterators are invalidated by some operations that modify a std::vector. Other containers have various rules about when iterators are and are not invalidated. This is a post (by yours truly) with details. By the way, the entrypoint function main() MUST return int: int main() { ... }
5,638,730
5,638,786
virtual function with user-defined-type vector
I want to define an abstract base class with a vector of struct variables, and a virtual function to be implemented by derived classes: class TestFather { private: struct myStruct { // struct definition }; vector<myStruct> myStructVect; public: virtual vector<myStruct> get_myStructVect() =...
You don't have to redefine the struct in TestSon, and you also can't do this. The caller of fatherptr->get_myStructVect statically gets a vector<TestFather::myStruct> back, so the compiler forbids you to override the base class function like that, because the dynamically returned object would potentially be incompatibl...
5,638,761
5,639,222
QScopedArrayPointer guarding my data but it is still leaking
#include <QScopedArrayPointer> #include <QDebug> #include <stdexcept> class MyData{ public: MyData() { qDebug() << "Construct a data"; } ~MyData() { qDebug() << "Delete a data"; } private: float internal_data_; }; class MyClass{ QScopedArrayPointer<MyData> data_; public: MyClass(){ data_.r...
I think the issue is that your exception is uncaught and is being handled by the terminate handler. Since there is no catch to handle the exception, there is no way for the compiler to know how much to "unroll". If you catch the exception, then destruction occurs. You can then of course re-throw it if you like, for exa...
5,638,886
5,638,941
Popup notifiers in C/C++
I've been working on a project that will need a notifier in the system tray (sorry, "System Notification Area"). It will be a simple app that just generates popup notifications when it receives a message via a Zeromq socket. I am not having any luck finding anything other than .NET resources and examples. Does anyone h...
I would start with this section of MSDN: Notifications and the Notification Area. Then I'd check the NotificationIcon Sample in the Windows SDK.
5,638,934
5,661,863
openCV and Threads issue
I'm trying to fit facedetect from openCV on my QT code, all run fine until i decided to create a thread for my openCV code so I can run another things while the face detect is on. the problem is if i call class->start(); my program breaks in the while loop in the run() but if i call the class.run(); (like a normal func...
Solution: I can't create windows outside the main thread, that is why it was crashing. If i comment the window creation all works good (face detection included)
5,638,977
9,035,829
How to Redraw/Repaint an IHTMLElement pointing to an image element in the DOM in IE9?
I've got a valid IHTMLElement object that points to an image in IE9. The image data was recently updated via an IDirectDrawSurface. I'm trying to find a way to force IE9 to repaint the image in the DOM after I update the image data. Could anyone please direct me to a method of forcing a repaint of an image that has bee...
Have you tried resetting the src of the element? From what I can see, IE won't do anything if you set the same src that is already present, but looks like it can be tricked; IHTMLImgElement pImg; m_pElement->QueryInterface(IID_IHTMLImgElement, (void**)(&pImg)); _bstr_t bstrOriginalSrc; pImg->get_src(bst...
5,639,037
5,639,066
would return 0 using C++ in a class outside of main close the application?
I'm currently working on implementing patch files in some code, and apparently one of the patch files uses return 0 in a class outside of the main. I know return 0 would close the application if it was in the main function, however I'm not sure about how it would function in a class outside of the main function. Basica...
No. Think of what would happen if this was the case: int add(int a, int b) { return a + b; } // somewhere: int zero = add(2, -2); // would this exit the program? It isn't the zero that is important in the return from main, it's the return. You can return any value from main and doing so will cause the program to exi...
5,639,048
5,639,145
Insert into multimap causes segfault
I am working on a project using multimaps inside of my own class, and I have run into a segfault. Here are the parts of my code relating to the issue. I would really appreciate some help. Thanks. Here is database.h #include <iostream> #include <map> using namespace std; class database{ public: database(); // start...
You need to allocate your database before starting to insert data on it. Change: database *data; to: database *data = new database(); or: database data; in main(). EDIT: if you use the latter, change -> to . on the subsequent method calls. Otherwise, remember to delete your data object after using it.
5,639,177
5,639,232
what exactly is a token, in relation to parsing
I have to use a parser and writer in c++, i am trying to implement the functions, however i do not understand what a token is. one of my function/operations is to check to see if there are more tokens to produce bool Parser::hasMoreTokens() how exactly do i go about this, please help SO! I am opening a text file with ...
Tokens are the output of lexical analysis and the input to parsing. Typically they are things like numbers variable names parentheses arithmetic operators statement terminators That is, roughly, the biggest things that can be unambiguously identified by code that just looks at its input one character at a time. One n...
5,639,275
5,639,344
How to use OpenGL 2.0 rather than a later version?
The goal is to make a game which will be compatible with many Graphics cards, and cross-platform. I decided to go with OpenGL 2.0 and Glut. I quickly came to realize however, that there are no specific DLL for version OpenGL version 1.0, 2.0, 2.1... This lead me to wonder, how exactly do you choose which OpenGL versio...
You simply don't use any of the new features introduced since 2.0
5,639,391
6,606,234
Google GYP to MSVC Solution
How can I create a MSVC solution from a Google GYP File? There seems to be limited documentation on this ...
The documentation is now more valid and this question is no longer needed.
5,639,403
5,641,967
Compiler error on Stopped enum value using GetStatus
I'm trying to get the status of a sound effect but I don't know how to actually find out what the status is. I'm quite new to C++. I tried to read up about enums and apply what I saw, but it won't work. Here's my code sf::Sound::Status BeepStatus = Beep.GetStatus(); cout << BeepStatus; if (BeepStatus == Stopped) { ...
You need to use the scope operator for your Stopped variable. Likely, it's this: sf::Sound::Stopped
5,639,927
5,640,379
Tool for generating a call flow graph [C C++ solaris linux]
I'm quite fond of IDA, but I'm working in Solaris on this project. I do have a linux machine, and if nothing is in the same league as IDA then I'll convince management to purchase a license for it. Barring that, I'm looking for alternative suggestions. Some of the other features in IDA would be handy, but the main th...
Take a look at the ERESI Project. It's a reverse engineering framework and it has a tool, called ELFsh, with capabilities of generating CFG from machine code. It doesn't have a stable/final yet, but it's worth a shot. If you want to try it: download and install (apt-get on Ubuntu) run elfsh32. You'll enter a shell. lo...
5,640,129
5,640,265
A non-relational embedded database with a permissive free software license?
many thanks in advance for taking the time to look at my question. (I am aware of this question Nonrelational Databases for C++, but my needs are a bit different and it only has one answer.) I am developing a commercial C++ library that must, among other things, persist messages. I would like to avoid reinventing the w...
Use SQLite in b-tree mode. Public domain. Avoids politics. Let's you work around the political issues by avoiding the SQL interface for performance-critical paths, and optionally using the SQL parser path for those queries that are not on the critical path.
5,640,144
5,640,189
c++ how to use select to see if a socket has closed
Can someone provide me an example of how to use select() to see if a client has closed the connection on a socket? FYI. I'm using linux. Thanks!
The below snippet first checks if the socket is marked readable (which it is when closed) and then if there's actually anything to be read. #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <sys/ioctl.h> bool isclosed(int sock) { fd_set rfd; FD_ZERO(&rfd); FD_SET(sock, &rfd); timeval tv...
5,640,429
5,654,721
Generalizing for_each over a tuple to accept a variable number of arguments
Currently, I have: template <unsigned I, unsigned N, typename Tuple, typename UnaryFunction> struct for_; template <unsigned N, typename Tuple, typename UnaryFunction> struct for_<N, N, Tuple, UnaryFunction> { static void call(const Tuple&, UnaryFunction) {} }; template <unsigned I, ...
See below for the map(UnaryFunction, Tuple&&...) implementation I will be using, as well as the code I had been messing with in an attempt to get it working completely as I wanted (for_aux, last, etc.). #include <array> #include <iostream> #include <tuple> namespace detail { struct static_ { private: static_(...
5,640,602
5,641,128
Module and classes handling (dynamic linking)
Run into a bit of an issue, and I'm looking for the best solution concept/theory. I have a system that needs to use objects. Each object that the system uses has a known interface, likely implemented as an abstract class. The interfaces are known at build time, and will not change. The exact implementation to be used w...
COM very likely is what you want. It is very broad but you don't need to use all the functionality. For example, you don't need to require participants to register GUIDs, you can define your own mechanism for creating instances of interfaces. There are a number of templates and other mechanisms to make it easy to crea...
5,640,748
5,640,899
Can I convert a null pointer of int to a long type by reinterpret_cast
int *pt = 0; long i = reinterpret_cast<long>(pt); Is i guaranteed to be 0? Is this well defined or implementation-defined? I checked the c++ standard, but it only states that A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it. In ...
No, i is not necessarily any value. The result is implementation-defined.† The representation of pointers, in C++, is implementation-defined, including the representation of a null pointer. When you assign an integer value of zero to a pointer, you set that pointer to the implementation-defined null pointer value, whic...
5,640,884
5,640,951
What is the C++ stream equivalent to perror?
Possible Duplicate: C++ alternative to perror() I can't find the stream equivalent to perror. Is there such a thing? I like the fact that I can call: perror("Error"); And it will fill in what errno is. Can I do this with streams?
To print an error message: str << strerror(errno); If you're talking about the streams error state - no you can't get an automatic meaningful error message for that.
5,640,907
5,640,920
C++ alloc array of objects
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean: ofstream* out = new ofstream[10]; for(int i = 0; i < 10; i++){ stringstream ss; ss << "file" << i << ".txt"; string str(ss.str()); char *fileName = (char*)str.c_st...
Get rid of the fileName variable and use out[i].open(str.c_str()); - and remember to delete[] out;
5,641,199
5,641,279
How to get the AST from YACC?
I know how to make YACC generate an AST, but how do you actaully get it? I mean, how do you actaully get the value of the root node from YACC?
Yacc only gives you back one node at a time, and it's always something that you just gave yacc at some earlier time, i.e., whatever you wanted to return from a reduced production or whatever you wanted to return from a terminal symbol. (Sorry, you said you knew that, but some people reading this might not.) So, take wh...
5,641,403
5,641,450
Overloading function on return type? (revisited)
Can someone tell me what different the compiler does in following two cases? #include <cstdio> using namespace std; template <typename TReturn, typename T> TReturn convert(T x) { return x; } int main() { printf("Convert : %d %c\n", convert<int, double>(19.23), convert<ch...
When the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appearance by the type passed as the actual template parameter (double in this case) and then calls it. This process is automatically performed by the compiler and is invisible to the ...
5,641,427
5,641,470
How to make preprocessor generate a string for __LINE__ keyword?
__FILE__ is replaced with "MyFile.cpp" by C++ preprocessor. I want __LINE__ to be replaced with "256" string not with 256 integer. Without using my own written functions like toString(__LINE__); Is that possible? How can I do it? VS 2008 EDIT I'd like to automatically Find and Replace all throw; statements with thro...
You need the double expansion trick: #define S(x) #x #define S_(x) S(x) #define S__LINE__ S_(__LINE__) /* use S__LINE__ instead of __LINE__ */ Addendum, years later: It is a good idea to go a little out of one's way to avoid operations that may allocate memory in exception-handling paths. Given the above, you shoul...
5,641,656
5,641,699
TCPSocket.h:35: error: expected ',' or '...' before numeric constant
I'm receiving "TCPSocket.h:35: error: expected ',' or '...' before numeric constant" when compiling what I'm pretty sure was previously compiling code. Line 35 is TCPSocket(int port, bool vOutput, const int DIRECTORY_SIZE); from the below pasted class declaration using namespace std; class TCPSocket { public: #define...
You can't do this: TCPSocket(int port, bool vOutput, const int DIRECTORY_SIZE); because it means TCPSocket(int port, bool vOutput, const int 8192); and this is not legal syntax. I guess you mean: TCPSocket(int port, bool vOutput, const int nSize = DIRECTORY_SIZE);
5,641,805
5,641,925
Why do I receive a warning for1I64<<31?
Why do I receive a warning for this code ? switch(iInput) { ... case 1I64<<31: return 31; break; ... } 1>C:\path-to-file.cpp(44) : warning C4309: 'case' : truncation of constant value 1I64<<31 is 0x0000000080000000 (__int64) so no truncation here, it's there a maximum value for case ?
The type of the expression controlling the switch controls they type of the expression the case labels will use. You'll need an __int64 (or equivalent) type in the controlling expression to get rid of the warning.
5,641,870
5,642,385
Allegro vs OpenGL speed/efficiency wise
I've been using Allegro 5 for a while now, and recently began looking into OpenGL with Freeglut. I would be ready to make a switch, but I would like to know if it's really worth it. Is OpenGL really much more efficient than Allegro5 for its drawing operations?
It depends on the drawing operations that you perform. It also depends on whether the operations you perform can be hardware-accelerated by OpenGL and whether that acceleration is beneficial. (On OpenGL, it can also depend on how you perform those operations, since some drawing methods are known to be measurably slower...
5,642,063
5,647,030
inheriting ostream and streambuf problem with xsputn and overflow
I have been doing research on creating my own ostream and along with that a streambuf to handle the buffer for my ostream. I actually have most of it working, I can insert (<<) into my stream and get strings no problem. I do this by implimenting the virtual function xsputn. However if I input (<<) a float or an int ...
It's not too clear what you're doing, although it sounds roughly right. Just to be sure: all your ostream does is provide convenience constructors to create and install your streambuf, a destructor, and possibly an implementation of rdbuf to handle buffers of the right type. Supposing that's true: defining xsputn in ...
5,642,237
5,642,308
'Enemy' was not declared in this scope?
Okay, so thats my error: 'Enemy' was not declared in this scope.The error is in the map.h file, even though map.h includes enemy.h as shown #ifndef MAP_H_INCLUDED #define MAP_H_INCLUDED #include <iostream> #include <fstream> #include <string> #include <vector> #include "enemy.h" #define MAX_TILE_TYPES 20 using name...
You need to remove one of the #include statements to break the circular reference. To allow the code to compile you can declare one of the included classes as just a simple definition class Map; in the top of the Enemy.hpp file, for example, and then include the header in the cpp file.
5,642,251
5,694,826
TagLib - How to handle UTF-8 encoded file paths?
Problem: I want TagLib::FileRef to open a file with Unicode characters in its file name or path, but do not succeed. I compiled TagLib 1.7 with MinGW (GNU Make 3.81, GCC 4.4.0) under Windows 7 (64-bit, but 32-bit compiler) after creating the Makefile with CMake 2.8.4. I use TagLib in conjunction with the Qt 4.7.2 frame...
The FileRef constructor accepts a FileName object (not String!), which can be either char* or wchar_t* string. On Windows you can assume that both wchar_t and QChar have 16-bits, so you can simply pass it filePath.constData(). Note that if you are planning to run the code on non-Windows platform, you need to have an #i...
5,642,319
5,642,363
Creating an instance of a C++ class in a .lib file from C#
As the description states. I have some static .lib files created in other rather large c++ projects containing a class I would like to be able to use in C#. What would the best way to use these classes from inside c#. The C++ libraries are not managed.
By far the easiest option is to build a wrapper library in C++/CLI.
5,642,367
5,642,453
extra qualification error in C++
I have a member function that is defined as follows: Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString); When I compile the source, I get: error: extra qualification 'JSONDeserializer::' on member 'ParseValue' What is this? How do I remove this error?
This is because you have the following code: class JSONDeserializer { Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString); }; This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler ...
5,642,616
5,642,639
An interesting result when I typecast te output
I am observing an interesting result when I typecast an output: Here is the code snippet: int bitSize = (int)log10(1.0*16)/log10(2.0); //bistsize = 3 it should be 4 int temp = log10(1.0*16)/log10(2.0); //temp = 4 Basically I want to take log2(16) which should be 4. I think my understanding of typecasti...
I think you are only casting the output of the first log(..) function. Put parenthesis around the entire expression: int bitSize = (int)(log10(1.0*16)/log10(2.0));
5,642,798
5,642,938
Using a TCP connection to GET data from a HTTP server, on rare occasion there's garbage data
I'm writing a networked game in C++ using Winsocks 2.2, using Visual Studio 2010, and decided it would be a good idea to use my web-server to store a list of active servers for the game. When a server starts up, it will register itself with my web server, on exit un-register; and the server itself will attempt to clea...
The so-called "garbage" is in fact the chunked data from the server. An HTTP/1.1 server is free to send data back in chunked format, if it prefers, and the HTTP/1.1 spec is pretty clear: "All HTTP/1.1 applications MUST be able to receive and decode the "chunked" transfer-coding". The details of chunked encoding are des...
5,642,819
5,645,345
Reverse traits lookup?
I have been looking for a design that solves the following problem. It will take a few words to describe. We have four types A1, A2, B, and C. We would like to write a function fn that takes as parameter a type P. Using traits, P resolves within A1/A2/B/C to PA1/PA2/PB/PC. The implementation of fn is the same for PA1 a...
I think that you are confusing two things here: The implementation of fn is the same for both PA1 and PA2 Does not preclude PA1 and PA2 from being distinct types with distinct typedef. Which we can therefore use as is: template <typename PA> char fn(PA pa) { typedef typename PA::type Type; // A1 or A2 return 'a';...
5,643,060
5,643,071
Is it wise to access read-only data from multiple threads simultaneously?
I have an application that I'm trying to make multithreaded. Each thread will access a large chunk of read-only data. Is is okay if multiple threads access the data simultaneously? I know that if the data were not read-only, I would need to use mutexes or some other form of synchronization to prevent race-conditions. B...
If the data is read-only for the lifetime of all the threads that read it, then yes, it's perfectly fine to read without synchronization.
5,643,140
5,643,183
Weird behavior merging 2 class functions and passing variables by reference
I have the following two class functions which I'm attempting to merge into one because they are very similar: void Camera::UpdateCameraPosition(void) { if(cameraMode == CAMERA_MODE_THIRD_PERSON) { float alpha = Math::DegreesToRadians(Rotation.y); float beta = Math::DegreesToRadians(Rotation.x); ...
You'll notice that target.SetValue uses + for Camera and - for Player when adjusting the X Y and Z coordinates.
5,643,178
5,643,838
CUDA how to get grid, block, thread size and parallalize non square matrix calculation
I am new to CUDA and need help understanding some things. I need help parallelizing these two for loops. Specifically how to setup the dimBlock and dimGrid to make this run faster. I know this looks like the vector add example in the sdk but that example is only for square matrices and when I try to modify that code...
As you have written it, that kernel is completely serial. Every thread launched to execute it is going to performing the same work. The main idea behind CUDA (and OpenCL and other similar "single program, multiple data" type programming models) is that you take a "data parallel" operation - so one where the same, larg...
5,643,337
5,643,587
2D Dynamic Array C++ Display Problem
I've read about 2d dynamic arrays but I obviously haven't quite got my head around it as this program doesn't work. The program seems to lie in displaying the array. The input file is a text file with V and E on the first line with a 'tab indent' between them. The input vertices are on the next lines again tab indented...
//Input number of vertices and edges f >> V >> E; // You're hiding your member variable in the following line, leading to an incorrect initialization // int** adj = new int*[V]; adj = new int*[V]; for (int i=0;i<=V;i++) { adj[i]= new int[V]; }
5,643,579
5,643,599
Is it safe to store a reference to an element of a list?
Is it safe to store a reference to an element in a std::list as long as that element is not removed from the list? I see from this question that it is safe to store list iterators, but is the same true for direct references? For example list<int> mylist; mylist.push_back(3); int& myint = *mylist.begin(); // modfy myl...
Is it safe to store a reference to an element in a std::list as long as that element is not removed from the list? Yes. Insertions and erasures do not invalidate references or iterators to elements in a std::list (except, of course, that references and iterators to an erased element is no longer valid).
5,643,639
5,643,996
How could a call to a member function of a class cause that object to no be longer "delete-able"?
I understand that this is a very broad question, but I was very curious about this so I decided to ask. Please understand that what information I give is unfortunately all that I have :) I was wondering, in a C++ program, what possible situations could the following case happen in: The following is the (mimicked) code...
The problem with declaring and implementing a class in a DLL and simply using it from outside is that "outside" needs to know the layout of your class. At a minimum the calls to new/ delete operators must know how much memory must be allocated and freed. Based on what you said, my best guess is that the client is usin...
5,643,659
5,643,703
how to insert pair<int, int> into queue?
i am having trouble inserting objects of type pair<int, int> into a queue. i am getting a strange error, and i have no idea how to go about fixing it. Can anyone help? the following is the code for the method, followed by the error messages. The first two errors are for the insert, the last is for the usage of the oper...
Lines of code like so: pairq.push(pair< &whereto->value, &whereto->adj->value >); should probably look like: pairq.push(make_pair(whereto->value, whereto->adj->value)); or if the value members aren't of type int: pairq.push(pair<int,int>(whereto->value, whereto->adj->value)); Finally, queue::pop() doesn't return any...
5,643,849
5,643,905
Visual Studio Questions/C++
I'm a hobbyist developer and have a background with Java (IDE of choice was Eclipse). I'm using Visual Studio Express 2010 and wanting to learn C++. Few questions: I create a "HelloWorld" in C++ and compiles/runs in VS/Windows. When I try to compile it under Linux/GCC, it obviously throws tons of errors. Default wi...
I create a "HelloWorld" in C++ and compiles/runs in VS/Windows. When I try to compile it under Linux/GCC, it obviously throws tons of errors. Default windows console project includes windows specific files; but if just create an "Empty Project" it throws tons of linker/build errors. What's the best pra...
5,643,923
5,644,008
C++ Initializing Non-Static Member Array
I am working on editing some old C++ code that uses global arrays defined like so: int posLShd[5] = {250, 330, 512, 600, 680}; int posLArm[5] = {760, 635, 512, 320, 265}; int posRShd[5] = {765, 610, 512, 440, 380}; int posRArm[5] = {260, 385, 512, 690, 750}; int posNeck[5] = {615, 565, 512, 465, 415}; int posHead[5] = ...
If your requirement really permits then you can make these 5 arrays as static data members of your class and initialize them while defining in .cpp file like below: class Robot { static int posLShd[5]; //... }; int Robot::posLShd[5] = {250, 330, 512, 600, 680}; // in .cpp file If that is not possible then, declare...
5,644,035
5,644,297
C++ QT4 detecting when a user double clickes a qtablewidget header
I am trying to detect when a user double clicks a header in a qtablewidget. To do this I am connecting to the signal "sectionDoubleClicked(int)" to a function with the same arguments (i got this from 1 ). My issue is that I am getting the following compile time error: mainwindow.cpp:117: error: no matching function f...
You either didn't include QHeaderView by #include <QHeaderView> or didn't declare "headerclickedscan(int)" as signal in your MainWindow class. Also are you sure you want "headerclickedscan(int)" to be a signal but not a slot ?
5,644,338
5,644,362
How to force child same virtual function call its parent virtual function first
guys, I have a case that needs the child class needs to call its parent virtual function at first before call its override virtual function. BaseClass::Draw() { } ChildClass::Draw() { BaseClass::Draw(); // BaseClass Draw must be called first. } GrandChildClass::Draw() { ChildClass::Draw(); // ChildClass Draw...
For simple cases you can use a second, private member function for the overrideable behavior: class Base { public: void Draw() { // Base-class functionality here OverrideableDraw(); } private: virtual void OverrideableDraw() { } }; class Derived : public Base { private: virtual void O...
5,644,421
5,644,469
call a childs version of a function instead of a parents?
Okay, so I got two classes. class a{ public: a(){}; void print(){cout << "hello"}; } class b : public a{ public: void print(){cout << "hello world";} } And a array of parents with a child a blah[10]; blah[5] = b(); Than I call print, and want it to say hello world. blah[5].print(); But it calls the parent. How do I...
This can be fixed by declaring the function virtual, a la: class a{ public: virtual void print(){ cout << "hello"; } } class b : public a{ public: virtual void print() { cout << "hello world"; } } This is how one implements polymorphism in C++. More here: http://en.wikipedia.org/wiki/V...
5,644,429
5,645,120
QSharedPointer VS std::tr1::shared_ptr VS boost::tr1::shared_ptr
These three are shared pointer classes from Qt, STL and Boost, respectively. They seem to be identical in functionality so I'm puzzled as to: What are advantages and disadvantages of each of them? Why do Boost and Qt versions even exist -- it was in STL already, why make your own? How should I choose which one to use?...
Look here for the answers to your questions.
5,644,448
5,644,602
Specialization of template template parameters
This is a sequel question (on a different topic) to an earlier question. The code below incorporates Dehstil's suggestion to use specialization. How should a function that has template template parameters be specialized? The code below (in which the two specialization lines do not compile) make the question concrete. #...
Partial Specialization of function template is NOT allowed by the C++ Standard! Overload your functions instead of specializing them. Read the explanation as to Why Not Specialize Function Templates? by Herb Sutter Then read why to overload than specialize : Template Specialization and Overloading by Herb Sutter How t...
5,644,776
5,644,962
How can I add multiple icons to an individual TreeView item?
I am trying to display multiple icons to the Treeview item but it is not displaying all the icons, it displays only one. I am using the following code: CImageList m_imageState; m_cTree.m_imageState.Create(16, 16, ILC_MASK, 0, 4); m_cTree.m_imageState.Add(&bm, RGB(255,255,0)); m_cTree.m_imageState.Add(&bm2, RGB(255,0,25...
Correct, only one icon will be displayed per item in a TreeView control. This is by design, a hard limitation of the native control that the MFC library wraps. The only way you're going to be able to display multiple icons per item is owner drawing. It's a pretty difficult task for a TreeView control, not nearly as eas...
5,644,861
5,645,891
Spinning in a non-blocking app without gobbling up CPU time
I have a UDP network application that reads packets sent to it and then processes them (same thread). The reads are non-blocking so I'm not using poll or select. Packets received are grouped by sessions. Work is governed by whether there is a session in progress. If there is no work to be done i.e. there are no sessi...
How many packets per second are you processing? How long does it take to process those packets? If you use blocking threads, what is the average CPU usage you get? Unless blocking wait is close to 100% usage, where shaving a few bits of performance from the blocking itself can help, spinning will not improve but rathe...
5,644,884
5,645,424
Working with Existing C++ code tested under Google Test and adding Qt
I am working on a program written in C++ using some c++0x features in Linux (Ubuntu). I have written a bunch of tests in Google Test. I am using g++ and plain makefiles which generate dependencies. Now I want to work on a completely separate UI. I have decided that Qt will be good, but found that it is kind of compli...
CMake seems to work well with Qt (based on my experiences with my current project). There are a good set of macros to do all the standard Qt things, plus it integrates reasonably well with other tools. Your initial project may be a bit confusing to setup, but I'm sure there are numerous Qt examples available on the net...
5,645,261
5,645,292
Reversing the contents of an std::list
class Print { public: void PrintAll() {} private: std::list<int> mylist; }; I see this example question from a C++ language book. And I want to print the internal mylist elements. How can it be done if mylist needs to be reversed, using C++ STL library and using to output the result. Thanks ...
std::list<>::reverse()? That said, if you only need to print the list in reverse, you can simply print it using list's reverse iterators (obtained by std::list<>::rbegin() and std::list<>::rend()) rather than by using list's normal iterators. E.g.: // given std::list<int> l; for (std::list<int>::const_reverse_iterator ...
5,645,386
5,645,431
How do I make sure only my origninal client is used to make requests to my server?
I'm writing a simple online multiplayer game. It involves sending a few http requests (I don't mind using any other protcool though) to my server to store stats about the game. The problem is that the game is P2P and then the stats are sent to my server, so this makes it possible to cheat by sending fake stats. I reali...
It all depends on the type of stats. If each client can submit partial stats about other clients, and full stats for itself, you could write a server-side validation mechanism detecting discrepancies - this'd require coordinated efforts by multiple clients to get past. When you design such a mechanism, you should work ...
5,645,521
5,645,685
shifting array elements
I've been able to learn a lot about array manipulating, but was wondering how to go about shifting the elements around in the array, I'd like to try to add one more sot in the array initialized it with 0 and shift the elements around.
Let's say you have an array: char* cArr = new char[20]; for(int i = 0; i < 20; ++i) { cArr[i] = i; } If you want to shift the array to add something at a specific index, you'll have to first setup a backup pointer to the old array, make a new array, and copy the data over. Actually, you'd have to consider doing ...
5,645,526
5,645,629
How to debug remote program running on linux from windows
I am used to visual studio debugger(its really good) and I have to debug a program running on linux(in C++) from my windows machine. Can anyone suggest how to debug remote program running on linux from windows
Install an X-Windows server on your windows machine, there are quite a few alternatives (e.g. cygwin/X). SSH to the linux machine with X forwarding enabled, or setup your X server to accept connections from your linux machine and manually setup the DISPLAY on the linux machine. Install and run e.g. ddd on the linux m...