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
453,440
453,621
COM event handling in C++
Without the following: ATL MFC Question: How to get the COM Server, to report back to the COM Client, once a particular event has terminated? Regards
See: COM event handling - IConnectionPointContainer - illustration
453,738
454,010
Inheritance or composition: Rely on "is-a" and "has-a"?
When I design classes and have to choose between inheritance and composition, I usually use the rule of thumb: if the relationship is "is-a" - use inheritance, and if the relationship is "has-a" - use composition. Is it always right? Thank you.
No - "is a" does not always lead to inheritence. A well cited example is the relationship between a square and a rectangle. A square is a rectangle, but it will be bad to design code that inherits a Square class off a Rectangle class. My suggestion is to enhance your "is a / has a" heuristic with the Liskov Substitutio...
453,769
459,455
How do I create a Lua Table in C++, and pass it to a Lua function?
In C++, I have a map<string, string>, containing an unknown number of entries. How can I pass this to a Lua function, so that the Lua function can use the data as a table?
if you want a real lua table: lua_newtable(L); int top = lua_gettop(L); for (std::map::iterator it = mymap.begin(); it != mymap.end(); ++it) { const char* key = it->first.c_str(); const char* value = it->second.c_str(); lua_pushlstring(L, key, it->first.size()); lua_pushlstring(L, value, it->second.siz...
453,928
454,276
Hibernate like layer for C++
Using a DB with C++ is a real mess and it was refreshing when I moved to Java to be able to use a unified system to abstract the whole layer away (aka Hibernate). There are a couple of C++ abstract layers for DB's out there but they are usually vendor specific and only a thin layer that wraps the real C API. Has anybod...
I don't know of any C++ library like Hibernate, but certainly there are non-vendor specific libs: SOCI and DTL
454,316
454,399
COM event notification
Without: ATL MFC Note: Client is executing in a different thread to that of the server Question: How do I control the behaviour of the client, once an event notification is received from the COM object (Server)? How to implement an event interface from client? Illustration below: hresult = pis8->QueryInterface(...
The client implements the event interface (IS8SimulationEvents) This can be in a separate component, or on the client component itself. The implementation is called when the component fires an event. After FindConnectionPoint, the client calls pConnection->Advise, passing the IS8SimulationEvents and receiving a "cookie...
454,664
454,669
Speech to text conversion in Linux
I am planning to start an application which converts the speech to text in Linux. Are there any existing interfaces so that I can extend them? or Is there any such existing application in Linux? Any inputs on this? EDIT: The application that I am planning to write should be able convert every word that we speak to text...
Well, this is quite an undertaking and without saying what technology you want to use, here are some links: Speech Recognition on Wikipedia Java Speech API W3C Speech Recognition Grammar Specification Sphinx - An open source recognition engine written in Java Good luck. With more detail, we may be able to provide bet...
454,762
454,782
vector or map, which one to use?
I've heard many people say that if the number of expected elements in the container is relatively small, it is better to use std::vector instead of std::map even if you were to use the container for lookups only and not iterating. What is the real reason behind this? Obviously the lookup performance of std::map cannot ...
I presume you're comparing map<A, B> with vector<pair<A, B> >. Firstly, finding an item in a very small vector can easily be faster than the same thing in a map, because all the memory in a vector is always contiguous (and so plays more nicely with computers' caches and such things), and the number of comparisons neede...
454,811
454,845
Opening an OpenDialog from Vis C++ console app?
I know this is a darn simple question, but I'm very used to using Borland and wrappers, so this is a bit of a new approach for me. Can someone simply tell me how I Can open an OpenDialog that only gets .obj files from a visual studio c++ console app? It's very much appreciated!
There isn't really any difference between a console application and a GUI application, except for entry point (WinMain in a 'GUI' app), and a console app will have a console window opened during startup if not started from a console. All of the Win32 API is available, so you need to use the GetOpenFileName call, as fol...
454,984
455,007
Receiving COM events
Without: ATL MFC Note: Plain C++ Out-of-process COM Object/server Predefined TLB file Question: How to implement an outgoing interface, so the COM Object can notify the sink of events? How to handle the event appropriately, once received? Below is the event function I'd like to implement - from TLB file: inline...
Implement the source interface in COM Server class. You should implement IConnectionPointcontainer if you are not using the ATL. In the client class call the COM server as mentioned below. 1. Call FindConnectionPointContainer 2. Call FindConnectionPoint 3. Call Advise on the interface pointer returned from step 2, we s...
455,125
455,162
How to implement an outgoing interface on a sink object (C++)
I have a predefined TLB file, with IS8SimulationEvents wrapper method implementations, for instance: inline HRESULT IS8SimulationEvents::S8SimulationReset ( ) { HRESULT _result = 0; _com_dispatch_method(this, 0x1, DISPATCH_METHOD, VT_ERROR, (void*)&_result, NULL); return _result; } Using Oleview, I can see...
This article explain how to implement connections points sources/sinks in plain C http://www.codeproject.com/KB/COM/com_in_c5.aspx Probably the whole series of articles "COM in plain C" by Jeff Glatt are more than recommended if you want to understand COM at the low level. PD: Lambdasoft Comet is a framework that imple...
455,251
455,257
I need a slightly different multimap
I'm looking for a C++ container class, that's a lot like a multimap, but slightly different. The container would store pairs of strings. But when I retrieve items from the container using key K, I want to find all the items where K begins with the item's own key. E.G. If I use key "abcde" I want to find items with key...
I would suggest using a trie. Basically you have a tree with 1 node per unique character. Your algorithm would be O(m) for both lookups and insertion, where m is the length of a string. So following your example with: "abcde", "hello" "abc", "Hi" "abcqz", "goodbye" Then you would have the following trie: a ...
455,346
455,356
What to do about wrong "control reaches end of non-void function" gcc warning?
$ cat t.cpp int sign(int i) { if(i > 0) return 1; if(i == 0) return 0; if(i < 0) return -1; } $ g++ -c t.cpp -Wall t.cpp: In function ‘int sign(int)’: t.cpp:5: warning: control reaches end of non-void function $ What do I do about this? Stop using -Wall as it's clearly wrong? Add a bogus return 0 at the en...
If you don't want to add "else" clauses because they would make the code longer, then perhaps you would like to remove the final "if" and make the code shorter: int sign(int i) { if(i > 0) return 1; if(i == 0) return 0; return -1; // i<0 } Or if you're really computing "sign" yourself and this isn't a ...
455,434
455,533
How should I use FormatMessage() properly in C++?
Without: MFC ATL How can I use FormatMessage() to get the error text for a HRESULT? HRESULT hresult = application.CreateInstance("Excel.Application"); if (FAILED(hresult)) { // what should i put here to obtain a human-readable // description of the error? exit (hresult); }
Here's the proper way to get an error message back from the system for an HRESULT (named hresult in this case, or you can replace it with GetLastError()): LPTSTR errorText = NULL; FormatMessage( // use system message tables to retrieve error text FORMAT_MESSAGE_FROM_SYSTEM // allocate buffer on local heap for...
455,483
455,487
Going from string to stringstream to vector<int>
I've this sample program of a step that I want to implement on my application. I want to push_back the int elements on the string separately, into a vector. How can I? #include <iostream> #include <sstream> #include <vector> using namespace std; int main(){ string line = "1 2 3 4 5"; //includes spaces stri...
int num; while (lineStream >> num) numbers.push_back(num);
455,518
455,535
How many and which are the uses of "const" in C++?
As a novice C++ programmer there are some constructs that look still very obscure to me, one of these is const. You can use it in so many places and with so many different effects that is nearly impossible for a beginner to come out alive. Will some C++ guru explain once forever the various uses and whether and/or why ...
Trying to collect some uses: Binding some temporary to reference-to-const, to lengthen its lifetime. The reference can be a base - and the destructor of it doesn't need to be virtual - the right destructor is still called: ScopeGuard const& guard = MakeGuard(&cleanUpFunction); Explanation, using code: struct ScopeGuar...
455,793
455,829
Programmatically copy a cell from Excel using VC++
Without: MFC ATL using COM, with pure C++, steps taken thus far: //steps above omitted _ApplicationPtr application(__uuidof(Excel::Application)); //omitted const BSTR wcharFileName = SysAllocString(L"..."); application->Workbooks->Open(wcharFileName); application->put_Visible(10, true); Question: How to then c...
Try this http://support.microsoft.com/kb/216388/en-us
455,904
456,184
Print information in "test mode" but not in "normal execution"
I am using an application in c++ that uses a special dprintf function to print information, this is an example: dprintf(verbose, "The value is: %d", i); What is doing is when I define verbose for test purposes then I print the information and when I am working in normal execution I do not define it and I do not see us...
I try to avoid using var-arg c-style functions for two main reasons: They are not type-safe, can't use operator<< They don't recognize when too few or many arguments were provided I've made a way that works using boost::fusion, which is given arguments in a type-safe way. It iterates over those arguments, printing ou...
456,303
456,312
How to validate input using scanf
How can I validate the user input by using scanf. Right now I have something like this, but doesn't work. NOTE: I have the atoi just to validate that the scanf validation works. scanf("%[0987654321.-]s",buf); i = atoi(buf); if(i) index = i;
Using scanf() is usually a bad idea for user input since failure leaves the FILE pointer at an unknown position. That's because scanf stands for "scan formatted" and there is little more unformatted than user input. I would suggest using fgets() to get a line in, followed by sscanf() on the string to actually check and...
456,310
456,339
Destructors of builtin types (int, char etc..)
In C++ the following code gives a compiler error: void destruct1 (int * item) { item->~int(); } This code is nearly the same, I just typedef the int to another type and something magic happens: typedef int myint; void destruct2 (myint * item) { item->~myint(); } Why does the second code work? Does an int get a d...
It's the reason that makes your code work for generic parameters. Consider a container C: template<typename T> struct C { // ... ~C() { for(size_t i = 0; i<elements; i++) buffer[i].~T(); } }; It would be annoying to introduce special cases for built-in types. So C++ allows you to do the...
456,323
456,332
Static/Dynamic Runtime Linking
What are the best practices for choosing the linking method in VC++? Can anything/everything be statically linked? On a dynamically linked project, is the relative/absolute location of the linked library important? What are the pros and cons ? added: I was mainly referring to lib files. Do they behave same as dll lin...
Dynamic links allow you to upgrade individual DLLs without recompiling your applications. That is why windows can be upgraded without your application being recompiled, because the dynamic linker is able to determine the entry points in the dll, provided that the method name exists. Statically linking your application...
456,357
456,390
C++ ifstream failure, why is this line not going where it's supposed to?
I want to make the line marked with // THIS LINE SHOULD BE PRINTING do its thing, which is print the int values between "synonyms" and "antonyms". This is the text file: dictionary.txt 1 cute 2 hello 3 ugly 4 easy 5 difficult 6 tired 7 beautiful synonyms 1 7 7 1 antonyms 1 3 3 1 7 4 5 5 4 7 3 #include <iostream> ...
The problem seems to be here: in>>myId>>word; On the "synonyms" line the extraction of myId fails and sets failbit on the stream, which causes the following extractions to also fail. You have to reset the error control state before extracting further elements (like the word "synonyms") from the stream: in.clear();
456,557
456,570
Getting this junk out of my vector
I want to eliminate the junk that I'm getting on the vector<int> synsAux below. It should print: 1 7 7 1 I'm getting an extra 2 before the first and third digit, why? Is this 2 an ascii value for the blank space or something? How do I avoid its reading? This is the dictionary file needed to run the program: dictionar...
You're printing the twos here: cout<<synsAux.size();
456,588
456,632
mem_fun fails, pthread and class ptr
pthread takes in as its parameter void *(*start_routine)(void* userPtr), I was hoping I can use std::mem_fun to solve my problem but I cant. I would like to use the function void * threadFunc() and have the userPtr act as the class (userPtr->threadFunc()). Is there a function similar to std::mem_func that I can use?
One way is to use a global function that calls your main thread function: class MyThreadClass { public: void main(); // Your real thread function }; void thread_starter(void *arg) { reinterpret_cast<MyThreadClass*>(arg)->main(); } Then, when you want to start the thread: MyThreadClass *th = new MyThreadClass(); p...
456,707
456,820
How to detect launching from a "Startup"-folder shortcut?
I need to add the "Run when Windows starts" option to my program CintaNotes, but do not want to sacrifice the "cleanness" of it: it is a 100% portable freeware and should not leave traces in the system. I've come up with the idea to autodetect running from the Startup shortcut and automatically minimizing to the system...
Your "cleanness" appears to be an artificial construct at best. If you're telling the user to create a shortcut in the start-up folder, you're already leaving a footprint (and, to be honest, there's little difference between "myprog.exe" and "myprog.exe -m"). In that case, there are some easier approaches than automagi...
456,713
456,716
Why do I get "unresolved external symbol" errors when using templates?
When I write C++ code for a class using templates and split the code between a source (CPP) file and a header (H) file, I get a whole lot of "unresolved external symbol" errors when it comes to linking the final executible, despite the object file being correctly built and included in the linking. What's happening her...
Templated classes and functions are not instantiated until they are used, typically in a separate .cpp file (e.g. the program source). When the template is used, the compiler needs the full code for that function to be able to build the correct function with the appropriate type. However, in this case the code for th...
456,738
456,748
Should I add throw() to the declarations for my C++ destructors?
I have seen some C++ classes with a destructor defined as follows: class someClass { public: someClass(); ~someClass() throw(); }; Is this a good idea? I am well aware that destructors should never throw exceptions, but will this actually prevent me from throwing exceptions in my destructors? I'm n...
It does not prevent you from throwing exceptions from your destructor. The compiler will still let you do it. The difference is that if you do allow an exception to escape from that destructor, your program will immediately call unexpected. That function calls whatever unexpected_handler points to, which by default is ...
456,786
456,811
Create thread with >70% CPU utilization
I am creating a test program to test the functionality of program which calcultes CPU Utilization. Now I want to test that program at different times when CPU utilization is 100%, 50% 0% etc. My question how to make CPU to utilize to 100% or may be > 80%. I think creating a while loop like will suffice while(i++< 2000...
You're right to use a loop, but: You've got IO You've got a sleep Basically nothing in that loop is going to take very much CPU time compared with the time it's sleeping or waiting for IO. To kill a CPU you need to give it just CPU stuff. The only tricky bit really is making sure the C++ compiler doesn't optimise awa...
456,884
456,995
Extending python - to swig, not to swig or Cython
I found the bottleneck in my python code, played around with psycho etc. Then decided to write a c/c++ extension for performance. With the help of swig you almost don't need to care about arguments etc. Everything works fine. Now my question: swig creates a quite large py-file which does a lot of 'checkings' and 'PySwi...
For sure you will always have a performance gain doing this by hand, but the gain will be very small compared to the effort required to do this. I don't have any figure to give you but I don't recommend this, because you will need to maintain the interface by hand, and this is not an option if your module is large! You...
456,951
456,990
what is the best way to check the type of base class pointer?
I want to know the runtime type of a base class pointer, I know you can use dynamic_cast. is there any better way?
dynamic_cast will only confirm your guess, and even that is not perfect. If C inherits from B which inherits from A, dynamic_cast<B*>((A*)&theC) will work. typeid will give you the actual type, but in a way that's not quite useful for anything. You can't create new objects of that same type, for instance. So, the biq ...
457,040
457,144
Condition evaluation in loops?
string strLine;//not constant int index = 0; while(index < strLine.length()){//strLine is not modified}; how many times strLine.length() is evaluated do we need to put use nLength with nLength assigned to strLine.length() just before loop
length will be evaluated every time you go via the loop, however since length is constant time (O(1)) it doesn't make much difference and adding a variable for storing this value will probably have a negligible effect with a small hit on code readability (as well as breaking the code if the string is ever changed).
457,441
457,451
Does restrict help in C if a pointer is already marked const?
Just wondering: When I add restrict to a pointer, I tell the compiler that the pointer is not an alias for another pointer. Let's assume I have a function like: // Constructed example void foo (float* result, const float* a, const float* b, const size_t size) { for (size_t i = 0; i < size; ++i) { res...
Your pointer is const, telling anyone calling your function that you won't touch the data which is pointed at through that variable. Unfortunately, the compiler still won't know if result is an alias of the const pointers. You can always use a non-const pointer as a const-pointer. For example, a lot of functions take a...
457,577
457,583
Catching access violation exceptions?
Example int *ptr; *ptr = 1000; can I catch memory access violation exception using standard C++ without using any microsoft specific.
Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.
457,595
529,725
Can you use Boost.Regex to parse a stream?
I was playing around with Boost.Regex to parse strings for words and numbers. This is what I have so far: #include <iostream> #include <string> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/range.hpp> using namespace std; using namespace boost; int main() { regex re ( "(" ...
Boost.IOStreams has a regex_filter allowing one to perform the equivalent of a regex_replace on a stream. However, looking at the implementation, it seems to "cheat" in that it simply loads the whole stream into a buffer and then calls Boost.Regex on that buffer. Making a regex search on a stream's contents without hav...
457,620
457,660
Which character set to choose when compiling a c++ dll
Could someone give some info regarding the different character sets within visual studio's project properties sheets. The options are: None Unicode Multi byte I would like to make an informed decision as to which to choose. Thanks.
All new software should be Unicode enabled. For Windows apps that means the UTF-16 character set, and for pretty much everyone else UTF-8 is often the best choice. The other character set choices in Windows programming should only be used for compatibility with older apps. They do not support the same range of chara...
457,709
458,135
VDMEnumProcessWOW returns no processes on Vista
I'm trying to use VDMEnumProcessWOW to find all 16 bit host processes on Vista. I call it, and it appears to not find any results even though I do have a 16 bit app running. I've also tried calling VDMEnumTaskWOWEx with the process id I got for ntvdm.exe from Windows Task Manager, and that also returns no results. ntvd...
You can request the hotfix through this link.
457,719
457,738
C++ Classes default constructor
Earlier I asked why this is considered bad: class Example { public: Example(void); ~Example(void); void f() {} } int main(void) { Example ex(); // <<<<<< what is it called to call it like this? return(0); } Now, I understand that it's creating a function prototype instead that returns a type Example. I sti...
this question will be helpful to understand this behavior
457,896
457,963
Why is it impossible to have a reference-to-void?
Why is it impossible to have a reference to void? The only thing I found in the C++ Standard is this line, at 8.3.2.1 A declarator that specifies the type "reference to cv void" is ill-formed. Why is it that way? Why can't I write a "generic" function that accept a void&? Just to be clear, I have no useful applicati...
If you did have a reference to void, what would you do with it? It wouldn't be a number, or a character, or a pointer, or anything like that. Your hypothetical generic function couldn't perform any operation on it, except taking its address (and not its size). "void" has two uses: to disclaim any knowledge of type (...
458,032
485,936
How can I add a new button to the navigation pane (outlook bar) in Outlook 2003/2007?
Most of us are familiar with the "accordion-style" navigation bar on the left side of Outlook 2003. It has buttons like Calendar, Tasks, Mail, etc, and clicking on one of those buttons opens up a browser pane with the list of common folders in that section. Using C++ or Delphi, I'd like to write a plugin that adds a n...
This site have info for you : http://www.outlookcode.com/article.aspx?ID=36 Good look.
458,476
458,488
Best way to copy a vector to a list in STL?
Is iterating through the vector using an iterator and copying to a list the most optimal method of copying. Any recommendations?
Why would you iterate and not use the standard copy algorithm? std::copy( vector.begin(), vector.end(), std::back_inserter( list ) );
458,525
458,611
Iterating over vector and calling functions
I have a class that has a vector of another class objects as a member. In many functions of this class I have to do same operation on all the objects in the vector: class Small { public: void foo(); void bar(int x); // and many more functions }; class Big { public: void foo() { for (si...
Well you can rewrite the for loops to use iterators and more of the STL like this: void foo() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::foo)); } void bar() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::bar)); } beyond that, you coul...
458,549
458,567
How does one share data between a C++app and a C# app without files?
I have a C++ application with data that needs to be shared with a C# application. I'm currently transferring the data via files, but with speed and quantity of the data becoming an issue I would like to find a way to share the data through memory. I'm a beginner to intermediate programmer at best, and so far I have hea...
You could use named pipes for interprocess communication. I haven't used it from c++ land yet though..
458,721
458,738
Disadvantages of a <std.h> file that brings in all std headers?
I find long sequences of standard includes annoying: #include <vector> #include <string> #include <sstream> #include <iostream> Considering these header files change only very rarely, is there a reason why I should not make a "std.h" file #including all std headers and just use that everywhere?
Including unnecessary header files will increase compile times.
458,795
458,893
Friend template functions (in non-template classes), C++
If I have a non-template (i.e. "normal") class and wish to have a template friend function, how do I write it without causing a compiler error? Here is an example to illustrate what I am trying to do: template <class T> void bar(T* ptr); class MyClass // note that this isn't a template class { private: void foo(...
Are you sure what you've posted gives the error? The following (using Visual Studio 2005) works fine for me: #include <iostream> template <class T> void bar(T* ptr); class MyClass // note that this isn't a template class { private: void foo(); template <class T> friend void bar(T*); // ERROR: compiler g...
459,107
459,527
.NET marshalling speed
I have a C++ method signature that looks like this: static extern void ImageProcessing( [MarshalAs(UnmanagedType.LPArray)]ushort[] inImage, [MarshalAs(UnmanagedType.LPArray)]ushort[] outImage, int inYSize, int inXSize); I've wrapped the function in timing methods, both internal and external...
The answer is, sadly, far more mundane than these suggestions, although they do help. Basically, I messed up with how I was doing timing. The timing code that I was using was this: Ipp32s timer; ippGetCpuFreqMhz(&timer); Ipp64u globalStart = ippGetCpuClocks(); globalStart = ippGetCpuClocks() *2 - globalStart; //use th...
459,372
459,400
Putting a close button on QTabWidget
I'm using a QTabWidget to render multiple documents in a window, and I want to draw a close button on each tab. I'm using Vista and Qt4, so the tab widget is a native windows control; this may affect the feasibility. Does anyone know if it is possible to do this using the QTabWidget control, or do I have to create a cu...
Currently there is no way to do this with the stock QTabWidget, however the upcoming Qt 4.5 (planned to be released in March 2009) will have the ability to add close buttons to tabs either manually or by setting a QTabBar.TabsClosable property. Until then, the only way to get close buttons is to subclass QTabWidget or ...
459,386
459,413
C++ metaprogramming - generating errors in code
Is there a way that I can create a function that takes an int template parameter, and have that function give a compile time error if the value passed to the function is less than 10? The following code does not work, but it shows what I want to accomplish: template <int number1> void reportErrorIfLessThan10() { #i...
If you don't want Boost C++ Libraries magic and want bare bones... template<bool> class static_check { }; template<> class static_check<false> { private: static_check(); }; #define StaticAssert(test) static_check<(test) != 0>() Then use StaticAssert. It's a #define for me because I have code that needs to run in a ...
459,414
459,421
boost weak_ptr_cast in shared_from_this()
I'm using boost's shared pointers, and enable_shared_from_this to enable returning a shared pointer to this. Code looks like this: class foo : public boost::enable_shared_from_this<foo> { boost::shared_ptr<foo> get() { return shared_from_this(); } } Why would shared_from_this throw a weak_ptr_cast exception...
If you declared foo on the stack, so that there are no other shared pointers to foo. For example: void bar() { foo fooby; fooby.get(); } fooby.get() would throw the weak_ptr_cast exception. To get around this, declare fooby on the heap: void bar() { boost::shared_ptr<foo> pFooby = boost::shared_ptr<foo>(new foo...
459,503
459,535
How can I avoid dynamic_cast in my C++ code?
Let's say I have the following class structure: class Car; class FooCar : public Car; class BarCar : public Car; class Engine; class FooEngine : public Engine; class BarEngine : public Engine; Let's also give a Car a handle to its Engine. A FooCar will be created with a FooEngine* and a BarCar will be created with a...
I'm assuming that Car holds an Engine pointer, and that's why you find yourself downcasting. Take the pointer out of your base class and replace it with a pure virtual get_engine() function. Then your FooCar and BarCar can hold pointers to the correct engine type. (Edit) Why this works: Since the virtual function Car:...
459,649
459,727
Can I simplify this?
typedef void (FunctionSet::* Function)(); class MyFunctionSet : public FunctionSet { protected: void addFunctions() { addFunction(Function(&MyFunctionSet::function1)); } void function1() { // Do something. } }; The addFunction method adds the function to a list in the base cla...
Looks like you assign a member function pointer to a function of the derived class to a member function pointer to a function of the base class. Well, that's forbidden, because it opens up a hole in the type-system. It comes at a surprise (at least for me, the first time i heard that). Read this answer for why. To ans...
459,794
462,420
Why would SDL_Mixer not play music for certain mp3s?
Why would SDL_Mixer not play music for certain mp3s? I am utilizing SDL_Mixer for music playback in an application I am creating. On certain songs (entire albums actually), the music will simply not play without returning any errors. The music data loads successfully using Mix_LoadMUS and when executing Mix_PlayMusic w...
This actually wound up being a sound issue with that particular computer. Upon trying the same tests on another machine, the sound worked flawlessly. Just a quick note in case someone else encounters this issue.
459,901
459,914
window handlers for opengl
I've been programming opengl using glut as my window handler, lately i've been thinking if there are any advantages to switching to an alternate window handler such as wxWidgets or qt. Are there any major differences at all or is it just a matter of taste? Since glut provides some additional functions for opengl-progra...
I can only speak from experiential of using QT: Once you have the basic structure set up then it is a simple case of doing what you have always done: for example, the project I am working on at the moment has an open gl widget embedded in the window. This widget has functions such as initializeGL, resize...paintGL etc....
459,942
459,970
Defining class string constants in C++?
I have seen code around with these two styles , I am not not sure if one is better than another (is it just a matter of style)? Do you have any recommendations of why you would choose one over another. //Example1 class Test { private: static const char* const str; }; const char* const Test::str = "mys...
Usually you should prefer std::string over plain char pointers. Here, however, the char pointer initialized with the string literal has a significant benefit. There are two initializations for static data. The one is called static initialization, and the other is called dynamic initialization. For those objects that a...
460,281
460,298
C++ Forward Declaration Problem when calling Method
I have a problem which I think is related to forward declarations, but perhaps not. Here is the relevant code: A.h #ifndef A_H_ #define A_H_ #include "B.h" class A { private: B b; public: A() : b(*this) {} void bar() {} }; #endif /*A_H_*/ B.h #ifndef B_H_ #define B_H_ #include...
You've got a circular reference, so you need to separate B.h. Try something like: B.h: #ifndef B_H_ #define B_H_ // don't include A.h here! class A; class B { private: A& a; public: B(A& a) : a(a) {} void foo(); }; #endif /*B_H_*/ B.cpp: #include "B.h" #include "A.h" void B::foo() { a.ba...
460,426
460,433
I want to start Qt development - what basic knowledge in C++ and OS do I have to own?
I'm going to learn Qt and I just want to know what parts of C++, OO design and other things I must have background in? Templates, RAII, Patterns, ....?
QT is no different from any other platform or library you can use. To use it properly you only need to know the basics of C++ and how to compile and build your code. This tutorial takes you through the basics of building a QT application. Of course like any other programming endeavor, the more you know about the langua...
460,583
461,292
How can I shift elements inside STL container
I want to shift elements inside container on any positions to the left or right. The shifting elements are not contiguous. e.g I have a vector {1,2,3,4,5,6,7,8} and I want to shift {4,5,7} to the left on 2 positions, the expected result will be {1,4,5,2,7,3,6,8} Is there an elegant way to solve it ?
You can write your own shifting function. Here's a simple one: #include <iterator> #include <algorithm> template <typename Container, typename ValueType, typename Distance> void shift(Container &c, const ValueType &value, Distance shifting) { typedef typename Container::iterator Iter; // Here I assumed that y...
460,613
460,703
#ifdef in switch statement bug?
I have some code that looks like this: someFunc(value) { switch(value){ case 1: case 2: case 3: #ifdef SOMEMACRO case 4: case 5: #endif return TRUE; } return FALSE; } SOMEMACRO is defined, and let's say the value is 4.. Why does case 4 and 5 get skipped and F...
"switch" Isn't Broken to, more or less, quote The Pragmatic Programmer. Go ahead and look somewhere else for the error. To convince yourself add value = 4 and #define SOMEMACRO right there in someFunc. Make a clean build to make sure every dependancy is resolved.
460,666
460,790
decreasing cache misses through good design
How to decrease the number of possible cache misses when designing a C++ program? Does inlining functions help every time? or is it good only when the program is CPU-bounded (i.e. the program is computation oriented not I/O oriented)?
Here are some things that I like consider when working on this kind of code. Consider whether you want "structures of arrays" or "arrays of structures". Which you want to use will depend on each part of the data. Try to keep structures to multiples of 32 bytes so they pack cache lines evenly. Partition your data in h...
460,809
461,174
C++: Dll unloading issue
How can I ensure a dll is not unloaded while any objects in it exist? The problem is, when I was using explict memory management I could delete the dll objects before freeing the dll, however with smart pointers I have no controll over the order there destroyed, meaning the dll may be freed first causeing a crash when ...
Assuming you do not want to terminate the thread when unloading the library (otherwise, see MSalters), you need to free the library from the caller that loaded it. COM solves that by an in-DLL instance counter (much like yours, if I understand you correctly), and regulary checking it by calling a global exported CanUnl...
460,847
460,897
Using std::for_each on polymorphic method in c++
When using the std::for_each, class A; vector<A*> VectorOfAPointers; std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo)); If we have classes inheriting from A and implementing foo(), and we hold a vector of pointers to A, is there any way to call a polymorphic call on foo(), rath...
It actually works this way. #include <algorithm> #include <iostream> #include <functional> #include <vector> struct A { virtual void foo() { std::cout << "A::foo()" << std::endl; } }; struct B: public A { virtual void foo() { std::cout << "B::foo()" << std::endl; } }; int main() { ...
460,869
460,889
for_each on a COM IEnumXxx interface?
I've got a COM object that returns an IEnumUnknown. Is there anything out there that'll turn it into an STL-style iterator? So that I can do something like this: IEnumUnkPtr pEnumUnk; // ...something that fills in pEnumUnk... MagicThing m(pEnumUnk); std::for_each(m.begin(), m.end(), DoSomethingWithUnk); ...or similar?...
Seems like the comstl project has what you need: http://www.stlsoft.org/doc-1.9/classcomstl_1_1enumerator__sequence.html
460,980
460,996
Where can I find the default icons used for folders and applications?
I'm trying to load the default HICON that explorer displays for: An open folder An exe that has no embedded default icon of its own. This can also be seen in 'Add/Remove Programs' or 'Programs and Features' as it's called on Vista. Do you know where these can be found? I think the folder icon might be in the resour...
I think they are in %windir%\system32\SHELL32.dll Found some code in the internet, try if that works: HINSTANCE hDll; hDll = LoadLibrary ( "SHELL32.dll" ); wincl.hIcon = LoadIcon (hDll , MAKEINTRESOURCE ( 1 )); wincl.hIconSm = LoadIcon (hDll, MAKEINTRESOURCE ( 2 )); Edit: Windows has a lot more icons in the "morico...
461,062
461,190
C++ anonymous variables
Why won't this work? 0. #define CONCAT(x, y) x ## y 1. 2. #define VAR_LINE(x) \ 3. int CONCAT(_anonymous, __LINE__) = x 4. 5. #define VAR_LINE2(x) \ 6. int _anonymous ## x = 1 7. 8. int main() 9. { 10. VAR_LINE(1); 11. VAR_LINE(1); 12. VAR_LINE(1); 13. VAR_LINE2(__LINE__); 14. } The...
You need to add a level of indirection so that __LINE__ will be expanded: #define _CONCAT_(x,y) x ## y #define CONCAT(x,y) _CONCAT_(x,y) #define VAR_LINE(x) int CONCAT(_anonymous, __LINE__) = x
461,093
461,107
Viewing compiler expanded code - C++
I learned that compiler will expand macros while compiling. Templates are also expanded at the compile time. Is there any way to see this expanded code? I am compiling using Visual Studio 2008. any thoughts?
The VC++ compiler (cl.exe) supports a few command line switches for this: /E preprocess to stdout /P preprocess to file /EP preproscess to stdout with no #lines Additional command-line switches can be added in your project properties. In my version (VC2005), Configuration Options -> C/C++ -> Command Line -> Additional...
461,203
461,224
When to use virtual destructors?
I have a solid understanding of most OOP theory but the one thing that confuses me a lot is virtual destructors. I thought that the destructor always gets called no matter what and for every object in the chain. When are you meant to make them virtual and why?
Virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class: class Base { // some virtual methods }; class Derived : public Base { ~Derived() { // Do some important cleanup } }; Here, you'll notice that I didn't declare Base'...
461,236
461,250
How to cast a pointer in C++
void foo(void **Pointer); int main () { int *IntPtr; foo(&((void*)IntPtr)); } Why do I get an error? error: lvalue required as unary ‘&’ operand Thanks
(void*) is not an lvalue, it is kind of a casting operator, you need to have the ampersand to the immediate left of the variable (lvalue). This should be right: foo(((void**)&IntPtr));
461,449
461,528
return statement vs exit() in main()
Should I use exit() or just return statements in main()? Personally I favor the return statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having return seems like a better choice tha...
Actually, there is a difference, but it's subtle. It has more implications for C++, but the differences are important. When I call return in main(), destructors will be called for my locally scoped objects. If I call exit(), no destructor will be called for my locally scoped objects! Re-read that. exit() does not retu...
461,507
479,471
How to use BOOST_FOREACH with a boost::ptr_map?
How can I use BOOST_FOREACH efficiently (number-of-character/readability-wise) with a boost::ptr_map? Kristo demonstrated in his answer that it is possible to use BOOST_FOREACH with a ptr_map, but it does not really save me any typing (or makes my code really more readable) than iterating over the ptr_map with an ite...
As STL style containers, the pointer containers have a value_type typedef that you can use: #include <boost/ptr_container/ptr_map.hpp> #include <boost/foreach.hpp> int main() { typedef boost::ptr_map<int, int> int_map; int_map mymap; BOOST_FOREACH(int_map::value_type p, mymap) { } } I find that u...
461,535
461,548
Using an asterisk in a RegExp to extract data that is enclosed by a certain pattern
I have an text that consists of information enclosed by a certain pattern. The only thing I know is the pattern: "${template.start}" and ${template.end} To keep it simple I will substitute ${template.start} and ${template.end} with "a" in the example. So one entry in the text would be: aINFORMATIONHEREa I do not know...
Simply use non-greedy expressions, namely: a(.*?)a
461,580
462,366
Persistence solutions for C++ (with a SQL database)?
I'm wondering what kind of persistence solutions are there for C++ with a SQL database? In addition to doing things with custom SQL (and encapsulating the data access to DAOs or something similar), are there some other (more general) solutions? Like some general libraries or frameworks (something like Hibernate & co fo...
It sounds like you are looking for some ORM so that you don't have to bother with hand written SQL code. There is a post here that goes over ORM solutions for C++. You also did not mention the type of application you are writing, if it is a desktop application, mobile application, server application. Mobile: You are be...
461,711
6,170,155
Dealing with "C compiler cannot create executables" in Cygwin
Whatever I try to compile in Cygwin I get the following output: checking for mingw32 environment... no checking for EMX OS/2 environment... no checking how to run the C preprocessor... gcc -E checking for gcc... gcc checking whether the C compiler (gcc ) works... no configure: error: installation or configuration pr...
Your Configure is wrong. Usually autoreconf -f helps. If not you need to check the failing rule and fix it.
461,773
464,917
What is the easiest way to convert a compressed wav file to an uncompressed wav file in C# or C++?
What is the easiest way to programatically convert a compressed wav file (MPEG codec for example, but could be any installed codec) to an uncompressed wav file (16 bit PCM)? I've heard that using direct show and writing the code in native C++ would do it, but I've not had much experience with direct show. Is there an ...
You can decompress WAV files in C# using any ACM codec installed on your PC using NAudio. Here's some sample code: using (WaveFileReader reader = new WaveFileReader(inputFileName)) { using (WaveStream convertedStream = WaveFormatConversionStream.CreatePcmStream(reader)) { WaveFileWriter.CreateW...
461,836
727,836
Arduino C++ code: can you use virtual functions and exceptions?
Following up on this comment from the question Writing firmware: assembly or high level?: When compiling C++ code for the Arduino platform, can you use virtual functions, exceptions, etc? Or would you want to (have to) use a subset of C++ (as described in the comment)? Any other caveats when programming for the Arduin...
The Arduino environment uses the AVR version of the GCC toolchain. The code is compiled as C++, so you can use classes. Virtual functions are possible; the vtables will be stored in the .data section and have the correct addresses. In fact, the Print base class uses virtual functions to adapt the various "print" met...
461,870
462,001
Selecting an index in a QListView
This might be a stupid question, but I can't for the life of me figure out how to select the row of a given index in a QListView. QAbstractItemView , QListView's parent has a setCurrentIndex(const QModelIndex &index). The problem is, I can't construct a QModelIndex with the row number I want since the row and column fi...
You construct the QModelIndex by using the createIndex(int row, int column) function of the model you gave to the view. QModelIndexes should only be used once, and must be created by the factory in the model.
461,918
462,242
Is that a good idea to define exception with template?
I am thinking is that a good idea to define exception with template. Defining different types of exception is a super verbose task. You have to inherit exception, there is nothing changed, just inherit. Like this.. class FooException : public BaseException { public: ... }; class BarException : public BaseException...
It's definitely possible and works fine, but i would avoid it. It obscures diagnostics. GCC will display the name of the exception type, with the usual template stuff included. I would take the few minutes to define the new exception class, personally. It's not like you would do it all the time.
461,981
462,046
Destructor vs member function race
When I'm inside a destructor is it possible that some other thread will start executing object's member function? How to deal with this situation?
C++ has no intrinsic protection against using an object after it's been deleting - forget about race conditions - another thread could use your object after it's been completely deleted. Either: Make sure only one place in the code owns the object, and it's responsible for deleting when no-one is using the object. Mak...
462,160
462,441
Launching a C++ executable from a C# app and keeping role based security context
First off I know this is probably a tall order but... :) We have some software that interacts with the hardware our company produces. This software loads a .NET assembly and this acts as our interface to the hardware. Currently we have a 'Launcher' application written in C# which provides role based security. This 'La...
You would have to modify the C++ application to check the roles as well. If you can do that, you might consider breaking up part of your C# application into multiple assemblies. Specifically, take the roles part the C# application, and compile that as a dll with COM/ActiveX extensions. Then you can call the C# dll (vi...
462,165
462,203
error: ‘NULL’ was not declared in this scope
I get this message when compiling C++ on gcc 4.3 error: ‘NULL’ was not declared in this scope It appears and disappears and I don't know why. Why? Thanks.
NULL is not a keyword. It's an identifier defined in some standard headers. You can include #include <cstddef> To have it in scope, including some other basics, like std::size_t.
462,180
462,739
Why doesn't C++ have a pointer to member function type?
I could be totally wrong here, but as I understand it, C++ doesn't really have a native "pointer to member function" type. I know you can do tricks with Boost and mem_fun etc. But why did the designers of C++ decide not to have a 64-bit pointer containing a pointer to the function and a pointer to the object, for exam...
@RocketMagnet - This is in response to your other question, the one which was labeled a duplicate. I'm answering that question, not this one. In general, C++ pointer to member functions can't portably be cast across the class hierarchy. That said you can often get away with it. For instance: #include <iostream> usin...
462,252
462,271
Using static vs. member find method on a STL set?
I am using a set because, i want to use the quick look up property of a sorted container such as a set. I am wondering if I have to use the find member method to get the benefit of a sorted container, or can I also use the static find method in the STL algorithms? My hunch is that using the static version will use a l...
You are right that the non-member version does a linear search, while the member version will do a O(log N) search. std::set is optimized for O(log N) insertion, retrieval and deletion. As a point of definition, the std::find method is not a static function. See here for a description of the various things static can...
462,860
472,175
C++ Library for image recognition: images containing words to string
Does anyone know of a c++ library for taking an image and performing image recognition on it such that it can find letters based on a given font and/or font height? Even one that doesn't let you select a font would be nice (eg: readLetters(Image image).
I've been looking into this a lot lately. Your best is simply Tesseract. If you need layout analysis on top of the OCR than go with Ocropus (which in turn uses Tesseract to do the OCR). Layout analysis refers to being able to detect position of text on the image and do things like line segmentation, block segmentation,...
462,924
463,399
There is really something like Objective C++?
I'm reading a post about iPhone programming and I've noticed that the talk about Objective C++, the code shown in the post looks mainly like Objective-C but there also are several snippets in C++. Is it really possible to program Cocoa from C++?
In addition to the other comments, I would add that Objective-C++ is not exactly the same as "program Cocoa from C++" because there is no C++ to Cocoa bridge involved. In Objective-C++, you program the Cocoa API entirely with Objective-C objects/syntax. The Cocoa API remains unchanged, so you need to communicate with i...
462,982
473,107
Putting a CGImageRef on the clipboard
I'm trying to copy a CGImageRef to the clipboard pasteboard. I found a function that claims it should do this by creating a destination from (zero sized), adding the image to the destination, finalizing, then PasteboardPutItemFlavor the ref into the clipboard. However it doesn't work, so two questions: Is this the cor...
Ok, I'm answering my own question here, but here's what I've found: Apple wants you to use PDF for pasteboards. So if you swap out Pict with PDF, it pretty muc just works. However, MS Word (what I was testing with) only started to allow pasting of PDF in the newest version (Which I don't have). So, that's the solutio...
463,020
463,127
How can I get and set the 'read-only' property of an edit box?
How can I get and set the 'read-only' property of an edit box?
The CEdit class has a SetReadOnly method which can be called at run-time. Details on MSDN: http://msdn.microsoft.com/en-gb/library/aa279328(VS.60).aspx
463,240
463,269
What is the best way to pass information from java to c++?
I have a java application I need to pass some info to a C++ program. It has been suggested that I use some simple socket programming to do this. Is this the best way? If not what are the alternatives? If so, how should I go about learning about socket programming?
You have a few options: Pass a file from Java to C++. This is probably simplest. It's easy to test and shouldn't require any 3rd party libraries on either end. Use sockets as mentioned. In C++, if you require a cross-platform solution a library such as ACE or boost will save you some heartache Use JNI to call from Jav...
463,708
464,014
Wireless debugging of windows mobile applications
I'm trying to debug a windows mobile aplication using a wifi connection, on a Vista with Visual Studio 2008 following this instruction http://blogs.msdn.com/vsdteam/archive/2005/04/28/413304.aspx. It worked flawlessly with XP SP2, but not with Vista. Do you know if this is possible at all? or is another flaw from Vista...
It should work fine. I debug to a CE 5.0 device from Studio '08 on Vista quite regularly. I use the same general outline of steps (though i do use a tool that automates the process).
464,000
464,156
Simple Dynamic Graph Display for C++
I am looking for a simple graph layout library for C++. I want to embed the library into our visualizer based on wxWidgets. In summary, I am looking for something like graphviz, except dynamic - that is when an event occurs, only the change in graph needs to be loaded, not the complete display. There is dynagraph, but ...
The layout that Graphviz generates is based on the global structure - any single addition can dramatically change the output (unless you're using fixed coordinates, in which case you probably wouldn't be asking this question). Basically, if you want automatic placement of elements, you need to accept one of these solu...
464,143
464,159
Why doesnt Multi Args in constructor work under linux?
For my exception class i have a constructor that has multi arguments (...) which works fine under windows, how ever, under linux it compiles fine but refuses to link to it. Why does this not work under linux? here is an example: class gcException { public: gcException() { //code here } gcExcep...
It compiles and links just fine. I expanded your test code to a full "program": class gcException { public: gcException() { } gcException(int errId, const char* format, ...) { } }; int main() { new gcException(1, "foo", "bar", "baz"); } And then g++ -Wall test.cpp ran without errors. According to g...
464,560
464,595
How to use #include directive correctly?
Is there any material about how to use #include correctly? I didn't find any C/C++ text book that explains this usage in detail. In formal project, I always get confused in dealing with it.
Check Large-Scale C++ Software Design from John Lakos if you have the money. Google C++ coding guidelines also have some OK stuff. Check Sutter Herb materials online (blog) as well. Basically you need to understand where include headers are NOT required, eg. forward declaration. Also try to make sure that include fil...
464,618
464,676
What's the equivalent of Windows' QueryPerformanceCounter on OSX?
I'm porting a library from Windows to *NIX (currently OSX), does anyone now what function can I use instead of Microsoft's QueryPerformanceCounter and QueryPerformanceFrequency?
http://www.tin.org/bin/man.cgi?section=3&topic=clock_gettime (and the other functions mentioned there) - it's Posix! Will fall back to worse counters if HPET is not existent. (shouldn't be a problem though) http://en.wikipedia.org/wiki/High_Precision_Event_Timer Resolution should be about +10Mhz.
464,675
465,500
CListCtrl - how to enable multiple selection
I am creating a MFC application for Windows Mobile and don't know how to enable multiple selection for List Control (CListCtrl). In properties panel Single Selection is set to False but still can't select multiple items. Any idea?
I have never targeted Windows Mobile but you might try the following: list.ModifyStyle(LVS_SINGLESEL, 0);
464,788
464,796
Port Mingw32 based code to msvc2008
We recently had a new requirement to use the phonon component of Qt, which on windows requires Visual Studio. I installed VS2008 and ran a compile. There are a stack of problems due to make not working anything like nmake. Since I need to maintain cross-platform I want to test which compiler is being used so that I ca...
Use the _MSC_VER macro. If it is defined, you're using Visual Studio: #ifdef _MSC_VER ... MSVC code ... #else ... other compiler ... #endif
464,843
464,916
C++ 3D Model Animation libraries?
I have my own game engine using C++ and OpenGL, but I have models with individual pieces that can be moved, and Im not sure how to animate them without hardcoding it. Are there any libraries that would provide a solution via scripts or IK or some other animation technique without resorting to a game engine such as Ogre...
Cal3d could be an option. Skinned character animation without needing to import a whole engine.
465,345
466,874
How do you create a COM DLL in Visual Studio 2008?
It's been ages since I've written a COM dll. I've made a couple of classes now, that inherit from some COM interfaces, but I want to test it out. I know I have to put a GUID somewhere and then register it with regsvr32, but what are the steps involved? Edit: Sorry, forgot to mention I'm using C++.
To create a new ATL COM project you can proceed as follow: File/New Project Visual C++/ATL/ATL Project Customize it settings, and press finish when done You have created a new dll, but it is empty, to add a COM object you can do this: Project/Add Class Visual C++/ATL/ATL simple object, press add Give the name you wa...
465,388
465,403
C++. Is it possible that a RNG gives different random variable in two different machines using the same seed?
I have this long and complex source code that uses a RNG with a fix seed. This code is a simulator and the parameters of this simulator are the random values given by this RNG. When I execute the code in the same machine, no matter how many attempts I do the output is the same. But when I execute this code on two diffe...
It is certainly possible, as the RNG may be combining machine specific data with the seed, such as the network card address, to generate the random number. It is basically implementation specific.
465,517
465,594
overloaded increment's return value
In his The C++ Programming Language Stroustrup gives the following example for inc/dec overloading: class Ptr_to_T { T* p; T* array ; int size; public: Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p Ptr_to_T(T* p); // bind to single object, initial value p Ptr_to_T& o...
To understand better, you have to imagine (or look at) how are these operators implemented. Typically, the prefix operator++ will be written more or less like this: MyType& operator++() { // do the incrementation return *this; } Since this has been modified "in-place", we can return a reference to the instance...
465,693
465,744
What garbage collectors are there available for C++?
What garbage collectors are there available for C++? Are you using any of them? With what results?
The Boost library includes some shared_ptr stuff that basically acts as a reference counting garbage collector. If you embrace the RAII principle of C++ design, that and auto_ptr will fill your need for a "garbage collector".
466,143
466,246
QCompleter and QLineEdit for multiple words
Is there any way to have the QCompleter to act like an autocomplete for multiple words? Someone has any idea how to do it?
I don't know if I understand correctly: QStringList wordList; wordList << "alpha and beta" << "omega" << "omicron" << "zeta"; QCompleter *completer = new QCompleter(wordList, this); completer->setCaseSensitivity(Qt::CaseInsensitive); QLineEdit *lineEdit = new QLineEdit(this); lineEdit->setCompleter(completer); If yo...
466,285
470,268
Availability of #include <map> with xlC on AIX 4.3
Is there a version of xlC/VACPP available for AIX 4.3, which does not choke when given following source: #include <map> int main(void) { return 0; } If yes, is it still available anywhere?
You might want to try using STLport as a replacement for the STL shipped with the compiler.
466,377
466,389
How to detect what CPU is being used during runtime?
How can I detect which CPU is being used at runtime ? The c++ code needs to differentiate between AMD / Intel architectures ? Using gcc 4.2.
If you're on Linux (or on Windows running under Cygwin), you can figure that out by reading the special file /proc/cpuinfo and looking for the line beginning with vendor_id. If the string is GenuineIntel, you're running on an Intel chip. If you get AuthenticAMD, you're running on an AMD chip. void get_vendor_id(char ...
466,488
466,531
Printing detailed debugging output easily?
I'm basically looking for a way to automate typing stuff like the following: cout << "a[" << x << "][" << y << "] =\t" << a[x][y] << endl; Something like: PRINTDBG(a[x][y]); Ideally this would also work for PRINTDBG(func(arg1, arg2)); and even PRINTDBG(if(condition) func(foo);); (which would print e.g. "if(false) f...
This is, in the way you want it, not possible. If you have if(condition) func(foo); given to a macro, it can stringize that stuff, and it will print if(condition) func(foo);, but not with the actual values of the variables substituted. Remember the preprocessor doesn't know about the structure about that code. For deb...