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
351,806
351,894
Where is the Don't Fragment Bit of the IP Flags used?
I am curious to know where the "Don't Fragment" [DF] Bit of the IP Flags is used. As fragmentation is invisible to higher layers and they don't care too. I am also looking for an example. Thanks a lot in advance.
Fragmentation is not always invisible to all upper layers. Some early (and probably even current) micro-controller TCP/IP stacks did not implement the full capabilities such as fragmentation handling. Use of the flag in that situation would ensure that the packet arrived in its original form instead of a lot of fragmen...
351,845
351,865
Finding the type of an object in C++
I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B. What is the best way to fin...
dynamic_cast should do the trick TYPE& dynamic_cast<TYPE&> (object); TYPE* dynamic_cast<TYPE*> (object); The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast. If you attempt to cast to pointer to a type that is not a type of...
351,864
352,920
Porting C++ lib/app on android
I want to port few C/C++ libraries to Android, how feasible it would be e.g. OpenSSL can it be ported or suppose an application which depends on OpenSSL, what is the best way to port it to Android when Android I think itself has libssl.so what are the tools available e.g. Scratchbox, any alternatives? Has anybody exper...
The android internals wiki is a good starting point, and includes a link explaining how to compile simple native applications. Scratchbox does seem to be the way to go for compiling more complex apps & libraries, as you probably know already. I would suggest contacting those folks to get a bearing on your OpenSSL proje...
352,152
352,235
Is there a dereference_iterator in the STL?
I was wondering if there is an iterator in the STL that dereferences the object pointed before returning it. This could be very useful when manipulating containers aggregating pointers. Here's an example of what I would like to be able to do: #include <vector> #include <iterator> #include <algorithm> using namespace s...
Try Boost's indirect_iterator. An indirect_iterator has the same category as the iterator it is wrapping. For example, an indirect_iterator<int**> is a random access iterator.
352,236
360,247
Reading from a text field in another application's window
Is there a way for a Windows application to access another applications data, more specifically a text input field in the GUI, and grab the text there for processing in our own application? If it is possible, is there a way to "shield" your application to prevent it? EDIT: The three first answers seem to be about gett...
For reading text content from another application's text box you will need to get that text box control's window handle somehow. Depending on how your application UI is designed (if it has a UI that is) there are a couple of different ways that you can use to get this handle. You might use "FindWindow"/"FindWindowEx"...
352,341
352,583
Multiple Integer-type classes in C++
I often find myself using Integers to represent values in different "spaces". For example... int arrayIndex; int usersAge; int daysToChristmas; Ideally, I'd like to have separate classes for each of these types "Index","Years" and "Days", which should prevent me accidentally mixing them up. Typedefs are a help from a ...
You could try BOOST_STRONG_TYPEDEF. From boost/strong_typedef.hpp: // macro used to implement a strong typedef. strong typedef // guarentees that two types are distinguised even though the // share the same underlying implementation. typedef does not create // a new type. BOOST_STRONG_TYPEDEF(T, D) creates a new typ...
352,420
352,426
what is the difference between stringstream clear and str
I just wanted to know what's the difference between clear() and str(""); For example: stringstream ss("Stack Overflow"); ss.clear(); ss.str(""); I wanted to know the underlying technical difference.
clear() clears the error state flags in the stringstream. That is to say it sets the error state to goodbit(which is equal to zero). str("") sets the associated string object to the empty string. They actually do completely different things. The peculiar choice of names only make it sound as though they perform similar...
352,758
358,277
How to access to parent widget on qt?
I have an inherited QTreeWidget (called PackList) class and its parent is a KXmlGuiWindow. How can I access to the parent's slots? I've tried getParent()->mySlot() from the QTreeWidget class but I've got error: no matching function for call to 'PackList::mySlot()' Does anybody know the correct way? Thanks
If you know the parent's class, you will have to cast parentWidget() to that class and then call your slot. Keep in mind whether or not it's a slot makes no difference in this case. You are just calling a method. ((KXmlGuiWindow*)parentWidget())->mySlot(); You can make the call without casting by wiring up your signal...
352,885
352,972
Dependency injection in C++
This is also a question that I asked in a comment in one of Miško Hevery's google talks that was dealing with dependency injection but it got buried in the comments. I wonder how can the factory / builder step of wiring the dependencies together can work in C++. I.e. we have a class A that depends on B. The builder wil...
This talk is about Java and dependency injection. In C++ we try NOT to pass RAW pointers around. This is because a RAW pointer have no ownership semantics associated with it. If you have no ownership then we don't know who is responsible for cleaning up the object. I find that most of the time dependency injection is d...
353,038
353,070
_endthreadex(0) hangs
I have some code which I did not originally create that uses _beginthreadex and _endthreadex. For some reason, when it calls _endthreadex(0), the call just hangs and never returns. Any ideas as to what would normally cause this call to hang?
_endthreadex ends the thread, so it can't return. That's the whole point of calling it. EDIT: It's a bit unusual to call _endthreadex, normally you just let the thread start procedure return and the runtime calls _endthreadex for you. You may need to explain a bit more, what you are trying to do before we can help.
353,180
353,217
How do I find the name of the calling function?
I have been using PRETTY_FUNCTION to output the current function name, however I have reimplemented some functions and would like to find out which functions are calling them. In C++ how can I get the function name of the calling routine?
Here are two options: You can get a full stacktrace (including the name, module, and offset of the calling function) with recent versions of glibc with the GNU backtrace functions. See my answer here for the details. This is probably the easiest thing. If that isn't exactly what you're looking for, then you might tr...
353,226
353,302
Facial recognition/merging software
Can anyone point me in the right direction of some facial recognition libraries & algorithms ? I've tried searching/googling but i mostly find thesises and very little real software.
How about Eigenfaces? Utilizes simple mathematics to store recognizable eigenvector of the face and reconstruct faces using multiple vectors. The code is all available in Python as well here.
353,296
353,334
Best way to in situ delete an element
I have a set of objects which I iterate through, however I may decide during the iteration that one (or more) of those objects now need to be deleted. My code goes as follows: if( ! m_Container.empty() ) { for( typedefedcontainer::iterator it = m_Container.begin(); it != m_Container.end(); ...
It depends on the container. The list container supports deletion during enumeration by returning a new iterator from the erase method that represents the next item in the list. map doesn't support this. A simple method for map is to accumulate the items you want to erase in a separate list, and then iterate over tha...
353,464
15,201,457
Verbatim Literals in Managed C++? (like C#'s @"blah")
Is there a way to use verbatim String literals in managed C++? Similar to C#'s String Docs = @"c:\documents and settings\"
in C++11, there is raw string literal: cout<<R"((\"ddd\aa)\n)"<<endl; cout<<R"delimiter((\"ddd\aa)\n)delimiter"<<endl; output is: (\"ddd\aa)\n (\"ddd\aa)\n
353,550
353,640
Prevent creation of class whose member functions are all static
All the member variables and member functions in my class ClassA are static. If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user fro...
Like others said, a namespace is what you should use. If you want to stay with your class, create a class that has a private constructor, and derive from it, to make your intention obvious: class NonConstructible { NonConstructible(); }; class SuperUtils: NonConstructible { static void foo(); // ... s...
353,632
353,659
Why use = to initialise a primitive type in C++?
Where I work, people mostly think that objects are best initialised using C++-style construction (with parentheses), whereas primitive types should be initialised with the = operator: std::string strFoo( "Foo" ); int nBar = 5; Nobody seems to be able to explain why they prefer things this way, though. I can see that ...
Unless you've proven that it matters with respect to performance, I wouldn't worry about an extra copy using the assignment operator in your example (std::string foo = "Foo";). I'd be pretty surprised if that copy even exists once you look at the optimized code, I believe that will actually call the appropriate parame...
353,634
353,705
Are there any downsides to using UPX to compress a Windows executable?
I've used UPX before to reduce the size of my Windows executables, but I must admit that I am naive to any negative side effects this could have. What's the downside to all of this packing/unpacking? Are there scenarios in which anyone would recommend NOT UPX-ing an executable (e.g. when writing a DLL, Windows Service,...
... there are downsides to using EXE compressors. Most notably: Upon startup of a compressed EXE/DLL, all of the code is decompressed from the disk image into memory in one pass, which can cause disk thrashing if the system is low on memory and is forced to access the swap file. In contrast, with uncompressed EXE/DLL...
353,694
353,725
How to cast QVariant to custom class?
I have a QVariant object within a QTreeWidgetItem, how can I cast it to my own object?
you need to declare somewhere in an .h file the following: Q_DECLARE_METATYPE(MyStruct) and then you can just use: MyStruct s; QVariant var; var.setValue(s); // copy s into the variant // retrieve the value MyStruct s2 = var.value<MyStruct>(); see the docs here
353,817
353,890
Should every class have a virtual destructor?
Java and C# support the notion of classes that can't be used as base classes with the final and sealed keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not? Edit: Since C++11 this is...
The question is really, do you want to enforce rules about how your classes should be used? Why? If a class doesn't have a virtual destructor, anyone using the class knows that it is not intended to be derived from, and what limitations apply if you try it anyway. Isn't that good enough? Or do you need the compiler to...
354,329
354,343
Anyone know where a good windows constant list lives
I'm trying to set an invalid value to -1.. But I don't like magic numbers.. Anyone know where to find a set of common constants. I'm working in VS6 (ish). I'm trying to read a file from across a network, and I need a bad value for the total file size,so I know if I got valid info on it.. 0 is a valid size so I can't u...
#define BAD_VALUE -1 EDIT: the original question had no context. The revised question indicates you want an invalid file size and are thus looking for the win32 constants. Look at windows.h i think the constant you seek may be in windows.h or one of its sub-includes. grep your windows include directory ;-)
354,442
354,481
Looking for C++ STL-like vector class but using stack storage
Before I write my own I will ask all y'all. I'm looking for a C++ class that is almost exactly like a STL vector but stores data into an array on the stack. Some kind of STL allocator class would work also, but I am trying to avoid any kind of heap, even static allocated per-thread heaps (although one of those is my s...
You don't have to write a completely new container class. You can stick with your STL containers, but change the second parameter of for example std::vector to give it your custom allocator which allocates from a stack-buffer. The chromium authors wrote an allocator just for this: https://chromium.googlesource.com/chro...
354,607
504,085
How to get the document CDHtmlDialog after Asp.Net AJAX UpdatePanel
When the page displayed in our CDHtmlDialog does an Asp.Net AJAX UpdatePanel we get a navigate event, but everything after that seems to be lost. We don't have a document anymore or get any mouse events on the page.
Looks like I made the original post as an unregistered user, so I don't think I can edit it. We were able to work around the original issue, but it came up again in a different context (really starting to hate CDHTMLDialog). Here is the cause of the problem: Javascript calls are causing a Navigate event, and CDHtmlDial...
354,613
354,621
convert bitmap to byte array
How can I convert a bitmap to a byte array in c++ WITHOUT the .net framework?
If you’re using Windows, you can use GetDIBits to retrieve the bitmap data.
355,258
355,302
Why must const members be initialized in the constructor initializer rather than in its body?
Why must class members declared as const be initialized in the constructor initializer list rather than in the constructor body? What is the difference between the two?
In C++, an object is considered fully initialised when execution enters the body of the constructor. You said: "i wanted to know why const must be intialized in constructor initializer list rather than in it's body ?." What you are missing is that initialisation happens in the initialisation list, and assignment...
355,650
412,985
C++ HTML template framework, templatizing library, HTML generator library
I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc. It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc. Parameter passing to template rendering engine is also important if I could pass all of them i...
A quick review of the mentioned project. http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language ClearSilver Site: http://www.clearsilver.net Project: https://code.google.com/p/clearsilver/ Group: http://tech.groups.yahoo.com/group/ClearSilver License: New BSD License Language: C Last Upd...
355,690
1,771,896
Symbian C++ STOMP library
I want my S60 Application to utilize the Stomp protocol. Although it would be fairly simple to implement myself (but nothing is ever as simple as I hope with Symbian) - I am wondering if anyone has any experience in this already. It seems a Stomp library exists in almost every other language already. The closest match ...
In case this is still relevant - I've just finished my implementation of a STOMP client for Symbian, fully using the Active Scheduler framework. We're going to release it as opensource once I get something set up on Google Code. As Adam says - the implementation needed to be purely within the Symbian framework or it wo...
355,958
416,820
How to detect deadlock whith Asio library?
i have little problem with boost::asio library. My app receive and process data asynchronously, it create threads and run io_service.run() on each of them. boost::asio::io_service io; boost::thread_group thread_pool; ... int cpu_cnt = get_cpu_count(); for (int i = 0; i < cpu_cnt; ++i) { thread_pool.create_thread( b...
I may be wrong, but would the use an io_service per thread solve your problem? Another idea: post cpu_cnt times reply_to_supervisor calls that use a little sleep() - not nice, but should work
356,002
357,043
How to erase elements from boost::ptr_vector
So I'm trying to get rid of my std::vector's by using boost::ptr_vector. Now I'm trying to remove an element from one, and have the removed element deleted as well. The most obvious thing to me was to do: class A { int m; }; boost::ptr_vector<A> vec; A* a = new A; vec.push_back(a); vec.erase(a); But this won't even c...
Well you can do that with a std::vector either. In both cases erase takes an iterator as a parameter. So before you can erase something from a vector (or a ptr_vector) you need to locate it. Also note that the ptr_vector treats its content as if you have stored an object not a pointer. So any searching is done via the ...
356,726
356,728
Is 'bool' a basic datatype in C++?
I got this doubt while writing some code. Is 'bool' a basic datatype defined in the C++ standard or is it some sort of extension provided by the compiler ? I got this doubt because Win32 has 'BOOL' which is nothing but a typedef of long. Also what happens if I do something like this: int i = true; Is it "always" guara...
bool is a fundamental datatype in C++. Converting true to an integer type will yield 1, and converting false will yield 0 (4.5/4 and 4.7/4). In C, until C99, there was no bool datatype, and people did stuff like enum bool { false, true }; So did the Windows API. Starting with C99, we have _Bool as a basic data typ...
356,950
356,993
What are C++ functors and their uses?
I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?
A functor is pretty much just a class which defines the operator(). That lets you create objects which "look like" a function: // this is a functor struct add_x { add_x(int val) : x(val) {} // Constructor int operator()(int y) const { return x + y; } private: int x; }; // Now you can use it like this: add_x ad...
357,243
357,327
I think STL is causing my application triple its memory usage
I am inputting a 200mb file in my application and due to a very strange reason the memory usage of my application is more than 600mb. I have tried vector and deque, as well as std::string and char * with no avail. I need the memory usage of my application to be almost the same as the file I am reading, any suggestions ...
Your memory is being fragmented. Try something like this : HANDLE heaps[1025]; DWORD nheaps = GetProcessHeaps((sizeof(heaps) / sizeof(HANDLE)) - 1, heaps); for (DWORD i = 0; i < nheaps; ++i) { ULONG HeapFragValue = 2; HeapSetInformation(heaps[i], HeapCompatibilityInformation, ...
357,307
357,380
How to call a parent class function from derived class function?
How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. H...
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private). If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons ...
357,404
357,464
Why are unnamed namespaces used and what are their benefits?
I just joined a new C++ software project and I'm trying to understand the design. The project makes frequent use of unnamed namespaces. For example, something like this may occur in a class definition file: // newusertype.cc namespace { const int SIZE_OF_ARRAY_X; const int SIZE_OF_ARRAY_Y; bool getState(userTyp...
Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace: namespace unique { /* empty */ } using namespace unique; namespace unique { /* namespace body. stuff in here */ } The extra step using the empty body is ...
357,481
357,551
writing 2d arrays to output files - c++
I'm trying to write a 2d array into an output file, it's all working fine except in creating the .getline function to draw the array back out of the file. My issue is putting the string length. My current code for the line is; inputFile.getline(myArray, [10][10], '\n'); but it doesn't like having the string length in s...
For that to compile, myArray must be an array of char, or a char*. In particular, it is a one-dimensional array. To read multiple dimensions, you'll need to read each row separately. The second parameter to std::istream::getline is the maximum number of chars to read and store in the array, minus one. To begin reading ...
357,564
358,823
Uses for anonymous namespaces in header files
Someone asserted on SO today that you should never use anonymous namespaces in header files. Normally this is correct, but I seem to remember once someone told me that one of the standard libraries uses anonymous namespaces in header files to perform some sort of initialization. Am I remembering correctly? Can someon...
The only situation in which a nameless namespace in header can be useful is when you want to distribute code as header files only. For example, a large standalone subset of Boost is purely headers. The token ignore for tuples, mentioned in another answer is one example, the _1, _2 etc. bind placeholders are others.
357,629
357,638
How do you find the range of values that integer types can represent in C++?
The size and range of the integer value types in C++ are platform specific. Values found on most 32-bit systems can be found at Variables. Data Types. - C++ Documentation. How do you determine what the actual size and range are for your specific system?
C Style limits.h contains the min and max values for ints as well as other data types which should be exactly what you need: #include <limits.h> // C header #include <climits> // C++ header // Constant containing the minimum value of a signed integer (–2,147,483,648) INT_MIN; // Constant containing the maximum value...
357,898
381,321
How to reload a 3rd party DLL that crashes often
I'm using a 3rd party DLL written in unmanaged C++ that controls some hardware we have. Unfortunately this DLL crashes now and then and I've been tasked to make it "reload" automagically. I'm not too sure about how to proceed to get best results. My project uses C++.Net 2.0 (2005). I'm wrapping the 3rd party stuff in a...
The most effective approach will be to not load that DLL in your application's process at all. Instead, create a second process whose only job is to use that DLL on behalf of your application. You can use a shared memory region, local socket, or other IPC mechanism to control the proxy process. This way, when the pro...
357,963
358,115
std::ifstream::open() not working
I am developing a prototype for a game, and certain gameplay rules are to be defined in an ini file so that the game designers can tweak the game parameters without requiring help from me in addition to a re-compile. This is what I'm doing currently: std::ifstream stream; stream.open("rules.ini"); if (!stream.is_open(...
You are assuming that the working directory is the directory that your executable resides in. That is a bad assumption. Your executable can be run from any working directory, so it's usually a bad idea to hard-code relative paths in your software. If you want to be able to access files relative to the location of your...
358,533
358,581
How important is Boost to learn for C++ developers?
I am curious to learn Boost. But I wanted to ask: How important is it to make the effort to learn Boost? What prerequisites should one have before jumping on Boost? Why I am curious to know about Boost is that many people are talking about Boost on IRC's channels and here in StackOverflow.
I think anyone that is seriously considering C++ development as a career should learn Boost, and learn it well. Once you get into serious programming you will realize how beneficial these libraries can be and how much more productive they can make you. Not only are they cross-platform, but once you get into data crunch...
358,972
359,279
Unwanted xmlns="" in _di_IXMLNode
I'm creating a xml-file for display in Excel using _di_IXMLDocument. But for some tags I get an unwanted extra (empty) xmlns attribute witch makes the file unreadable for Excel... This is what i do: ... _di_IXMLNode worksheet = workbook->AddChild("Worksheet"); worksheet->SetAttribute("ss:Name",Now().DateString()); ... ...
Ok I had a look at this question. The trick was to create the child nodes and telling the what namespace they belong to, and then not to output it... _di_IXMLNode worksheet = workbook->AddChild("Worksheet","workbooks-namespace",false); worksheet->SetAttribute("ss:Name",Now().DateString()); this produces the desired ou...
359,084
359,558
How to capture high resolution image on Windows Mobile
I would like to capture high resolution image with Windows Mobile device. I've tried the example from WM SDK, but it captures just a single frame of video camera and the resolution is poor. Has anyone any experience with image capturing on Pocket PC with C++? Thanks
You need to change the filter used by the example code to capture a high-resolution image. When you use the viewfinder in a digital camera, the camera "simulates" a video camera look by applying the lowest resolution filter and then rapidly taking and displaying single frames. When you click the button to take a high...
359,732
359,753
Why is it considered a bad practice to omit curly braces?
Why does everyone tell me writing code like this is a bad practice? if (foo) Bar(); //or for(int i = 0 i < count; i++) Bar(i); My biggest argument for omitting the curly braces is that it can sometimes be twice as many lines with them. For example, here is some code to paint a glow effect for a label in C#. ...
Actually, the only time that's ever really bit me was when I was debugging, and commented out bar(): if(foo) // bar(); doSomethingElse(); Other than that, I tend to use: if(foo) bar(); Which takes care of the above case. EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common...
359,885
362,100
Symbian C++ - S60 application launches through TRK and Carbide, but not afterwards or when downloaded
My application has just started exhibiting strange behaviour. I can boot it through the Carbide Debugger (using TRK) and it works fine with no visible errors and is left installed on the device. Any further attempts to launch the application fail, even after a restart. Uninstalling and downloading the .sisx file manual...
You should install ErrRd sis file to enable your phone to show extended panics - maybe this will give you some hints. If you get "Menu -1" then most probably you are missing some resource file or library. Also if you use DLL files then check that they have at least the same capabilities than your EXE file.
359,928
365,738
Which C++ signals/slots library should I choose?
I want to use a signals/slots library in a project that doesn't use QT. I have pretty basic requirements: Connect two functions with any number of parameters. Signals can be connected to multiple slots. Manual disconnection of signal/slot connection. Decent performance - the application is frame-based (i.e. not event...
First, try with boost::signal anyway. Don't assume it will not be fast enough until you try in your specific case that is your application If it's not efficient enough, maybe something like FastDelegate will suit your needs? (i did'nt try it but heard it was a nice solution in some cases where boost::signal don't seem ...
359,992
360,032
S60 application - Symbian C++ - Exit button doesn't work
In my Symbian S60 application, my Options menu works as expected. But the Exit button does nothing. I am developing with Carbide and have used the UI Designer to add items to the options menu. Does anyone know how to enable the exit button, or why else it might not work? Thanks!
Are you handling (in your appui::HandleCommandL) command ids EEikCmdExit and EAknSoftkeyExit? if ( aCommand == EAknSoftkeyExit || aCommand == EEikCmdExit ) { Exit(); }
360,154
360,190
Native C++ SQL Framework
I need a high performance framework in native C++ for SQL. I need it to be able to use MySQL, Oracle and Microsoft SQL Server and provide abstraction from the lower level problems/idiosyncrasies found in every different syntax required for by DBMS from different vendors. Something like LINQ for C# and VB .Net.
I believe that Qt has at least some of what you're looking for
360,338
360,372
C#/Java programmer learning C++ again. Project file structure?
As the question states, i am a C#/Java programmer who is interested in (re)learning C++. As you know C#/Java have a somewhat strict project file structure (especially Java). I find this structure to be very helpful and was wondering if it is a) good practice to do a similar structure in a C++, b) if so, what is the bes...
I find the structure of java projects quite nice. I do it like this (root is the root directory) root/include/foo/bar/baz.hpp becomes namespace foo { namespace bar { // declare/define the stuff (classes, functions) here } } // foo::bar in code. I keep the source in root/src/foo/bar/baz.cpp . If i have some stuff...
361,312
361,407
C++ developing a GUI - classes?
I do have to say I'm fairly inexperienced when it comes to C++, don't be too harsh on me. Recently stumbled unto the wonders of the win32 API and have chosen to practice using it (I'd rather not use MFC/wxWidgets/etc at this point, just for educational purposes). Well, my real question is: How do you properly code your...
The biggest problem I faced back when I used the Win32 API (have since moved on to Linux and cross-platform solutions) were the callbacks. Especially the winproc one, AKA the message pump. I found this, which should be a good hint. I did what that page suggests when I rolled my own wrapper.
361,500
361,597
initializing std::string from char* without copy
I have a situation where I need to process large (many GB's) amounts of data as such: build a large string by appending many smaller (C char*) strings trim the string convert the string into a C++ const std::string for processing (read only) repeat The data in each iteration are independent. My question is, I'd like ...
Is it at all possible to use a C++ string in step 1? If you use string::reserve(size_t), you can allocate a large enough buffer to prevent multiple heap allocations while appending the smaller strings, and then you can just use that same C++ string throughout all of the remaining steps. See this link for more informati...
361,648
361,674
How do you make linux GUI's?
My main experience is with C && C++, so I'd prefer to remain with them. I don't want to use anything like QT, GTK, or wxWidgets or any tool kits. I'd like to learn native programming and this sort of defeats the purpose. With that in mind I'd also like to avoid Java. I understand gnome and xfce and KDE and such are all...
X is a hideous layer to program for and, despite your intent to avoid Java, QT or any of the excellent UI abstraction layers, you'll be doing yourself a disservice by coding to that level. I've done it (a long time ago when Motif was in its infancy on the platform we were using) and I would not do it again if there was...
361,730
361,780
VS2008 binary 3x times slower than VS2005?
I've just upgraded a native C++ project from VS2005-SP1 to VS2008-SP1 The first thing I tested was a very basic functionality test of the application and the first thing I noticed is that the main number-crunching algorithm performs three times slower in the VS2008 binary. I tested again the VS2005 binary to make sure ...
Strangest. Thing. Ever. It seems that the project upgrade wizard of vs2008 simply doesn't copy the 'Optimization="2"' property so the new project is left with no optimization in release. The fix was to go to the properties dialog, change optimization to 1 and then back to 2. compile again and everything works it sh...
362,225
362,340
Setting Zoom on Windows Mobile device with IAMCameraControl::Set()
I am developing an application for video capture and I would like to implement zoom functionality. Working with DirectShow I came across IAMCameraControlInterface. It has a method ::Set(), which should be used for setting several camera parameters. However I played around and I couldn't do anything with it. Then I trie...
I don't have any personal experience, but have a look at this forum port. According to a replier, the driver may not implement the IAMCameraControl interface correctly and rely on implementation specific tricks to do zoom in and out. As far as I know (please someone correct or verify it) the camera driver isn't part of...
362,260
362,268
Thread safety and `const`
How does const (pointers, references and member functions) help with thread safety in C++?
The main problem with multiple threads is mutability. const restricts this, but since you can cast away the const-ness, it's not foolproof.
362,570
368,093
Carbide / Symbian C++ - Change Application Icon
I am using Carbide (just upgraded to 2.0) to develop an S60 3rd Edition application. I would like to know the easiest way to change the icon (both the application icon on the device menu and the icon at the top left of the main view) because I have the need to skin my application in many different ways as easily as pos...
To change the app icon when you run your app use (in the status bar): CEikStatusPane* sp=iEikonEnv->AppUiFactory()->StatusPane(); CAknContextPane* cp=(CAknContextPane *)sp->ControlL(TUid::Uid(EEikStatusPaneUidContext)); _LIT(KContextBitMapFile, "my_bitmap_file.mbm"); CFbsBitmap* bitmap = iEikonEnv->CreateBitmapL(KConte...
362,822
362,892
How do I export templated classes from a dll without explicit specification?
I have a dll that contains a templated class. Is there a way to export it without explicit specification?
Since the code for templates is usually in headers, you don't need to export the functions at all. That is, the library that is using the dll can instantiate the template. This is the only way to give users the freedom to use any type with the template, but in a sense it's working against the way dlls are supposed to w...
362,928
362,943
Open source C++ library for vector mathematics
I would need some basic vector mathematics constructs in an application. Dot product, cross product. Finding the intersection of lines, that kind of stuff. I can do this by myself (in fact, have already) but isn't there a "standard" to use so bugs and possible optimizations would not be on me? Boost does not have it. T...
Re-check that ol'good friend of C++ programmers called Boost. It has a linear algebra package that may well suits your needs.
363,007
363,033
How to reposition/resize the resource on the screen?
I want to embed the native camera application into custom form. The RECT r properties where I want to embed the camera are the following: r.top = 26; r.bottom = 220; r.left = 0; r.right = 320; and this is the method which runs the native camera application: HRESULT CPhotoCapture::CameraCapture(HWND hwndOwner, LPTSTR p...
You're not too clear on what hwndOwner points to. My **guess* on how this probably works is that you need to create a Window that is a child of your main display Window whose location matches your rect (and is visible), then pass it's handle in and that the capture API then uses DShow to pipe the output of the frame g...
363,160
364,815
How do I set the ideal QPixmapCache::cacheLimit?
I have just started using QPixmapCache and I was wondering, since there is not much documentation, about how to adjust the size based on the system the application is running on. Some users might have lots of free memory while others have very little. I have no idea what the best setting would be. What would be the ...
To detect free RAM in Windows, you can use the GlobalMemoryStatus function. I'm not sure if this will help you size the pixmap cache; perhaps you will need to do some performance measurements and create a lookup table.
363,292
363,338
Why is Visual C++ lacking refactor functionality?
When programming in C++ in Visual Studio 2008, why is there no functionality like that seen in the refactor menu when using C#? I use Rename constantly and you really miss it when it's not there. I'm sure you can get plugins that offer this, but why isn't it integrated in to the IDE when using C++? Is this due to some ...
The syntax and semantics of C++ make it incredibly difficult to correctly implement refactoring functionality. It's possible to implement something relatively simple to cover 90% of the cases, but in the remaining 10% of cases that simple solution will horribly break your code by changing things you never wanted to cha...
363,302
363,378
openGL textures that are not 2^x in dimention
I'm trying to display a picture in an openGL environment. The picture's origninal dimensions are 3648x2432, and I want to display it with a 256x384 image. The problem is, 384 is not a power of 2, and when I try to display it, it looks stretched. How can I fix that?
There's three ways of doing this that I know of - The one Albert suggested (resize it until it fits). Subdivide the texture into 2**n-sized rectangles, and piece them together in some way. See if you can use GL_ARB_texture_non_power_of_two. It's probably best to avoid it though, since it looks like it's an Xorg-specif...
363,336
368,431
Trouble tracking down a potential memory overwrite. Windows weirdness
This is driving me nuts. I am using some 3rd-party code in a Windows .lib that, in debug mode, is causing an error similar to the following: Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted. The error is thrown when either the object goes out of scope or is deleted. Simply allocating one of ...
OK, I tracked the problem down and it's a cracker, if anyone's interested. Basically, my .LIB, which exhibited the problem. had defined _WIN32_WINNT as 0x0501 (Windows 2000 and greater), but my EXE and the 3rd-party LIB had it defined as 0x0600 (Vista). Now, one of the headers included by the 3rd-party lib is sspi.h ...
363,351
376,362
Once you've adopted boost's smart pointers, is there any case where you use raw pointers?
I'm curious as I begin to adopt more of the boost idioms and what appears to be best practices I wonder at what point does my c++ even remotely look like the c++ of yesteryear, often found in typical examples and in the minds of those who've not been introduced to "Modern C++"?
Just a few off the top of my head: Navigating around in memory-mapped files. Windows API calls where you have to over-allocate (like a LPBITMAPINFOHEADER). Any code where you're munging around in arbitrary memory (VirtualQuery() and the like). Just about any time you're using reinterpret_cast<> on a pointer. Any time ...
363,453
403,171
Looking for a better C++ class factory
I have an application that has several objects (about 50 so far, but growing). There is only one instance of each of these objects in the app and these instances get shared among components. What I've done is derive all of the objects from a base BrokeredObject class: class BrokeredObject { virtual int GetInterfaceI...
My use-case tended to get a little more complex - I needed the ability to do a little bit of object initialization and I needed to be able to load objects from different DLLs based on configuration (e.g. simulated versus actual for hardware). It started looking like COM and ATL was where I was headed, but I didn't wan...
363,760
2,218,783
Windows Explorer directory as bundle
I have been investigating for some time now a way to prevent my user from accidently entering a data directory of my application. My application uses a folder to store a structured project. The folder internal structure is critic and should not be messed up. I would like my user to see this folder as a whole and not be...
Looks like some Windows ports of FUSE are starting to appear. I think this would be the best solution since it would allow me to keep the legacy code (which is quite large) untouched.
363,864
363,873
invalid types 'int[int]' for array subscript
This code throws up the compile error given in the title, can anyone tell me what to change? #include <iostream> using namespace std; int main(){ int myArray[10][10][10]; for (int i = 0; i <= 9; ++i){ for (int t = 0; t <=9; ++t){ for (int x = 0; x <= 9; ++x){ ...
You are subscripting a three-dimensional array myArray[10][10][10] four times myArray[i][t][x][y]. You will probably need to add another dimension to your array. Also consider a container like Boost.MultiArray, though that's probably over your head at this point.
364,017
364,156
Faster bulk inserts in sqlite3?
I have a file of about 30000 lines of data that I want to load into a sqlite3 database. Is there a faster way than generating insert statements for each line of data? The data is space-delimited and maps directly to an sqlite3 table. Is there any sort of bulk insert method for adding volume data to a database? Has anyo...
You can also try tweaking a few parameters to get extra speed out of it. Specifically you probably want PRAGMA synchronous = OFF;.
364,146
364,163
C++ syntax help dealing with recursive definition (or so my compiler tells me)
I'm building a game and I was compiling seeing what sort of errors were coming up and there is one there is very common and very puzzling to me: 1>c:\users\owner\desktop\bosconian\code\bosconian\ship.h(9) : error C2460: 'Ship::Coordinate' : uses 'Ship', which is being defined This also comes up for the SpaceObject cla...
You've got something like this: class Ship { class Coordinate { Ship m_ship; }; Coordinate m_coordinate; }; The problem is that each Ship object contains as a member a Coordinate, which contains as a member a Ship, ad nauseum. The size of a Ship would become infinitely large if this were allo...
364,209
364,224
variable or field declared void
I have a function called: void initializeJSP(string Experiment) And in my MyJSP.h file I have: 2: void initializeJSP(string Experiment); And when I compile I get this error: MyJSP.h:2 error: variable or field initializeJSP declared void Where is the problem?
It for example happens in this case here: void initializeJSP(unknownType Experiment); Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.
364,240
364,257
How do YOU reduce compile time, and linking time for Visual C++ projects (native C++)?
How do YOU reduce compile time, and linking time for VC++ projects (native C++)? Please specify if each suggestion applies to debug, release, or both.
It may sound obvious to you, but we try to use forward declarations as much as possible, even if it requires to write out long namespace names the type(s) is/are in: // Forward declaration stuff namespace plotter { namespace logic { class Plotter; } } // Real stuff namespace plotter { namespace samples { c...
364,985
365,068
Algorithm for finding the smallest power of two that's greater or equal to a given value
I need to find the smallest power of two that's greater or equal to a given value. So far, I have this: int value = 3221; // 3221 is just an example, could be any number int result = 1; while (result < value) result <<= 1; It works fine, but feels kind of naive. Is there a better algorithm for that problem? EDIT. The...
Here's my favorite. Other than the initial check for whether it's invalid (<0, which you could skip if you knew you'd only have >=0 numbers passed in), it has no loops or conditionals, and thus will outperform most other methods. This is similar to erickson's answer, but I think that my decrementing x at the beginnin...
365,048
365,055
Interesting C++ Abstract Function
why this is happen ? When u create abstract class in c++ Ex: Class A (which has a pure virtual function) after that class B is inherited from class A And if class A has constructor called A() suppose i created an Object of class B then the compiler initializes the base class first i.e.class A and then initialize ...
Quick answer: constructors are special. When the constructor of A is still running, then the object being constructed is not yet truly of type A. It's still being constructed. When the constructor finishes, it's now an A. It's the same for the derived B. The constructor for A runs first. Now it's an A. Then the constru...
365,104
365,111
Why are destructors required in C++?
When a pointer goes out of scope, its memory is freed, so why are destructors created in c++?
If you're asking why C++ classes have destructors, some classes have requirements other than just freeing memory. You may have an object that's allocated a socket connection that needs to be shut down cleanly, for example. Also, 'unscoping' a pointer does not free the memory that it points to since other pointers may b...
365,198
365,206
Getting this BST template to work
hI, I'm trying to get this code from Larry Nyhoff's book to compile in Bloodshed. It's actually been taken word for word from the author's website, though I declared it on .cpp instead of .h (the .h file ain't working with the tester application). http://cs.calvin.edu/activities/books/c++/ds/2e/SourcePrograms/Chap12/ ...
Put a typename before the declaration: typename BST<DataType>::BinNodePointer locptr = myRoot; The point is that due to potential template specialization, the compiler cannot know that the dependent identifier BinNodePointer identifies a type.
365,316
365,466
3D Engine Comparison
I am currently investigating several free/open source OpenGL based 3D engines, and was wondering if you guys could provide some feedback on these engines and how they are to work with in a real world project. The engines being compared are (in no particular order): Crystal Space Panda3D Irrlicht These are the main one...
You can find a lot of informations on lot of engines on this database. CrystalSpace is a full engine so it's a monolithic bloc that you have to customize for your needs. Irrlicht too but it's made do do things easy. The counter effect is that it's hard to do specific things. Now, i think Ogre might be the most general ...
365,458
365,796
How can I detect if a program is running from within valgrind?
Is there a way to identify at run-time of an executable is being run from within valgrind? I have a set of C++ unit tests, and one of them expects std::vector::reserve to throw std::bad_alloc. When I run this under valgrind, it bails out completely, preventing me from testing for both memory leaks (using valgrind) an...
You should look at this page from the Valgrind manual, it contains a RUNNING_ON_VALGRIND macro (included from valgrind.h) which does what you want.
365,476
365,492
C++ Problem Stuffing 8 bits into a char
This is weird. It is a trivial problem: A std::string with bits with length multiple of 8, the first 8 is: "10011100". //Convert each 8 bits of encoded string to bytes unsigned char c = 0; for(size_t i = 0; i < encoded.size(); i += 8) { for(size_t k = 0; k < 8; k++) { c <<= k; if(encoded.at(i + ...
at k = 0, c = 1 at k = 1, c = 2 at k = 2, c = 8 That is because: input = 10011100 c = 0 `k=0, b=1` shift by 0 add 1 => `c = 1`, dec = 1 `k=1, b=0` shift by 1 add 0 => `c = 10`, dec = 2 `k=2, b=0` shift by 2 add 0 => `c = 1000`, dec = 8 b means "current bit". Possibly you don't want to shift by k, but by 1 ? If you l...
365,650
365,668
Visual Studio skips build
When I try to build my project I get the following message in the build window : ========== Build: 0 succeeded or up-to-date, 0 failed, 1 skipped ========== I tried rebuilding , then building again , but it doesn't help . Is there a way to view more detailed messages ? The "skipped" part doesn't give me any info on wha...
Check with the configuration manager like CMS said and make sure that you have the right platform set. A lot of the time when you use something like the MS Application Blocks the default platform is set to Itanium.
365,823
365,862
What kinds of interview questions are appropriate for a c++ phone screen?
Curious to get people's thoughts. I conduct frequent interviews, and have had enough in my career to reflect on them, and I've noticed a broad array of questions. I made this c++ specific, but it's worth noting that I have had people ask me algorithmic complexity questions over the phone, and I don't even mean what is ...
I'd ask about resource/memory management, because it's an important subject in C++, and it doesn't require concrete code. Just sketch a simple hypothetical scenario, and ask how they'd ensure some vital resource gets freed even in the face of errors/exceptions. Say they're developing a network app, how do they ensure t...
365,887
365,891
How do 'malloc' and 'new' work? How are they different (implementation wise)?
I know how they are different syntactically, and that C++ uses new, and C uses malloc. But how do they work, in a high-level explanation? See What is the difference between new/delete and malloc/free?
I'm just going to direct you to this answer: What is the difference between new/delete and malloc/free? . Martin provided an excellent overview. Quick overview on how they work (without diving into how you could overload them as member functions): new-expression and allocation The code contains a new-expression supply...
366,028
14,005,292
What is a good C/C++ CSS parser?
What is a good C/C++ CSS parser? All that I can find is CSSTidy, and it seems to be more of an application than a parsing library.
libcss seems also a common google hit and it looks good http://www.netsurf-browser.org/projects/libcss/
366,134
366,138
Can you declare a pointer as extern in C++?
I have the following bit of legacy C++ code that does not compile: #include <stdio.h> #include <iostream> extern ostream *debug; GCC (g++) complains: "expected initializer before ‘*’ token" Looking around it seems more common to declare these as external references, like this: extern ostream& debug; Why is a pointer...
Yes, you can declare a pointer using extern. Your error is most likely you forgot to qualify using std:: : // note the header is cstdio in C++. stdio.h is deprecated #include <cstdio> #include <iostream> extern std::ostream *debug;
366,228
366,268
.def files C/C++ DLLs
I am not understanding the point of using .def files with DLLs. It seems that it replaces the need to use explicit exports within your DLL code (ie. explicit __declspec(dllexport)) however I am unable to generate a lib file when not using these which then creates linker issues later when using the DLL. So how do you u...
My understanding is that .def files provide an alternative to the __declspec(dllexport) syntax, with the additional benefit of being able to explicitly specify the ordinals of the exported functions. This can be useful if you export some functions only by ordinal, which doesn't reveal as much information about the func...
366,257
366,266
Everything a c++ developer should know about network programming?
So I am doing a lot of high performance network programming using Boost::Asio (or just Asio if you will), and have a pretty solid grasp of the essentials of both TCP and UDP protocols. I am wondering though, because I still don't consider myself an expert in networking despite my knowledge, what is a good way to frame ...
Some bullet points off the top of my head of things you should know: How and why TCP works... 3-way handshakes, acknowledgement, delayed ack, nagling, sliding window protocol. There's a concrete reason for every one of those features... and they can all destroy your application's performance if handled improperly. UD...
366,742
366,773
Creating an Environment Stack in OpenGL
I'd like to create an abstraction in OpenGL of the environment settings(blending, stenciling, depth, etc.) that works like the matrix stack. Push onto the stack, make any changes you need, draw your objects, then pop the stack and go back to the prior settings. For example, currently you might have drawing code like th...
OpenGL already contains this functionality. You want glPushAttrib(GL_ALL_ATTRIB_BITS); and glPopAttrib();. See http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushattrib.html for more.
366,768
538,742
Convert bitmap to PNG in-memory in C++ (win32)
Can I convert a bitmap to PNG in memory (i.e. without writing to a file) using only the Platform SDK? (i.e. no libpng, etc.). I also want to be able to define a transparent color (not alpha channel) for this image. The GdiPlus solution seems to be limited to images of width divisible by 4. Anything else fails during th...
I read and write PNGs using libpng and it seems to deal with everthing I throw at it (I've used it in unit-tests with things like 257x255 images and they cause no trouble). I believe the API is flexible enough to not be tied to file I/O (or at least you can override its default behaviour e.g see png_set_write_fn in se...
366,923
367,132
Need advice on Windows to OS X Port Estimation and cost of dev. on OS X
I am a 10year+, C++ linux/windows developer and I have been asked to estimate the effort to port the windows application to OS X. I haven't developed on OS X before,so I don't know what to expect. It is a C++/Qt application, so I want to ask: what are the de facto tools like editor, IDE, compiler, make tool, etc ? Whic...
As jakber already posted, XCode is the standard IDE for MacOSX, and is free (comes with the install DVD or can be downloaded from apple. The XCode IDE is quite different from that of Visual Studio, and it seems to me as if it were more familiar to Codewarrior. I don't know if there are any tools to convert VS projects ...
366,955
366,969
Obtain a std::ostream either from std::cout or std::ofstream(file)
how do I bind a std::ostream to either std::cout or to an std::ofstream object, depending on a certain program condition? Although this invalid for many reasons, I would like to achieve something that is semantically equivalent to the following: std::ostream out = condition ? &std::cout : std::ofstream(filename); I've...
std::streambuf * buf; std::ofstream of; if(!condition) { of.open("file.txt"); buf = of.rdbuf(); } else { buf = std::cout.rdbuf(); } std::ostream out(buf); That associates the underlying streambuf of either cout or the output file stream to out. After that you can write to "out" and it will end up in the ...
367,310
395,962
Dynamic Memory Allocation Failure Recovery
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is...
There are a few different ways to attack this - note that the tool instructions will vary a bit, based on what version of Windows CE / Windows Mobile you are using. Some questions to answer: 1. Is your application leaking memory, leading to this low memory condition? 2. Does your application simply use too much memory...
367,633
367,662
What are all the common undefined behaviours that a C++ programmer should know about?
What are all the common undefined behaviours that a C++ programmer should know about? Say, like: a[i] = i++;
Pointer Dereferencing a NULL pointer Dereferencing a pointer returned by a "new" allocation of size zero Using pointers to objects whose lifetime has ended (for instance, stack allocated objects or deleted objects) Dereferencing a pointer that has not yet been definitely initialized Performing pointer arithmetic that...
367,819
368,050
enum-int casting: operator or function
In the external code that I am using there is enum: enum En {VALUE_A, VALUE_B, VALUE_C}; In another external code that I am using there are 3 #define directives: #define ValA 5 #define ValB 6 #define ValC 7 Many times I have int X which is equal to ValA or ValB or ValC, and I have to cast it to the corresponding va...
Since you can't just cast here, I would use a free function, and if there are likely to be other enums that also need converting, try to make it look a little bit like the builtin casts: template<typename T> T my_enum_convert(int); template<> En my_enum_convert<En>(int in) { switch(in) { case ValA: return ...
367,824
371,474
Using Win32 API in Qt OSE project
It is a messy question, hopefully you can figure out what I want :) What is the best way to use Win32 functionality in a Qt Open Source Edition project? Currently I have included the necessary Windows SDK libraries and include directories to qmake project file by hand. It works fine on a small scale, but its inconvenie...
You could build an interface layer to wrap the Win32 functionality and provide it in a DLL or static library. The DLL would minimize the need for linking directly to the Win32 libraries with your qmake project. It would be more in keeping with the portability of Qt to create generic interfaces like this and then hide t...
367,926
370,538
Use a dll from a c++ program. (borland c++ builder and in general)
I'm trying to use a dll, namely libcurl, with my program, but, it's not linking. Libcurl comes with .h files that I can include (takes care of dllimport), but then I guess I must specify which dll to actually use when linking somehow... How do I do that? I'm compiling with Borland C++ builder, but I really want to know...
As mentioned, you will need the static .lib file that goes with the .dll which you run through implib and add the result lib file to your project. If you have done that then: You may need to use the stdcall calling convention. You didn't mention which version of Builder you are using, but it is usually under Project o...
367,984
367,990
What C++ HTTP frameworks are available?
What C++ HTTP frameworks are available that will help in adding HTTP/SOAP serving support to an application?
Well, gSOAP of course. :) http://www.cs.fsu.edu/~engelen/soap.html
368,184
368,284
Does it make sense to catch exceptions in the main(...)?
I found some code in a project which looks like that : int main(int argc, char *argv[]) { // some stuff try { theApp.Run(); } catch (std::exception& exc) { cerr << exc.what() << std::endl; exit(EXIT_FAILURE); } return (EXIT_SUCCESS); } I don't understand why the exceptions are being catched. If they were...
If an exception is uncaught, then the standard does not define whether the stack is unwound. So on some platforms destructors will be called, and on others the program will terminate immediately. Catching at the top level ensures that destructors are always called. So, if you aren't running under the debugger, it's pro...
368,262
370,228
Function call jumps to the wrong function
I am compiling a c++ static library in vs2008, and in the solution i also have a startup project that uses the lib, and that works fine. But when using the lib in another solution i get an run-time check failure. "The value of ESP was not properly saved across a functioncall" Stepping through the code i noticed a func...
Forgive me for stating the bleeding obvious here, but... I've seen this sort of thing happen many times before when object (.o) and header (.h) files get out of sync. Especially with respect to virtual methods. Consider: The object file is compiled with header: class Foo { virtual void f(); }; But then the header g...
368,737
368,810
c++ deduction of "non type pointer to function" class template parameters
Consider a template class like: template<typename ReturnType, ReturnType Fn()> class Proxy { void run() { ReturnType ret = Fn(); // ... do something ... } }; // and a functions int fn1() { return 5; } float fn2() { return 5; } This can be instantiated by using: Proxy<int, &fn1> p1; But ex...
This isn't possible in C++03. If you want to pass a function pointer as a non-type parameter, the compiler has to know the type of the parameter. So you have to provide the missing pieces (in this case, the return type). You can give the proxy the function pointer as a value at runtime, and provide it with the type of ...
368,963
368,974
Symbian C++ - Persistent storage of a single variable
I wish to store a single variable in my application that will be saved between runs. This will be a version number that will be used to trigger an update option and so will change only rarely. Does anyone have suggestions on the best way of implementing this? Considering it's such a simple requirement I am interested i...
Normally, that sort of information will be held in a constant (not a variable) in the binary, and the binary will contact an external site to find out whether there is a more recent version of the software. When it downloads the new, the newly downloaded file will have a new constant embedded in it. Alternatively, you...
368,976
368,984
How to allocate memory to an array of instances using an abstract class?
I have an abstract class defining a pure virtual method in c++: class Base { Base(); ~Base(); virtual bool Test() = 0; }; I have subclassed this with a number of other classes (which provide an implementation for Test()), which I'll refer to as A, B, C, etc. I now want to create an array of any of these types using t...
There is only a slight misunderstanding in that code. Instead of allocating Base objects, you have to allocate pointers. A pointer can exist at any time. A pointer to a abstract class, to an incomplete type, and even to void is valid: int main(int argc, char* argv[]) { int size = 0; Base** bases = new Base*[10]...
369,211
369,276
What function in the std library is there to binary search a vector and find an element?
I've got a node struct struct Node{CString text, int id;}; in a sorted vector. I'm wondering if there's a function in algorithm that will do a binary search of the vector and find an element.
std::binary_search() will tell you if a value exists in the container. std::lower_bound()/std::upper_bound() will return an iterator to the first/last occurrence of a value. Your objects need to implement operator< for these algorithms to work.
369,506
369,513
./ changes target when i use OpenFileDialog
I'm using a streamwriter to log errors the way it has been designed (please dont ask why) is to open a new streamwriter everytime the application has to log a message. It outputs everything to ./Logs/[current-date].txt which usually resolves to "c:\myappfolder\logs[current-date].txt" Everything works correctly, but aft...
The current directory is a process wide value. The OpenFileDialog is changing the current directory. If you're using the .NET OpenFileDialog class, you can set the RestoreDirectory property to true to tell the dialog to leave the current directory alone (although the way the docs for RestoreDirectory is written there...