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
1,653,958
1,653,965
Why are #ifndef and #define used in C++ header files?
I have been seeing code like this usually in the start of header files: #ifndef HEADERFILE_H #define HEADERFILE_H And at the end of the file is #endif What is the purpose of this?
Those are called #include guards. Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page. When the code is included again, the first ifndef fails, resulting in a blank file. That prevents double declaration of any identifiers such as types, enums and static variables.
1,654,143
1,654,165
Why might using a "long long" in C or C++ be a bad thing?
Why might using a "long long" in C or C++ be a bad thing? I was compiling a runtime library the other day and in the code it checks to see if longs are 64bits and if not it uses a long long. But along with that, it sends out a #warning "using long long". I can't think of any reason for the "long long" being a warning unless it was leftover debug cruft from the developer. Thanks Chenz
As far as I know, long long is currently standard only in C99. It will also be a type in C++0x, but most modern compilers should support it already. However, for fixed-sized integers one might use the C99 header <stdint.h>, or in C++ <boost/cstdint.hpp>
1,654,149
1,654,182
Static data on iphone c++
I have data for countries which include Name, Population, Area etc for countries... What is the best way to store them, I was thinking of static arrays in header files ...? I am using c++ primarily for some game on iPhone Should I consider other options like sqlite, plists, dictionaries ....?
It depends. If the data is never going to change then static arrays in header files is probably a good enough solution. The problem is that if one day you do want to make a change to the data, you'll have to recompile your application, which might not be a concern for you. But it might also be a complete hassle, especially if you need to repeatedly try out different values for some of the data. Personally I'd be tempted to store this data in an external file of some description. plists might be perfect for this, although if there's large amounts of unstructured data you might find them a bit heavyweight. I've often used simple plain text files for storing some types of data. I suspect SQLite may be completely over the top, unless your data makes sense to be structured using a relational database, or needs to be changed by the app itself regularly.
1,654,150
1,654,187
Scope of exception object in C++
What is the scope of the exception object in C++? does it go out of scope as soon as catch handler is executed? Also, if I create an unnamed exception object and throw it, then while catching that exception does it matter if I catch it by const reference or a non-const reference?
When a throw expression is evaluated, an exception object is initialized from the value of the expression. The exception object which is thrown gets its type from the static type of the throw expression ignoring any const and volatile qualifiers. For class types this means that copy-initialization is performed. The exception object's scope is outside of the scope of the block where the throw occurs. Think of it as living in a special exception area off to one side of the normal call stack where local objects live. Inside a catch block, the name initialized with the caught exception object is initialized with this exception object and not the argument to throw, even if this was an lvalue. If you catch via non-const reference, then you can mutate the exception object, but not what it was initialized from. You can alter the behaviour of the program if you re-throw the exception in ways that you couldn't if you caught by value or const reference (const_casts aside). The exception object is destroyed when the last catch block that does not exit via a re-throw (i.e. a parameterless throw expression evaluation) completes.
1,654,159
1,654,172
How to prevent compiler doing implicit typecasting in for the class constructor argument?
#include <iostream> using namespace std; struct testarray{ int element; public: testarray(int a):element(a){} }; class myarray { public: testarray i; public: myarray(testarray a) : i(a){ } } ; int main() { myarray objArray[3] = {1,2,3}; return 0; } The above code compiles fine in Visual C++ 2005 Express Edition IDE. But what I want is to prevent the compiler from implicitly typecasting the object type.
You can use explicit keyword for your struct constructor.
1,654,381
1,882,767
How can I add a wxIcon to my frame app?
I've looked all over the net and can't seem to find a standard way of including a wxIcon in my wxWidgets app that actually works! I've tried converting the icon to an XPM and including that I've also tried loading the bitmap but whatever I do it seems to compile but the icon never appears!
If you are trying this on Windows make sure the icon is 32x32 pixels. All other sizes weren't being rendered at all...
1,654,444
1,654,455
Why is there a class keyword in C++?
This question came to my mind when I learned C++ with a background of C. Even if there was a struct why did Stroustrup felt it was necessary to introduce the class keyword? I tried asking people at that time but couldn't get a satisfactory answer. So can the Stack Overflow community answer it?
As David says, structs are public by default, classes are private by default. The larger point is that adding object orientation to C was a big change, and giving developers ways to express themselves accurately is an important part of designing a language. As it turns out, the distinction between struct and class is quite minor from a technical point (default-public vs default-private), but in programmers' minds, the distinction is quite large. Adding the keyword was an important way to emphasize the OO nature of C++.
1,655,089
1,655,378
CMake RequireAdministrator
I'm trying to set the RequireAdministrator manifest flag on an executable I'm building with CMake and Visual Studio. Any ideas on how to direct CMake to set that option? Thanks! Billy3
try this: SET_TARGET_PROPERTIES(your_executable PROPERTIES LINK_FLAGS "/MANIFESTUAC:\"level='requireAdministrator' uiAccess='false'\" /SUBSYSTEM:WINDOWS")
1,655,096
1,655,160
C++ class, its base class and circular include includes
FILE #1 (foo.h): #ifndef FOO_H_ #define FOO_H_ #include "baseclass.h" #include "bar.h" class Bar; class Foo : public baseclass { public: bar *varBar; }; #endif FILE #2 (bar.h): #ifndef BAR_H_ #define BAR_H_ #include "foo.h" class Foo; class Bar { public: Foo *varFoo; }; #endif FILE #3 (baseclass.h): #ifndef BASECLASS_H_ #define BASECLASS_H_ #include "foo.h" class Foo; class baseclass { public: list<Foo*> L; }; #endif But I get an compile error in file #1 in line class Foo : public baseclass: Error: expected class-name before »{« token If I add class baseclass; bevor class declaration, I get this error: Error: invalid use of incomplete type »struct baseclass« So my question is, how can I resolve circular dependencies with baseclasses? Ask if you don't get somepoint. I allready tried to change the order of includeing the headers, but no luck so far. Thanks for any hint. EDIT: Note: I am using include guards EDIT2: It is not limited to pointers, so I remove them, just in case. EDIT3: Added baseclass (forgot O.o) EDIT4: Now it should be clear and without anymore flaws, the problem persisits with this code.
What you seem to have posted is to have a Bar member in the Foo, and a Foo member in the Bar. That is a circular dependency you need to break - if every Foo contains a Bar which contains a Foo then constructing either never terminates. class Foo : public baseclass { public: Bar varBar; }; class Bar { public: Foo varFoo; }; Instead you need to use a pointer or reference to the Foo or Bar in at least one of them: class Bar; class Foo : public baseclass { public: Bar& varBar; }; class Bar { public: Foo varFoo; }; As the circularity is broken and you're only using a reference to the object, you don't need to have the full definition of the referred-to type, and can use a forward declaration. Include guards are good for users, but try and not rely on them when developing. If the compiler has to check whether or not something has been included, it's still doing work even if it has optimisations for guards/pragmas. You do need to have some understanding of what depends on what to break the initial cycle, and putting guards on the files won't help you with that.
1,655,242
1,655,288
LPD3DXFONT DrawText using DT_CALCRECT?
How do I use DT_CALCRECT to determine my rectangle bottom and right coords? e.g I have this rect: RECT textPos; textPos.left = 100; textPos.right = 100; What do I do next to calculate the rect and draw the text?
Mmm you just make a call to DrawText with the DT_CALCRECT parameter set, and the pointer to your original rectangle. It will modify the rectangle, extending the bottom and right values. Then you make another call to DrawText with your updated rectangle and whatever DT_ parameter needed. http://msdn.microsoft.com/en-us/library/ms901121.aspx
1,655,466
1,655,494
Can you tell iostreams which characters to treat as whitespace?
So that you could do something like this, for instance: std::string a("01:22:42.18"); std::stringstream ss(a); int h, m, s, f; ss >> h >> m >> s >> f; Which normally requires the string to be formatted "01 22 42 18". Can you modify the current locale directly to do this?
Take a look at scanf and fscanf. You might* be able to do something like this: int h, m, s, f; sscanf(a.c_str(), "%d:%d:%d.%d", &h, &m, &s, &f); * Caveat: It's been a while for me and C++
1,655,501
1,655,534
Shifting elements in array C++
Im wondering why my data in 'intFront' does not stay the same. Im shifting the elements in my array left: void stack::rotate(int nRotations) { for (; nRotations > 0 ;) // Number of Rotations to the left { intFront = &items[top+1].n; for ( int shiftL = 0; shiftL < count-1; shiftL++ ) { items[shiftL] = items[shiftL+1]; // shift left from the front } items[count-1].n = *intFront; nRotations--; // decrement=0 will indicate no more rotations left } } Whats happening is that the first value or "head" or "front" of the array is put into a varaible 'intFront'. I rotate everything left by the given number of rotations, hoping to just make a simple transfer at the end. Guess not..
You overrun your array: read of items[shiftL+1] goes beyond array bounds at last iteration, You save a pointer to member of a structure into intFront and then override these structures by value in the inner loop - that'll sure change value intFront points to, There's no need for doing multiple copies, i.e. no need for two embedded loops, since you know by how much you need to shift (nRotations).
1,655,650
1,655,660
Linux optimistic malloc: will new always throw when out of memory?
I have been reading about out of memory conditions on Linux, and the following paragraph from the man pages got me thinking: By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer. [...] Considering that the operator new implementation will end up calling malloc at some point, are there any guarantees that new will actually throw on Linux? If there aren't, how does one handle this apparently undetectable error situation?
It depends; you can configure the kernel's overcommit settings using vm.overcommit_memory. Herb Sutter discussed a few years ago how this behavior is actually nonconforming to the C++ standard: "On some operating systems, including specifically Linux, memory allocation always succeeds. Full stop. How can allocation always succeed, even when the requested memory really isn't available? The reason is that the allocation itself merely records a request for the memory; under the covers, the (physical or virtual) memory is not actually committed to the requesting process, with real backing store, until the memory is actually used. "Note that, if new uses the operating system's facilities directly, then new will always succeed but any later innocent code like buf[100] = 'c'; can throw or fail or halt. From a Standard C++ point of view, both effects are nonconforming, because the C++ standard requires that if new can't commit enough memory it must fail (this doesn't), and that code like buf[100] = 'c' shouldn't throw an exception or otherwise fail (this might)."
1,655,904
1,655,938
convert pointer string to integer
I am trying to convert treePtr->item.getInvest() which contains a string to an integer. Is this possible?
#include <sstream> // ... string str(*(treePtr->item.getInvest())); // assuming getInvest() returns ptr istringstream ss(str); int the_number; ss >> the_number;
1,655,912
1,655,919
problem passing in istream argument to a class constructor
I have the following code in my header file: class Factovisors { public: Factovisors(std::istream& strm):strm_(strm) { } void run() { unsigned int n,m; while (!strm_.eof()) { strm_ >> n >> m; if (isFact(n,m)) std::cout << m << " divides " << n << "!\n"; } } std::istream strm_; }; My .cpp file has the following code. std::ifstream strm("factovisor.test"); Factovisors facto(strm); facto.run(); strm.close(); The error my compiler gives me is: std::ios::basic_ios(const std::ios &) is not accessible from std::istream::basic_istream(const std::istream &) I imagine I am missing something really obvious. So any help would be greatly appreciated.
The problem is that istream is an "interface". It has pure virtual functions, so it doesn't make sense to have a copy of it. What you might do is to keep a reference to the passed stream: std::istream& strm_; strm_ could be ifstream or istringstream or any input stream derived from istream.
1,655,960
1,655,975
What are the most surprising elements of the C++ standard?
I've decided to get more acquainted with my favorite programming language, but only reading the standard is boring. What are the most surprising, counter-intuitive, or just plain weird elements of C++? What has shocked you enough that you ran to your nearest compiler to check if it's really true? I'll accept the first answer that I won't believe even after I've tested it. :)
The order of several declarators is actually unordered: volatile long int const long extern unsigned x; is the same as extern const volatile unsigned long long int x;
1,655,996
1,656,003
Variables as a parameters for templates in C++
I'm trying to start learning C++ and I have a problem. I'm trying to create a function template, template<multimap<string, double> arr> void calculate(string key) { } and use it like this: multimap<string, double> arr; vector<string> keys; // ... for_each(keys.begin(), keys.end(), calculate<arr>); But i doesnt'complile: Illegal type for non-type parameter, etc Please, help me. How to arhive the behavior I expect? I really don't want to create a callback for every for_each, etc. (Maybe, closures have made me more lazy than it needed for C++ and I have to, but I don't want to believe) (btw, is there a way to get a vector with keys from multimap?) I've tried typedef multimap<string, double> my_map; template<my_map arr> still doen't work
I don't know what you're trying to do, but templates are parameterized by type. An ordinary function or a function object should do what you want. So let's make your function look like this: void calculate(const string &key, multimap<string, double>& myMap) { // do something... } now we can use the STL's binders and ptr_fun to convert your function to an object and bind its second argument to your map. multimap<string, double> map1; vector<string> v = getValuesForMyVector(); for_each(v.begin(), v.end(), bind2nd(ptr_fun(calculate), map1); So what's going on is that ptr_fun(calculate) converts calculate, which is a pointer-to-function, into a special class called a pointer_to_binary_function<string, multimap<string, double>, void> which has operator() defined to call your function, i.e. it takes 2 parameters. bind2nd(ptr_fun(calculate), map1) returns a binder2nd<string, void> which still has operator() defined, but now it only takes 1 parameter. The 2nd parameter is bound to map1. This allows for_each to operate with this function object. Of course, you're stuck using these 2 adaptors if you make a function. A better way is to make a class: class MapCalculator { public: MapCalculator(multimap<string, double>& destination) : map_(destination) {} void operator()(const string& s) { // do something... } private: multimap<string, double>& map_; }; // later... multimap<string, double> map1; vector<string> v = getValuesForMyVector(); for_each(v.begin(), v.end(), MapCalculator(map1));
1,656,140
1,656,191
Logic of iterating through a list. Element "flickering"
[SOLVED]: Applying proper list iteration procedure fixed problem. (Shown below) I currently have a program in which elements of a list are iterated through and erased if they meet certain conditions. Due to the nature of the program, this can be visually seen. Objects on screen that are being iterated through sometimes flicker on and off. This usually happens when objects around them are destroyed (i.e. erased in the code). At first I thought it was screen flickering, but now I realize that I think my iteration functions' logic may be causing the problem. Here are the two functions. The first detects bullet collisions with blocks. If a bullet hits a block, the block is destroyed. // Edit: WRONG WAY TO ITERATE THROUGH LIST void DetectBulletCollisions() { std::list<Bullet>::iterator bullet = game::player_bullets.begin(); for ( ; bullet != game::player_bullets.end(); ++bullet) { if (bullet->IsOnScreen()) { bullet->DetectBlockCollision(game::blocks); } else // Remove bullet from list { bullet = --game::player_bullets.erase(bullet); } } } This function moves the blocks that are flickering. // Edit: RIGHT WAY TO ITERATE THROUGH LIST void MoveBlocks(const int delta_ticks) { // Blocks on screen std::list<Block>::iterator block = game::blocks.begin(); while (block != game::blocks.end()) // Loop through blocks { block->Show(); // Show block if (!block->IsDestroyed()) // If block hasn't been destroyed { block->Move(delta_ticks); // Move block ++block; // Increment iterator } else // Block has been destroyed, remove it from list. { block = game::blocks.erase(block); } } } Is there something wrong with the logic of these loops? Notably the second one? It seems that when a block is destroyed, others around it flicker on and off (it isn't consistent, but that may just be frame rate). I'm not sure if the list rearranging the elements after each erasure would be a problem or not. The blocks each have coordinates, so it doesn't matter where they are in the list. If any more information is needed I'd be happy to give it. I'm just wondering if my logic is wrong in the writing of these loops, or if I should take a different approach. I chose lists because they are the most efficient STL container for removing elements.
In both loops, when you erase an element, you assign the return value of erase to the loop iterator. According to cplusplus.com, list::erase returns the element after the erased element. So that code will always skip a bullet or a block when an erase happens if I'm not mistaken. Could that have anything to do with it?
1,656,329
1,656,336
Pointer to shift array C++
Im trying to shift my array left as efficiently as possible. Im using pointers now, and im having trouble assigning the values back into my array: void stack::rotate(int nRotations) { if ( count <= 1 ) return; int *intFrontPtr = &items[top+1].n; int *intBackPtr = &items[count-1].n; int temp = 0; for (int shift = 0; nRotations != 0 ;) { if ( nRotations > 0 ) // we rotate left { temp = *++intFrontPtr; // give temp the value items[++shift].n = temp; // debug shows success if ( shift == count ) // dont overrun array { temp = *intBackPtr; items[count-1].n = temp; shift = 0; // reset for another rotation nRotations--; // decrement we have reached the end } } } }
c++ has a function built in in <algorithm>. Just call std::rotate(front_ptr, front_ptr + N, back_ptr);
1,656,790
1,656,838
How do I destroy a Window correctly?
I'm programming a little game, and I set the lpfnWndProc to DefWindowProc and after that, I made a loop in that way: MSG lastMessage; while (true) { if (PeekMessage( &lastMessage, this->getWindow(), 0, 0, PM_REMOVE)) { TranslateMessage(&lastMessage); DispatchMessage(&lastMessage); } } So how do I handle the Close Window event in that case?
First of all, this is not how you write a message loop: it will take 100% CPU while waiting for messages, and won't remove messages for other windows from the queue. It will also never terminate. See here for an example of a message loop. About closing windows: DefWindowProc will handle WM_CLOSE automatically and destroy your window. If you want your application to terminate when the window is closed, you need to handle WM_DESTROY and call PostQuitMessage(0) from it. This means you will need your own window procedure instead of DefWindowProc.
1,657,225
1,699,225
Experiences with Adobe's "Adam and Eve" C++ GUI library?
I tried out the demo application which was pretty impressive. However building it and integrating it with my own code is hard because it's such a large project. Has anyone successfully used it for their own projects? Was is difficult to build and integrate with your own C++ code? Link: STLab. For the interested: there's also a Google Tech Talk clarifying the philosophical ideas behind the project.
ASL is used fairly heavily within Adobe. The layout library (Eve) is used in many Adobe products and variants of it have been in use since Photoshop 5. The property model library (Adam) got a little use in CS4 and will likely be used more in future products. I can no longer speak with certainty because I left Adobe a few months ago and am now working at Google. I still put in some time on ASL and continue to collaborate with Prof. Jarvi and some of his students on the property model library (see the paper on the ASL wiki). It can be a bit difficult to integrate with your product. The platform libraries in ASL (backends to Adam and Eve for Windows and Mac Carbon) started as some small example code, then the community started to refine it (the Windows port was initially a community effort), then we had some ambition to make it a real, supported library. But then Apple dropped Carbon for 64 bits and Adobe's framework plans changed so we weren't able to leverage our efforts here inside Adobe. Because of this the platform libraries are a little shaky - if your code base is already using a framework you might consider integrating Adam and Eve directly (the API for both libraries is very small). There are two challenges with integrating with a framework. Eve needs good metrics to do a good layout, including things like baselines - getting that from your UI toolkit may be tough. The property model library assumes a strict model/view/controller pattern that most UI toolkits don't obey so you have to do a bit of adapting. Feel free to ask questions on the ASL mailing list. We can also help with building - it really isn't as complex as it seems.
1,657,364
1,657,373
Cant track down access violation 0xC00000FD
Im using VS2008 and My MFC application has started to crash when setting breakpoints or running to cursor. I get lots of errors like this:- First-chance exception at 0x78a5727c (mfc90ud.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0xfffffffc. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. First-chance exception at 0x00000000 in MyApp.exe: 0xC0000005: Access violation reading location 0x00000000. The call stack is not much left either it only lists code in NT.dll > 00000000() ntdll.dll!7c9032a8() [Frames below may be incorrect and/or missing, no symbols loaded for ntdll.dll] ntdll.dll!7c90327a() ntdll.dll!7c92aa0f() ntdll.dll!7c90e48a() ntdll.dll!7c9032a8() I am not able to find the problem using break points or stepping through my code. The application "seems" to run normally if run using F5 in VS. Whats the best method to track this problem down?
Where is the stack overflow from your question title? Access violations generally indicate an invalid pointer dereference. Use your revision history to find the first version where things started going boom, then critically analyze all pointer stuff going on in and around the code modified in that revision.
1,657,484
1,657,518
Can you give an example of stack overflow in C++?
Can you give an example of stack overflow in C++? Other than the recursive case: void foo() { foo(); }
The typical case that does not involve infinite recursion is declaring an automatic variable on the stack that is too large. For example: int foo() { int array[1000000]; }
1,657,643
1,657,813
How are C++-style comments handled in GCC 4.3.3 by default?
I'm using GCC 4.3.3 on Ubuntu 9.04 64-bit and was getting errors using C++-style comments in C code. When I say "by default" in the title, I mean simply invoking gcc test.c According to the GCC 4.3.3 docs (here), this is supported...yet I got the errors anyway. These errors went away with a simple -std=c99 addition to my compile string, so my problem is solved. Curious if any GCC experts out there had an explanation for this, as it seems to me to be a clear contradiction to the documentation. #include <stdio.h> // this is a comment int main( void ) { return 0; }
By defualt GCC is using C89/90 standard with GCC extensions. Strictly speaking by default it is not adhering to any specific standard, since by default it will not issue any diagnostic messages in situations when such messages are required by the standard. You need to run gcc in -ansi -pedantic mode (possibly also -Wall) in order to make it stick to the standard. And in this case you'll have, once again, C89/90.
1,657,673
1,657,719
"Trap" control-d and control-c
I have a console program and I want if the user press ctrl-z the program exits and if he press ctrl-c nothing happens. In Bash i'd put a trap, what I should use in C++?
In Unix use signal() in <signal.h> to register a function to invoke upon receiving a signal. For example: #include <signal.h> void leave(int sig); // ... { signal(SIGINT,leave); for(;;) getchar(); } // Beware: calling library fn from signal handler isn't std-conforming // and may not work. void leave(int sig) { exit(sig); }
1,657,807
1,657,842
Problems returning vector stack reference
I am working on an application that builds a vector of structs for items in a given directory and returns a reference of the vector for it to be read, I receive the following errors when attempting to compile the example code below: 1. 'class std::vector<indexStruct, std::allocator<indexStruct> >' has no member named 'name' 2. no matching function for call to `std::vector<indexStruct, std::allocator<indexStruct> >::push_back(std::vector<indexStruct, std::allocator<indexStruct> >&)' exampleApp.cpp #include "exampleApp.h" exampleApp::exampleApp() { this->makeCatalog(); } char* findCWD() { char* buffer = new char[_MAX_PATH]; return getcwd(buffer, _MAX_PATH); } void exampleApp::makeCatalog() { char* cwd = this->findCWD(); vector<indexStruct> indexItems; this->indexDir(cwd, indexItems); } void exampleApp:indexDir(char* dirPath, vector<indexStruct>& indexRef) { DIR *dirPointer = NULL; struct dirent *dirItem = NULL; vector<indexStruct> indexItems; vector<indexStruct> indexItem; try { if ((dirPointer = opendir(dirPath)) == NULL) throw 1; while (dirItem = readdir(dirPointer)) { if (dirItem == NULL) throw 2; if (dirItem->d_name[0] != '.') { indexItem.name = dirItem->d_name; indexItem.path = dirPath; indexItems.push_back(indexItem); indexItem.clear(); } } indexRef.swap(indexItems); closedir(dirPointer); } catch(int errorNo) { //cout << "Caught Error #" << errorNo; } } exampleApp.h #ifndef EXAMPLEAPP_H #define EXAMPLEAPP_H #include <iostream.h> #include <dirent.h> #include <stdlib.h> #include <vector.h> using namespace std; struct indexStruct { char* name; char* path; }; class exampleApp { public: exampleApp(); private: char* findCWD(); void makeCatalog(); void indexDir(char* dirPath, vector<indexStruct>& indexRef); }; #endif What am I doing wrong here, and is there a better way going about this?
You've made 'indexItem' a vector, you probably just want it to be the type you want to put in 'indexItems'. Also, I'd create the new struct in your loop: while (dirItem = readdir(dirPointer)) { if (dirItem == NULL) throw 2; if (dirItem->d_name[0] != '.') { indexStruct indexItem; indexItem.name = dirItem->d_name; indexItem.path = dirPath; indexItems.push_back(indexItem); } }
1,657,830
1,658,249
C++ template specialization via a base class
I want to be able to make the compiler shout when i call a constructor of foo with a class that is NOT derived from _base*. The current code allows only for foo<_base*> itself. Any easy solution ? class _base { public: // ... }; class _derived: public _base { public: // ... }; template <typename T> class foo { public: foo () { void TEMPLATE_ERROR; } }; template <> foo<_base*>::foo () { // this is the only constructor } main-code: foo<_base*> a; // should work foo<_derived*> b; // should work (but doesnt) foo<int*> c; // should not work (and infact doesnt)
Without Boost you can use something like the following to determine whether a pointer-to-type can be implicitly cast to another pointer-to-type: template <class Derived, class Base> struct IsConvertible { template <class T> static char test(T*); template <class T> static double test(...); static const bool value = sizeof(test<Base>(static_cast<Derived*>(0))) == 1; }; To make it trigger an error at compile-time, you can now use value in an expression that causes an error if it is false, for example typedef a negative-sized array. template <typename T> class foo { public: foo () { typedef T assert_at_compile_time[IsConvertible<T, _base>::value ? 1 : -1]; } };
1,657,883
1,657,924
Variable number of arguments in C++?
How can I write a function that accepts a variable number of arguments? Is this possible, how?
You probably shouldn't, and you can probably do what you want to do in a safer and simpler way. Technically to use variable number of arguments in C you include stdarg.h. From that you'll get the va_list type as well as three functions that operate on it called va_start(), va_arg() and va_end(). #include<stdarg.h> int maxof(int n_args, ...) { va_list ap; va_start(ap, n_args); int max = va_arg(ap, int); for(int i = 2; i <= n_args; i++) { int a = va_arg(ap, int); if(a > max) max = a; } va_end(ap); return max; } If you ask me, this is a mess. It looks bad, it's unsafe, and it's full of technical details that have nothing to do with what you're conceptually trying to achieve. Instead, consider using overloading or inheritance/polymorphism, builder pattern (as in operator<<() in streams) or default arguments etc. These are all safer: the compiler gets to know more about what you're trying to do so there are more occasions it can stop you before you blow your leg off.
1,657,988
1,657,992
Resolving "'hi' is not recognized as internal or external command..." error using C++ with codeblocks on Windows Vista?
I am learning C++ in school now. Currently using C++ with codeblocks on my windows vista laptop. I noticed whenever I try to use functions from imported classes from the Clibrary I get an error in the console. " 'hi' is not recgonized as internal or external command, operable command or batch file " My code looks like this ... #include <iostream> #include <cstdlib> using namespace std; int main() { system("hi"); return 0; } Just something simple you can see, however I am getting that error. I can use the iostream fine, I have tested the io include and that works... is there something else I need to install to be able to use the cstdlib? Thank you, Zach Smith
The error is exactly what it looks like: you're trying to execute with system a command that simply does not exist, so you'll get just the same error if you typed hi at a command prompt (codeblocks has nothing to do with it). Try using e.g. system("echo hi") or any other command that does exist and your results might be better.
1,658,061
1,658,074
Organising project dependencies
I'm with a fairly large team and we are running into problem with the other libraries we depend on, and getting the same project files to work for every one. The problem is that many people have more than one version of the same library (eg the project users boost 1.36, and I use boost 1.39 for some of my other stuff), and every developer has these in different places (eg I use C:\lib\c++\boost_1_36). As a result right now all the developers have to add a fairly large number of entries to each projects "Additional Include Directories", and "Additional Library Directories", which is a pain, especially with trying to get new members set up correctly (eg making sure the correct static/dynamic dependencies are linked for each configuration, which is made worse by most libraries using a common name for all the .lib and .dll files, rather than say like how boost does it with the file name reflecting the configuration and auto-linking). I was thinking of making use of the macros in the project properties, with things like "$(MYSQL_HOME)\lib\opt" in the "Additional Include Directories", however I cant see a way to define my own ones (like MYSQL_HOME))
You can use property sheets to help manage dependencies and other common project settings. Property sheets also allow you to define user-defined macros, which is what you need to do to define your own macros like MYSQL_HOME
1,658,469
1,658,582
How do I configure indentation in vim in a specific way?
If I type the following void main(int blah, and then press enter, I want to continue here: float blah); How can I achieve this?
:set cino=(0 For more about cinoption see here.
1,658,768
1,658,792
Moving Qt UI code out to separate class
I'm just starting with Qt. Despite spending sometime on it this evening, I'm struggling to move my UI setup code out of main into it's own class. #include <QtGui> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *window = new QWidget; QLabel *hw = new QLabel(QObject::tr("Hello World!")); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(hw); window->setLayout(layout); window->show(); return app.exec(); } I've tried making my own class and passing window to it but run into compilation errors. main.cpp: #include <QtGui> #include "hworld.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QDialog *hWorld = new hWorld; hWorld->show(); return app.exec(); } hworld.h: #ifndef HWORLD_H #define HWORLD_H #include <QtGui> class hWorld : public QDialog { Q_OBJECT public: hWorld(QWidget *parent = 0); ~hWorld(); private: void setup(); }; #endif // HWORLD_H hworld.cpp: #include <QtGui> #include "hworld.h" hWorld :: hWorld(QWidget *parent) : QDialog(parent) { setup(); } hWorld :: ~hWorld() { } void hWorld :: setup() { QLabel *hw = new QLabel(QObject::tr("Hello World!")); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(hw); setLayout(layout); setWindowTitle("Test App"); } Compilation errors: main.cpp: In function ‘int main(int, char**)’: main.cpp:8: error: expected type-specifier before ‘hWorld’ main.cpp:8: error: cannot convert ‘int*’ to ‘QDialog*’ in initialization main.cpp:8: error: expected ‘,’ or ‘;’ before ‘hWorld’ make: *** [main.o] Error 1 Changing main, means this compiles but I get a blank window (because the constructors not called?): QDialog hWorld; hWorld.show();
Shouldn't you use a different name for the class and the instantiated variable? QDialog *hWorld = new hWorld; is quite confusing and the source of the error you get, use HWorld for the class instead (for example), since it is common use to start a type name with an upper case (upper camel casing). Also, is the change from QWidget to QDialog on purpose?
1,658,821
1,658,831
C++ operator[] syntax
Just a quick syntax question. I'm writing a map class (for school). If I define the following operator overload: template<typename Key, typename Val> class Map {... Val* operator[](Key k); What happens when a user writes: Map<int,int> myMap; map[10] = 3; Doing something like that will only overwrite a temporary copy of the [null] pointer at Key k. Is it even possible to do: map[10] = 3; printf("%i\n", map[10]); with the same operator overload?
The way it works with std::map is that, if the key doesn't exist, the map class will insert a default value and then return an lvalue (an assignable reference to the value associated with the key), so it can be assigned a new value. So, in the following code sample, assuming map is empty, this will insert 10 into the map and associate it with a value of 3. map[10] = 3; With your custom map class, operator[] should first check if the Key k exists, and if not, insert a new key/value pair (using the default constructor of typename Val) into the map. You can then return a reference to the Value associated with the new key, so the user can assign a value to it. Note that this means that Val must be Assignable and have a default constructor. This allows operator[] to be used both for insertion and lookup. You should also overload a const version of operator[], which of course only supports lookup. Edit: I now noticed in your code that you are returning a pointer. If you want to use the insert/lookup paradigm for operator[] used by std::map, it makes more sense to return a reference. Returning a pointer gives you the advantage that you can examine the return value of operator[] for NULL to check if the key doesn't exist, but again, if you want operator[] to provide both lookup and insert functionality, a reference would be the way to go here.
1,658,956
1,659,688
C++ deque's iterator invalidated after push_front()
Just now, I'm reading Josuttis' STL book. As far as I know -- c++ vector is a c-array that can be reallocated. So, I understand, why after push_back() all iterators and references can become invalid. But my question is about std::deque. As I know it is array of large blocks (c-array of c-arrays). So push_front() inserts element at the beginning and if there is no space, deque allocates new block, and places the element at allocated block's end. After insert() in the middle all references and iterators become invalid and I understand why -- all elements are moved. But I really misunderstand the phrase "...after push_back() and push_front() all references stays valid, but iterators don't" (same phrase can be found @ standard:23.2.2.3) What does it mean?! If references are valid, than deque couldn't reallocate (== move) its elements. So why iterators become invalid? Why can't I use them after non-moving-elements insertion? Or does the phrase mean, that I can't be sure about iterators equality to begin() or end() and overflow? Also, I wanna mention, that after erase() all iterators and references stay valid (except the erased one :-) ). PS: please don't answer in "standard" form: "it can't be used because THE STANDARD says so". I wanna understand why, what can happen.
I think that the reason iterators get invalidated but references not might be because of the possible deque implementation of an array of pointers to the deque's pages that store the elements. A reference to an element in a deque will refer directly to the element in a 'page'. However, an iterator into the deque might be dependant on the vector of pointers that point to the various pages. Inserting a new element into a deque at one or another end will never require reallocating and moving exsting data pages, but it might require adding to (and therefore reallocating & copying) the array of page pointers, invalidating any iterators that depended on the previous array of page pointers. Array of pointers (if this grows Data Pages and gets copied, (these never move iterators are invalid) due to insert at ends) ----------------- -------------------- +----------+ +----------+ | -+-------------->| | +----------+ +----------+ | -+---------+ | | +----------+ | +----------+ | -+---+ | | | +----------+ | | +----------+ | | | | | | | | +----------+ | +---->| | | +----------+ | | | | +----------+ | | | | +----------+ | | +----------+ +---------->| | +----------+ | | +----------+ | | +----------+
1,658,991
1,659,009
Understanding how the pointer referencing works
I am currently reading "Developer's Workshop to COM and ATL 3.0". Chapter 3 introduces GUIDs, referencing and comparisons. Pointers are painful. I could use some help in deciphering the REFGUID #define (see below) and how memcmp in IsEqualGUID works against the pointers. Given: typedef struct_GUID{ unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; How do I interpret this #define?: #define REFGUID const GUID * const How is the &rguid1 addressing the incoming variable? BOOL IsEqualGUID(REFGUID rguid1, REFGUID rguid2) { return !memcmp(&rguid1, &rguid2, sizeof(GUID)); }
The REFGUID is constant ptr to a constant guid (ie neither can change). Shoud the code not be? BOOL IsEqualGUID(REFGUID rguid1, REFGUID rguid2) { return !memcmp(rguid1, rguid2, sizeof(GUID)); } as memcmp takes: int memcmp(const void *s1, const void *s2, size_t n); The memcmp should be passed the pointers (rguidx) not the address of the pointer. if looks like the code was originally written with REGUID defined as a const GUID or const GUID reference (C++) perhaps
1,659,099
1,659,118
Why is it preferable to write func( const Class &value )?
Why would one use func( const Class &value ) rather than just func( Class value )? Surely modern compilers will do the most efficient thing using either syntax. Is this still necessary or just a hold over from the days of non-optimizing compilers? Just to add, gcc will produce similar assembler code output for either syntax. Perhaps other compilers do not? Apparently, this is just not the case. I had the impression from some code long ago that gcc did this, but experimentation proves this wrong. Credit is due to to Michael Burr, whose answer to a similar question would be nominated if given here.
There are 2 large semantic differences between the 2 signatures. The first is the use of & in the type name. This signals the value is passed by reference. Removing this causes the object to be passed by value which will essentially pass a copy of the object into the function (via the copy constructor). For operations which simply need to read data (typical for a const &) doing a full copy of the object creates unnecssary overhead. For classes which are not small or are collections, this overhead is not trivial. The second is the use of const. This prevents the function from accidentally modifying the contents of value via the value reference. It allows the caller some measure of assurance the value will not be mutated by the function. Yes passing a copy gives the caller a much deeper assurance of this in many cases.
1,659,155
1,659,321
I have a floating-point overflow problem
Well, I'm a beginner, it's my year as a computer science major. I'm trying to do an exercise from my textbook that has me use a struct called MovieData that has a constructor that allows me to initialize the member variables when the MovieData struct is created. Here's what my code looks like: #include <iostream> #include <iomanip> #include <string> using namespace std; // struct called MovieData struct MovieData { string title; string director; unsigned year; unsigned running_time; double production_cost; double first_year_revenue; MovieData() // default constructor { title = "Title"; director = "Director"; year = 2009; running_time = 90; production_cost = 1000000.00; first_year_revenue = 1000000.00; } // Constructor with arguments: MovieData(string t, string d, unsigned y, unsigned r, double p, double f) { title = t; director = d; year = y; running_time = r; } }; // function prototype: void displayMovieData(MovieData); // main: int main() { // declare variables: MovieData movie, terminator("Terminator", "James Cameron", 1984, 120, 5000000, 2000000); // calling displayMovieData function for movie and terminator // so it will display information about the movie: displayMovieData(movie); displayMovieData(terminator); return 0; } // displayMovieData function: // It receives struct MovieData variable as // an argument and displays that argument's // movie information to the user. void displayMovieData(MovieData m) { cout << m.title << endl; cout << m.director << endl; cout << m.year << endl; cout << m.running_time << endl; cout << fixed << showpoint << setprecision(2); cout << m.production_cost << endl; cout << m.first_year_revenue << endl << endl; } here is the output I received: Title Director 2009 90 1000000.00 1000000.00 Terminator James Cameron 1984 120 -92559631349317830000000000000000000000000000000000000000000000.00 -92559631349317830000000000000000000000000000000000000000000000.00 Press any key to continue . . . Compiled on Microsoft Visual C++ 2008 Express Edition. My question is, is this happening due to an overflow of the double data-type? I even tried it using long double and the same thing occurs. even though i used 5mil as production_cost and 2mil as first_year_revenue both numbers output are the same. Using my default constructor properly prints out 1000000. Am I using the correct data-type in this case? I want it to be double because it's a monetary number, dollars and cents. Thanks for whatever help comes my way. Sorry about my long question. It's my first post on SO, so any feedback on correct format of posting questions will be great, Thanks!
Thanks for posting your complete code, the problem is now obvious. The following function is the problem: MovieData(string t, string d, unsigned y, unsigned r, double p, double f) { title = t; director = d; year = y; running_time = r; } You have omitted the following statements: production_cost = p; first_year_revenue = f; Without those statements, production_cost and first_year_revenue are not initialised when using the above constructor. This exercise highlights the need to post the exact code you're using when posting questions on Stack Overflow. The first version of the code you posted was different, and did not contain this bug.
1,659,159
1,659,176
python executing existent (&big) c++ code
I have a program in C++ that uses the cryptopp library to decrypt/encrypt messages. It offers two interface methods encrypt & decrypt that receive a string and operate on it through cryptopp methods. Is there some way to use both methods in Python without manually wrapping all the cryptopp & files included? Example: import cppEncryptDecrypt string foo="testing" result = encrypt(foo) print "Encrypted string:",result
If you can make a DLL from that C++ code, exposing those two methods (ideally as "extern C", that makes all interfacing tasks so much simpler), ctypes can be the answer, not requiring any third party tool or extension. Otherwise, it's your choice between cython, good old SWIG, SIP, Boost, ... -- many, many such 3rd party tools will let your Python code call those two C++ entry points without any need for wrapping anything else but them.
1,659,302
1,659,308
How does call by value and call by reference work in C?
In a C program, how does function call by value work, and how does call by reference work, and how do you return a value?
Call by value void foo(int c){ c=5; //5 is assigned to a copy of c } Call it like this: int c=4; foo(c); //c is still 4 here. Call by reference: pass a pointer. References exist in c++ void foo(int* c){ *c=5; //5 is assigned to c } Call it like this: int c=0; foo(&c); //c is 5 here. Return value int foo(){ int c=4; return c;//A copy of C is returned } Return through arguments int foo(int* errcode){ *errcode = OK; return some_calculation }
1,659,440
1,659,466
32-bit to 16-bit Floating Point Conversion
I need a cross-platform library/algorithm that will convert between 32-bit and 16-bit floating point numbers. I don't need to perform math with the 16-bit numbers; I just need to decrease the size of the 32-bit floats so they can be sent over the network. I am working in C++. I understand how much precision I would be losing, but that's OK for my application. The IEEE 16-bit format would be great.
std::frexp extracts the significand and exponent from normal floats or doubles -- then you need to decide what to do with exponents that are too large to fit in a half-precision float (saturate...?), adjust accordingly, and put the half-precision number together. This article has C source code to show you how to perform the conversion.
1,659,547
1,659,599
am trying to create class to encapsulate toolbar but the background turns black. c++ win32api
I created a simple class to hide the details of creating a toolbar in win32 API but I don't like the toolbars it is producing. (See image for clarification. I don't have reputation points so I have just posted a link) http://i35.tinypic.com/1zmfeip.jpg I have no idea now the black background is coming into my application. Here is the class declaration in file CToolBar.h #ifndef _CTOOLBAR_H #define _CTOOLBAR_H #include<windows.h> #include<commctrl.h> class CToolBar { public: CToolBar();//constructor ~CToolBar();//destructor void AddButton(int iconID, int command);//add Both a button, its icon and its command ID void Show();//display the toolbar void Initialise(HINSTANCE hInst, HWND hParent); protected: HINSTANCE m_hInst; HWND m_hParent; HWND m_hToolBar; HIMAGELIST m_hImageList; TBBUTTON m_Tbb[4]; //toolbar buttons int m_numberButtons; }; #endif here is the implementation in file CToolBar.cpp //CToolBar.cpp #include "CToolBar.h" #include<windows.h> #include<commctrl.h> CToolBar::CToolBar()//the constructor { m_hImageList=ImageList_Create(32, 32, ILC_COLOR32, 0, 15);//returns NULL if the function fails //finish other initialisations InitCommonControls();//initialise commctrl.dll whatever.. or else your toolbar wont appear } void CToolBar::Initialise(HINSTANCE hInst, HWND hParent) { m_hInst=hInst; m_hParent=hParent; m_hToolBar=CreateWindowEx( WS_EX_PALETTEWINDOW , TOOLBARCLASSNAME, "", WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS |WS_VISIBLE|TBSTYLE_BUTTON | TBSTYLE_TOOLTIPS | CCS_ADJUSTABLE | CCS_TOP , 0, 0, 0, 0, m_hParent, NULL, m_hInst, 0); } CToolBar::~CToolBar()//destructor { ImageList_Destroy(m_hImageList); } void CToolBar::AddButton(int iconID, int command) { HICON hIcon = LoadIcon(m_hInst, MAKEINTRESOURCE(iconID)); ImageList_AddIcon(m_hImageList, hIcon); DeleteObject(hIcon); if(iconID!= -1)//-1 means the separator. The rest are mere buttons { m_Tbb[m_numberButtons].iBitmap =m_numberButtons; m_Tbb[m_numberButtons].idCommand = command; m_Tbb[m_numberButtons].fsState = TBSTATE_ENABLED; m_Tbb[m_numberButtons].fsStyle = TBSTYLE_BUTTON; m_Tbb[m_numberButtons].dwData = 0; m_Tbb[m_numberButtons].iString = 0; } else//ie if (iconID== -1) ; then display the separator. the command value is ignored { m_Tbb[m_numberButtons].iBitmap =-1; m_Tbb[m_numberButtons].idCommand = 0; m_Tbb[m_numberButtons].fsState = TBSTATE_ENABLED; m_Tbb[m_numberButtons].fsStyle = TBSTYLE_SEP; m_Tbb[m_numberButtons].dwData = 0; m_Tbb[m_numberButtons].iString = 0; } m_numberButtons++; } void CToolBar::Show() { SendMessage(m_hToolBar, TB_SETIMAGELIST , (WPARAM)0, (LPARAM)m_hImageList); SendMessage(m_hToolBar, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0);//message for backward //compatibility SendMessage(m_hToolBar, TB_ADDBUTTONS, m_numberButtons, (LPARAM)m_Tbb); SendMessage(m_hToolBar,WM_SIZE,0,0); ShowWindow(m_hToolBar, SW_SHOW); } How i used the class in main.cpp, i created a global instance of the class. CToolBar myToolBar; in the callback procedure, under WM_CREATE, I used some member functions. case WM_CREATE: myToolBar.Initialise(g_hInst,hwnd); myToolBar.AddButton(IDI_OPEN, ID_OPEN); myToolBar.AddButton(IDI_MAIN,ID_OPEN);//Separator button myToolBar.AddButton(IDI_CLOSE, ID_CLOSE); myToolBar.AddButton(IDI_CLOSEALL, ID_CLOSE); myToolBar.Show(); break; That's about it.
Try modifying the flags parameter of ImageList_Create to include ILC_MASK as well
1,659,641
1,695,712
Array PopFront Method C++
Trying not to lose it here. As you can see below I have assigned intFrontPtr to point to the first cell in the array. And intBackPtr to point to the last cell in the array...: bool quack::popFront(int& nPopFront) { nPopFront = items[top+1].n; if ( count >= maxSize ) return false; else { items[0].n = nPopFront; intFrontPtr = &items[0].n; intBackPtr = &items[count-1].n; } for (int temp; intFrontPtr < intBackPtr ;) { ++intFrontPtr; temp = *intFrontPtr; *intFrontPtr = temp; } return true; } In the else statement I'm simply reassigning to ensure that my ptrs are where I want them. For some reason I'm popping off the back instead of off the front. Anyone care to explain?
I'm not entirely sure I understand what you're trying to do, but if I;m guessing right you're trying to 'pop' the 1st element of the array (items[0]) into the nPopFront int reference, then move all the subsequent elements of the array over by one so that the 1st element is replaced by the 2nd, the 2nd by the 3rd, and so on. After this operation, the array will contain one less total number of elements. Not having the full declaration of the quack class makes most of the following guesswork, but here goes: I'm assuming that item[0] represents the 'front' of your array (so it's the element you want 'popped'). I'm also assuming that 'count` is the number of valid elements (so item[count-1] is the last valid element, or the 'back' of the array). Given these assumptions, I'm honestly not sure what top is supposed to represent (so I might be entirely wrong on these guesses). Problem #1: your nPopFront assignment is reversed, it should be: nPopFront = items[0].n; Problem #2; your for loop is a big no-op. It walks through the array assigning elements back to their original location. I think you want it to look more like: for (int i = 1; i < count; ++i) { items[i-1].n = items[i].n; // move elements from back to front } Finally, you'll want to adjust count (and probably top - if you need it at all) before you return to adjust the new number of elements in the data structure. The whole thing might look like: bool quack::popFront(int& nPopFront) { if ( count >= maxSize ) return false; if ( count == 0 ) return false; // nothing to pop nPopFront = items[0].n; intFrontPtr = &items[0].n; // do we really need to maintain these pointers? intBackPtr = &items[count-1].n; for (int i = 1; i < count; ++i) { items[i-1].n = items[i].n; // move elements from back to front } count -= 1; // one less item in the array return true; }
1,659,932
1,659,941
"Expected constructor, destructor, or type conversion before '<' token"
I'm running into a syntax/parsing error, but I can't seem to locate it. DataReader.h:11: error: expected constructor, destructor, or type conversion before '<' token Here is DataReader.h: #include <fstream> #include <iostream> #include <vector> #ifndef DATA_H #define DATA_H #include "Data.h" #endif vector<Data*> DataReader(); // This is line 11, where the error is.. And this is the .cpp file: #include "DataReader.h" using namespace std; vector<Data*> DataReader() { ..... } I skipped the content of DataReader() because I think it's irrelevant, but I can post it if needed. Thanks for any input/suggestions.
In your header file, you need to explicitly use std::vector rather than just vector. Also, I'm guessing that "Data.h" contains statements of the form: #ifndef DATA_H #define DATA_H ... #endif That's fine, but you should not use these include guards across #include "Data.h" as well, only within the file itself.
1,660,195
1,660,220
C++ How to find the biggest key in a std::map?
At the moment my solution is to iterate through the map to solve this. I see there is a upper_bound method which can make this loop faster, but is there a quicker or more succinct way?
The end: m.rbegin(); Maps (and sets) are sorted, so the first element is the smallest, and the last element is the largest. By default maps use std::less, but you can switch the comparer and this would of course change the position of the largest element. (For example, using std::greater would place it at begin(). Keep in mind rbegin returns an iterator. To get the actual key, use m.rbegin()->first. You might wrap it up into a function for clarity, though I"m not sure if it's worth it: template <typename T> inline const typename T::key_type& last_key(const T& pMap) { return pMap.rbegin()->first; } typedef std::map</* types */> map_type; map_type myMap; // populate map_type::key_type k = last_key(myMap);
1,660,281
1,660,306
Stream and c++ - parsing file
I did it before... But I forgot. I have a file with some data: 0.5 0.6 0.7 1.2 1.5 How can I read this in c++? I did it with stream... something like: float var = 0; stream >> var;
Something like this? std::ifstream stream("C:/a.txt"); float var = 0; while(stream >> var) { //Do some processing }
1,660,334
1,660,358
How can I debug St9bad_alloc failures in gdb in C?
I have a program failing with: terminate called after throwing an instance of 'std::bad_alloc' what(): St9bad_alloc I imagine it's something to do with malloc/free, but I don't know which one. What breakpoint can I in gdb set that will break on the error so that I can view a stack trace? The program is a combination of C and C++, compiled with gcc 3.4.2.
It is not really malloc/free which causes the exception, it is "new" which is definitely in C++ part of your application. It looks like you are providing a parameter which is too big for "new" to allocate. 'std::bad_alloc' is caused by the following code for example: int * p = new int[50000000]; What does backtrace says when you load crash dump into gdb? If you cannot generate dump, you can ask GDB to stop when exception is thrown or caught. Unfortunately, some versions of GDB support only the following syntax: catch throw which allows you to break application when any exception is thrown. However, in help you see that it should be possible to run catch throw std::bad_alloc in newer versions. And don't forget that: (gdb) help catch is a good source for other useful information.
1,660,352
1,660,425
C++ Array initialization
the code below gives compilation error when I try to create test t[2]; because there is no default constructor for this. But if I create Test t[2] = {test(1,2), test(2,3)}; Then it works fine. 1)But think of a situation, if we want to create more then 100 array element. We need to create 100 element in the curly braces like.. Test t[100] = {test(1,2), test(1,2)……/100 times/}; The above code is difficult to maintain. One more solution is to create public member function which takes 2 integers and run in a loop. This solves the problem but i want to know any other good method. 2) If I create it using new Test *t = new test[10]; I get compilation error(No default constructor). How to solve this. class test { int _a;int _b; public: test(int a, int b); void display(); }; int _tmain(int argc, _TCHAR* argv[]) { test t[10]; for (int i = 0 ; i< 10; i++) t[i].display(); }
In order to construct your 10 elements in the array the compiler somehow has to instaciate them through a constructor. For arrays only a default constructor (taking no arguments) can bes used, as you can not pass any arguments to the elements in the array. Therfor you have to proved a constructor test::test() taking no arguments.
1,660,492
17,189,385
UTF-8 output on Windows console
The following code shows unexpected behaviour on my machine (tested with Visual C++ 2008 SP1 on Windows XP and VS 2012 on Windows 7): #include <iostream> #include "Windows.h" int main() { SetConsoleOutputCP( CP_UTF8 ); std::cout << "\xc3\xbc"; int fail = std::cout.fail() ? '1': '0'; fputc( fail, stdout ); fputs( "\xc3\xbc", stdout ); } I simply compiled with cl /EHsc test.cpp. Windows XP: Output in a console window is ü0ü (translated to Codepage 1252, originally shows some line drawing charachters in the default Codepage, perhaps 437). When I change the settings of the console window to use the "Lucida Console" character set and run my test.exe again, output is changed to 1ü, which means the character ü can be written using fputs and its UTF-8 encoding C3 BC std::cout does not work for whatever reason the streams failbit is setting after trying to write the character Windows 7: Output using Consolas is ��0ü. Even more interesting. The correct bytes are written, probably (at least when redirecting the output to a file) and the stream state is ok, but the two bytes are written as separate characters). I tried to raise this issue on "Microsoft Connect" (see here), but MS has not been very helpful. You might as well look here as something similar has been asked before. Can you reproduce this problem? What am I doing wrong? Shouldn't the std::cout and the fputs have the same effect? SOLVED: (sort of) Following mike.dld's idea I implemented a std::stringbuf doing the conversion from UTF-8 to Windows-1252 in sync() and replaced the streambuf of std::cout with this converter (see my comment on mike.dld's answer).
It's time to close this now. Stephan T. Lavavej says the behaviour is "by design", although I cannot follow this explanation. My current knowledge is: Windows XP console in UTF-8 codepage does not work with C++ iostreams. Windows XP is getting out of fashion now and so does VS 2008. I'd be interested to hear if the problem still exists on newer Windows systems. On Windows 7 the effect is probably due to the way the C++ streams output characters. As seen in an answer to Properly print utf8 characters in windows console, UTF-8 output fails with C stdio when printing one byte after after another like putc('\xc3'); putc('\xbc'); as well. Perhaps this is what C++ streams do here.
1,660,652
1,660,668
What limits my use of the stack in terms of memory?
In windows (or any other OS for that matter) what determines how much stack I can use? The name of this very website makes me assume it's possible to run out of stack so should I avoid putting large amounts of data on the stack?
It is language specific, Compiler specific and probably OS specific, but you should put large amount of data on the heap and not on the stack. Other SO post about this There are ways to change the stack size - but I wouldn't mess with it ! If you want to know your stack size using trial and error - just create an array on the stack and see how much it lets you...
1,660,712
37,744,393
Specification of source charset encoding in MSVC++, like gcc "-finput-charset=CharSet"
I want to create some sample programs that deal with encodings, specifically I want to use wide strings like: wstring a=L"grüßen"; wstring b=L"שלום עולם!"; wstring c=L"中文"; Because these are example programs. This is absolutely trivial with gcc that treats source code as UTF-8 encoded text. But, straightforward compilation does not work under MSVC. I know that I can encode them using escape sequences but I would prefer to keep them as readable text. Is there any option that I can specify as command line switch for "cl" in order to make this work? There are there any command line switch like gcc'c -finput-charset? If not how would you suggest make the text natural for user? Note: adding BOM to UTF-8 file is not an option because it becomes non-compilable by other compilers. Note2: I need it to work in MSVC Version >= 9 == VS 2008 The real answer: There is no solution
For those who subscribe to the motto "better late than never", Visual Studio 2015 (version 19 of the compiler) now supports this. The new /source-charset command line switch allows you to specify the character set encoding used to interpret source files. It takes a single parameter, which can be either the IANA or ISO character set name: /source-charset:utf-8 or the decimal identifier of a particular code page (preceded by a dot): /source-charset:.65001 The official documentation is here, and there is also a detailed article describing these new options on the Visual C++ Team Blog. There is also a complementary /execution-charset switch that works in exactly the same way but controls how narrow character- and string-literals are generated in the executable. Finally, there is a shortcut switch, /utf-8, that sets both /source-charset:utf-8 and /execution-charset:utf-8. These command-line options are incompatible with the old #pragma setlocale and #pragma execution-character-set directives, and they apply globally to all source files. For users stuck on older versions of the compiler, the best option is still to save your source files as UTF-8 with a BOM (as other answers have suggested, the IDE can do this when saving). The compiler will automatically detect this and behave appropriately. So, too, will GCC, which also accepts a BOM at the start of source files without choking to death, making this approach functionally portable.
1,660,765
1,661,401
Joining a boost::thread instance in the destructor
I'm seeing an issue where a call to boost's thread->join in a destructor leads to a deadlock. I don't understand why, and I'm not too keen on keeping code that just works (and I don't understand why it does) in the project. Class declaration (I've stripped the run() method of try/catch for brevity: according to the boost thread documentation, the result should be the same with or without it): class B { public: void operator()(){run();} void run(); void shutdown(); ~B(); B(); boost::thread *thr; bool shutdown_requested; }; void B::shutdown() { shutdown_requested = true; if (thr != NULL) { thr->interrupt(); thr->join(); // deadlock occurs here! delete thr; thr = NULL; } } B::~B() { shutdown(); } B::B() { thr = new boost::thread(boost::ref(*this)); } void B::run() { while (!shutdown_requested) { boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); xt.sec += 30; boost::this_thread::sleep(xt); } } Snippet which does not work: int main() { B *b = new B; Sleep(5000); printf("deleting \n");fflush(stdout); // b->shutdown(); delete b; printf("done\n");fflush(stdout); return 0; } Snippet which works: int main() { B *b = new B; Sleep(5000); printf("deleting \n");fflush(stdout); b->shutdown(); delete b; printf("done\n");fflush(stdout); return 0; } I think the reason for this behavior has something to do with this snippet of the boost documentation: the user of Boost.Thread must ensure that the referred-to object outlives the newly-created thread of execution. But I don't really understand why the deadlock - joining the thread would not call the destructor on B and the object itself is not deleted when the run() method is supposed to exit.
I've found the issue: it boils down to an over-zealous programmer. I had originally compiled my project using DUMA (http://sourceforge.net/projects/duma/) to see if my implementation of the current module was leak-free. Unfortunately, my test sandbox also had the duma settings on, which I did not realize until I stepped through the code in a debugger. After removing all memory leak-detection, everything works as expected.
1,661,007
1,661,013
not declared in this scope
I'm getting an error msg DataReader.h:13: error: 'String' was not declared in this scope DataReader.cpp:5: error: redefinition of 'std::vector<Data*, std::allocator<Data*> > DataReader' DataReader.h:13: error: 'std::vector<Data*, std::allocator<Data*> > DataReader' previously declared here DataReader.cpp:5: error: 'String' was not declared in this scope this is my cpp file #include "DataReader.h" using namespace std; vector<Data*> DataReader(String textFile) //line 5 that's giving error {........} and this my header file #include <fstream> #include <iostream> #include <vector> #include <string> #ifndef DATA_H #define DATA_H #include "Data.h" #endif std::vector<Data*> DataReader(String something); they work fine when i take out the string parameter and hard code the name of the string. but i need to use this function several times and would like to be able to pass in a string as a parameter. the string that i'm passing is name of a text file. am i mistaken somewhere? i can't seem to figure it out.. i mean what does it mean 'String' was not declared in this scope?? I am passing it and I included . something wrong with my parameter?? if you can shed some light to this matter, it would be greatly appreciated.. Dean
string should be lower case or std::string
1,661,062
1,661,067
How do I declare a string without assigning a value in C++?
I know that for an integer, you can use: int value; I tried: string str; but Visual C++ gave me an error. How do I declare it without assigning a value, then using cin >> str later on to assign it?
#include <string> int main() { std::string str; return 0; } Check this info on Namespaces by MSDN
1,661,131
1,661,167
C++ university course
Do you know any university which has its C++ course available online? I'm looking for something similar to MIT-style online lectures (lecture notes, projects and examples, assignments, exams, solutions and video content). This is what I've found on MIT, but id doesn't have video content.
I don't know about C++ specifically, but in terms of video lectures on programming concepts, check out this: http://academicearth.org/subjects/computer-science
1,661,154
1,661,207
std::string in a multi-threaded program
Given that: 1) The C++03 standard does not address the existence of threads in any way 2) The C++03 standard leaves it up to implementations to decide whether std::string should use Copy-on-Write semantics in its copy-constructor 3) Copy-on-Write semantics often lead to unpredictable behavior in a multi-threaded program I come to the following, seemingly controversial, conclusion: You simply cannot safely and portably use std::string in a multi-threaded program Obviously, no STL data structure is thread-safe. But at least, with std::vector for example, you can simply use mutexes to protect access to the vector. With an std::string implementation that uses COW, you can't even reliably do that without editing the reference counting semantics deep within the vendor implementation. Real-world example: In my company, we have a multi-threaded application which has been thoroughly unit-tested and run through Valgrind countless times. The application ran for months with no problems whatsoever. One day, I recompile the application on another version of gcc, and all of a sudden I get random segfaults all the time. Valgrind is now reporting invalid memory accesses deep within libstdc++, in the std::string copy constructor. So what is the solution? Well, of course, I could typedef std::vector<char> as a string class - but really, that sucks. I could also wait for C++0x, which I pray will require implementors to forgo COW. Or, (shudder), I could use a custom string class. I personally always rail against developers who implement their own classes when a preexisting library will do fine, but honestly, I need a string class which I can be sure is not using COW semantics; and std::string simply doesn't guarantee that. Am I right that std::string simply cannot be used reliably at all in portable, multi-threaded programs? And what is a good workaround?
Given that the standard doesn't say a word about memory models and is completely thread unaware, I'd say you can't definitely assume every implementation will be non-cow so no, you can't Apart from that, if you know your tools, most of the implementations will use non-cow strings to allow multi-threading.
1,661,410
1,663,360
How do I create a 64-bit native ATL C++ DLL in Visual Studio 2003?
I have a 32-bit ATL C++ in-proc COM server soultion. How do I port it to 64-bit Windows? I mean how do I make VC++7 emit 64-bit code? Is it possible with Visual Studio 2003?
You need a 64bit compiler that will compile long to a 64bit long. The version which was shipped in VS2005 would do. Later versions of Visual C++ and Windows SDK have higher versions of the compiler. 64bit support is disabled in standard or lower versions of Visual C++ but not in the freely available Windows SDK. Other compiler providers like Intel have their own products that supports Visual Studio and 64 bit.
1,661,526
1,661,614
Shorten nested namespace names
If you use nested namespaces, declarations in header files can get very long and unreadable. //header1 namespace test { namespace test1 { class Test {}; } } //namespace In header2 of the program: #include "header1" namespace test2 { class Test1 { void test(test::test1::Test &test) {} void test1(test::test1::Test &test) {} void test2(test::test1::Test &test1, test::test1::Test &test2) {} }; } Are there any possibilities to shorten the names in header2?
Here is my favorite technique: #include "header1" namespace test2 { class Test1 { private: typedef ::test::test1::Test MeaningfulName; void test(MeaningfulName &test) {} void test1(MeaningfulName &test) {} void test2(MeaningfulName &test1, MeaningfulName &test2) {} }; } I make my typedef aliases private, but I put them right at the beginning of the class declaration. It doesn't matter that they're private to the rest of the program because nobody will be using the aliased name, they will be using the actual type name or their own alias for the name. I also really prefer to use anchored namespace names to avoid later surprises. My rule for this is that I always use an anchored name unless the namespace is one I control and/or is part of the current project or package or whatever. Then I will use the shortest possible relative name. If that relative name would start from the root namespace, I still often use an anchored name. The main problem is the digraph <: which will crop up in template declarations a lot once you start using anchored names more often. You have to put in a space to avoid it, especially since digraph processing happens at a really early stage and can give you some very weird error messages.
1,661,529
1,661,564
Is Meyers' implementation of the Singleton pattern thread safe?
Is the following implementation, using lazy initialization, of Singleton (Meyers' Singleton) thread safe? static Singleton& instance() { static Singleton s; return s; } If not, why and how to make it thread safe?
In C++11, it is thread safe. According to the standard, §6.7 [stmt.dcl] p4: If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. GCC and VS support for the feature (Dynamic Initialization and Destruction with Concurrency, also known as Magic Statics on MSDN) is as follows: Visual Studio: supported since Visual Studio 2015 GCC: supported since GCC 4.3 Thanks to @Mankarse and @olen_gam for their comments. In C++03, this code wasn't thread safe. There is an article by Meyers called "C++ and the Perils of Double-Checked Locking" which discusses thread safe implementations of the pattern, and the conclusion is, more or less, that (in C++03) full locking around the instantiating method is basically the simplest way to ensure proper concurrency on all platforms, while most forms of double-checked locking pattern variants may suffer from race conditions on certain architectures, unless instructions are interleaved with strategically places memory barriers.
1,661,556
1,666,190
Use Eclipse's code completion for boost
I would like to profit from Eclipse's code completion for boost:shared_pointer in Eclipse 3.5 with CDT 6.0. Eclipse doesn't offer any completion while I'm writing the following code: #include <boost/shared_ptr.hpp> #include "A.h" typedef boost::shared_ptr<A> aPTR; int main() { aPTR test(new A); test->ge.... // no completion (there is a getter in class A) return 0; } The funny thing: My old Eclipse 3.4 with CDT 5.0 on my other computer performs code completion for boost-stuff without any problem. Do I need to proceed any configuration steps to get code completion with boost work? Do I have to index the boost files in /usr/include/boost/ in a special kind? Is there a way to force Eclipse to re-index the stuff. Finally: Yes I know this Post but I'm missing any concrete "next steps" in it. thanks
Eclipse CDT indexing of boost libraries starts struggling with version 1.37 (or even 1.36, couldn't verify that) already. My workaround to benefit from code completion while using an up-to-date boost version (1.39) is the following one: I have got two boost versions (1.35 and 1.39) on my computer. In the Debug Build Configuration (Settings/Directories) I set the include path to the old boost version. In the Release Build Configuration I set the include path to the actual boost library. I set the Indexer Option "Build Configuration for the Indexer" to "Use fixed build configuration" > Debug The indexer uses now the old library for indexing and code completion but the release version will still be compiled with the recent boost version. At least this worked for me. Please verify this for your build configuration, if you're suffering the same problem!! Sometimes, it seems to be rocket science.
1,661,575
1,662,369
How to associate non-member functions with a class in Doxygen?
I'm sure there's some way to do this with the \defgroup, \addgroup and \@{ \@} tags, but after a couple of hours of trial and (obviously) error, I'm asking SO..... I have: class C { public: void foo () const; }; and I have some helper non-member functions that really are part of C's interface, but aren't in the class: std::string format (const C& c, const std::string &fmt); I'd like the format function to appear on the same page as the class functions. Is that just not possible? Is the best I can do a "module" page, which lists C as a class (with a hyperlink to C's comments, and format as a function?
\relates (or \memberof) seem to be what you are looking for.
1,661,795
1,664,324
How to check if memory has aready been released in Destructor?
I have a simple tank wars style game using the allegro open source library. In my tank class, I initialize arrays of pointers to bitmap objects to 0. Then I create new objects with an allegro function create_bitmap which allocates the memory and initializes it. Then I go about my business as usual. The problem is, when I go to release the bitmap memory in the class destructor like a good OO boy, I crash the program because in this specific program, the allegro library does its cleanup (which releases the bitmap objects it created) before the class goes out of scope and is destroyed. It doesn't set my pointers to NULL again though so I can't check if the bitmaps are still valid and if I try to release them they will crash the program. Is there any way around this? Can I check for valid pointers if they are not NULL? How can I be SURE that the memory is freed if the class is used a different way within the program. As it stands right now, I'm essentially calling new without delete and I don't like it.
I think the problem is not that allegro releases the bitmaps itself (or otherwise you wouldn't need to release them at exit) but that allegro library has been deinitialized before the destructor is called. int main() { ObjectManagingBitmaps o; ... return 0; //allegro automatically shut down here } //o destructor invoked here END_OF_MAIN() What you can do to ensure that the destructor is invoked first is to use an artificial scope: int main() { { ObjectManagingBitmaps o; ... } //o destructor invoked here return 0; //allegro automatically shut down here } END_OF_MAIN()
1,661,912
1,662,052
Why does everybody use unanchored namespace declarations (i.e. std:: not ::std::)?
It seems to me that using unanchored namespaces is just asking for trouble later when someone puts in a new namespace that happens to have the same name as a root level namespace and mysteriously alters the meaning of a whole lot of programs. So, why do people always say std:: instead of ::std::. Do they really mean to be saying "I want to use whatever std is handy, not the root one."? Here is an example of what I mean: In fred/Foo.h: #include <string> namespace fred { class Foo { public: void aPublicMember(const std::string &s); }; } // end namespace fred In fred/Bar.h: namespace fred { namespace std { // A standard fred component class string { // Something rather unlike the ::std::string // ... }; } // namespace std class Bar { public: void aPublicMember(std::string &s); }; } // namespace fred In oops.cpp: #include <string> #include "fred/Bar.h" #include "fred/Foo.h" // Oops, the meaning of Foo is now different. Is that what people want, or am I missing something? And maybe you say that you should just never name a namespace std. And that's all well and good, but what about some other root level namespace then? Should any root level namespace anybody ever defines anywhere always be off-limits for a sub-namespace name? To clarify, I won't consider any answer that tells me std is special because I just used it as an example. I'm talking about a general issue, and I'm using std as a prop to illustrate it, though I do admit it's a rather startling prop.
The practical reason for unanchored namespaces is that one level of namespaces usually is enough. When it isn't, a second level is usually going to be used for implementation details. And finally, even when using multiple levels, they are still usually specified implicitly from root level. ie. even inside namespace ns1, you'd typically refer to ns1::ns2::foo instead of ns2::foo or ::ns1::ns2::foo. So, for these three reasons the ::ns1 form is redundant in normal cases. The only case where I'd consider it would be in submissions to Boost, because as a Boost author I won't know where my software will be used.
1,661,982
1,662,403
How do I get the full path for a filename command-line argument?
I've found lots of libraries to help with parsing command-line arguments, but none of them seem to deal with handling filenames. If I receive something like "../foo" on the command line, how do I figure out the full path to the file?
POSIX has realpath(). #include <stdlib.h> char *realpath(const char *filename, char *resolvedname); DESCRIPTION The realpath() function derives, from the pathname pointed to by filename, an absolute pathname that names the same file, whose resolution does not involve ".", "..", or symbolic links. The generated pathname is stored, up to a maximum of {PATH_MAX} bytes, in the buffer pointed to by resolvedname.
1,662,107
1,662,116
What's the difference between std::string and std::basic_string? And why are both needed?
What's the difference between std::string and std::basic_string? And why are both needed?
std::basic_string is a class template for making strings out of character types, std::string is a typedef for a specialization of that class template for char.
1,662,430
1,662,503
How can I force symbol a symbol reference in c++ (programmatically)
I'm trying to plug tcmalloc into a suite of software that we currently use at work. The software comprises of a lot of dll's. They all refer to a shared header file, so I can pragma link the library. However as none of the code refers to the symbol __tcmalloc the optimizer strips the dll. Now I don't want to have to edit 200 project files and add symbol references in each one. So my question is, is there a way to add a symbol reference programmatically? To add some clarity I am compiling under Visual Studio 2005.
Ah, for anyone searching to the answer to this it's as follows #pragma comment(linker, "/include:__tcmalloc")
1,662,624
1,662,644
c++: ifstream open problem with passing a string for text file name
i'm trying to pass a string from main to another function. this string is a name of text file that needs to be oepened. as far as i can see, i am passing the string alright, but when i try to use ifstream.open(textFileName), it doesn't quite work. but when i manually hardcode it as ifstream.open("foo.txt"), it works just fine. i would need to use this function several times so i would like to be able to pass in a string of text file name.. here's my main #ifndef DATA_H #define DATA_H #include "Data.h" #endif #ifndef DATAREADER_H #define DATAREADER_H #include "DataReader.h" #endif using namespace std; int main() { vector<Data*> database = DataReader("foo.txt"); return 0; } header of DataReader #include <fstream> #include <iostream> #include <vector> #include <string> #ifndef DATA_H #define DATA_H #include "Data.h" #endif using namespace std; vector<Data*> DataReader(string textFile); and finally the DataReader.cpp #include "DataReader.h" using namespace std; vector<Data*> DataReader(string textFile) { ifstream aStream; aStream.open(textFile); //line 11 i looked up the ifstream.open() and it takes a string and a mode as parameters. not really sure what to do with the modes, but i tried them but they gave the same error message DataReader.cpp: In function 'std::vector<Data*, std::allocator<Data*> > DataReader(std::string)': DataReader.cpp:11: error: no matching function for call to 'std::basic_ifstream<char, std::char_traits<char> >::open(std::string&)' /usr/local/lib/gcc/sparc-sun-solaris2.9/4.0.3/../../../../include/c++/4.0.3/fstream:495: note: candidates are: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>] thank you in advance for any input/suggestions. Dean
the standard streams doesn't accept a standard string, only c-string! So pass the string using c_str(): aStream.open(textFile.c_str());
1,662,737
1,662,808
initializing a const multidimensional array in c++
I'm currently working through some exercises in a c++ book, which uses text based games as its teaching tool. The exercise I am stuck on involves getting the pc to select a word from a const array of words (strings), mixing the letters up and asking the player to guess the word. This was easy, but as a follow on the book asks to add the option to provide a hint to the player to help them guess, firstly as a parallel array (again, no problem) and then as a 2 dimensional array. This is where I'm stuck. My (shortened) array of words is as follows: const string WORDS[NUM_WORDS] = {"wall", "glasses"}; I need to provide a hint for each of these words but not sure how to go about it. Posting this from phone so extensive googling is not an option! My parallel array was as follows: const string HINTS[NUM_WORDS] = "brick...", "worn on head"}; Just need to combine the two. Thanks in advance, Barry
you could make 2d array? string aArray[][2] = {{"wall", "brick..."}, {"glasses", "corrective eye tool thingymajig"}, {"calculator", "number cruncher"}}; not sure if the syntax is right but i hope you get the concept. it's an array inside another array. EDITED: i removed the NUM_WORDS from the first square bracket. you can't declare multi dimentional array from variables.. sorry i forgot about that. i just tested it and it works.
1,662,740
1,662,826
Why is this boost::variant example not working?
I am getting to know boost::variant. I think this example should work. #include <boost/fusion/sequence.hpp> #include <boost/fusion/include/sequence.hpp> #include <boost/variant/variant.hpp> #include <string> #include <vector> #include <iostream> #include <boost/variant/get.hpp> boost::variant< bool,long,double,std::string, std::vector<boost::variant<bool> > > v4; void main() { std::vector<boost::variant<bool> > av (1); v4= av; try { bool b= boost::get<bool> (v4[0]); // <--- this is line 20 std::cout << b; } catch (boost::bad_get v) { std::cout << "bad get" <<std::endl; } } I get a compilation error: d:\m\upp\boosttest\main.cpp(20) : error C2676: binary '[' : 'boost::variant' do es not define this operator or a conversion to a type acceptable to the predefined operator with [ T0_=bool, T1=long, T2=double, T3=std::string, T4=std::vector> ]
v4[0] is not valid since v4 is a variant, not a vector. You need to use boost::get to retrieve the vector stored in it first. So, line 20 should be boost::get<bool>(boost::get<std::vector<boost::variant<bool> > >(v4)[0]);
1,662,904
1,663,227
Qt in a professional setting
While I have played with parts of Qt in the past I am thinking of putting some real effort into learning it but also wondering what the potential monetary payback might be down the road. So I have some general questions about Qt's future. What is Qt's place in the job market? Are there many, or do you sense a growing number of installations using it? What are its main competitors? What kind of enterprise niches does Qt satisfy? Are more corporate applications trying to be cross-platform these days or do most of those efforts go the Java, etc., route? Since being bought by Nokia I assume Qt has a viable future on mobile devices. Has this in fact been working out? Is Qt pretty much limited to Nokia offerings or does it have a place on Android devices, etc.? Please feel free to comment on any aspect of Qt's future that I may have missed.
They have been around since 1995, and recently some feared that Nokia would buy them to stifle the competition in favour of Symbian. Now that seems definitely out of the way by the way Qt will soon support Symbian and Maemo 5. Seeing the effort they spend in R&D and what their framework already provides on so many platforms, I wouldn't worry about their future. As an open-source platform, I would venture Android devices are more of a competitor, rather than a possible platform, but it's just a wild guess ;-) There are some fierce debates out there on the subject. Another real competitor would be .NET, both offer more than just IDE building tools and deal with workstations and the embedded world. Clifford's advice about not sticking with only one framework is very wise IMHO. Another argument to start with Qt beside the advantage of covering more platforms is that it uses the C++ language, which is more demanding than C#. Starting with that will give you good programming habits, and it will be much easier to investigate something else later, be that a C# or a Java-based framework: you'll have a better idea of what lies behind the scenes of memory management (if that is not already the case, that is), and your code will be potentially more efficient.
1,662,905
1,663,245
Using valid STATIC member function of class that can't be installed
I have following piece of code: It compiles without problems under gcc-3.4, gcc-4.3, intel compiler, but fails under MSVC9. MSVC tells "use of undefined type c_traits<C>, while compiling class template member function void foo<C>::go(void) with C=short. The point it the compiler tries to install unused member function of unused class, because this class is just not used at all. I can work-around the issue by specializing entire class foo instead of specializing its member function. But the point it that specializing entire class is little bit problematic for me for different reasons. The big question: what is right? Is my code wrong and gcc and intel compiler just ignore the issue because they do not install foo fully, or The code is correct and this is bug of MSVC9 (VC 2008) that it tries to install unused member functions? The code: class base_foo { public: virtual void go() {}; virtual ~base_foo() {} }; template<typename C> struct c_traits; template<> struct c_traits<int> { typedef unsigned int_type; }; template<typename C> class foo : public base_foo { public: static base_foo *create() { return new foo<C>(); } virtual void go() { typedef typename c_traits<C>::int_type int_type; int_type i; i=1; } }; template<> base_foo *foo<short>::create() { return new base_foo(); } int main() { base_foo *a; a=foo<short>::create(); delete a; a=foo<int>::create(); delete a; }
Both compilers are right here; the behavior for your case is unspecified. ISO C++ 14.7.1[temp.inst]/9: An implementation shall not implicitly instantiate a function template, a member template, a non-virtual member function, a member class or a static data member of a class template that does not require instantiation. It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated. The reasoning for this is fairly simple: a virtual function requires a vtable entry, and with virtual dispatch, it may be tricky for the compiler to determine whether a given virtual function is actually called or not. Therefore, ISO C++ permits the compilers to do such advanced analysis for the sake of generating smaller code, but does not require it of them - so, as a C++ programmer, you should always assume that all virtual functions will always be instantiated.
1,663,094
1,663,520
What are the differences between using array offsets vs pointer incrementation?
Given 2 functions, which should be faster, if there is any difference at all? Assume that the input data is very large void iterate1(const char* pIn, int Size) { for ( int offset = 0; offset < Size; ++offset ) { doSomething( pIn[offset] ); } } vs void iterate2(const char* pIn, int Size) { const char* pEnd = pIn+Size; while(pIn != pEnd) { doSomething( *pIn++ ); } } Are there other issues to be considered with either approach?
Boojum is correct - IF your compiler has a good optimizer and you have it enabled. If that's not the case, or your use of arrays isn't sequential and liable to optimization, using array offsets can be far, far slower. Here's an example. Back about 1988, we were implementing a window with a simple teletype interface on a Mac II. This consisted of 24 lines of 80 characters. When you got a new line in from the ticker, you scrolled up the top 23 lines and displayed the new one on the bottom. When there was something on the teletype, which wasn't all the time, it came in at 300 baud, which with the serial protocol overhead was about 30 characters per second. So we're not talking something that should have taxed a 16 MHz 68020 at all! But the guy who wrote this did it like: char screen[24][80]; and used 2-D array offsets to scroll the characters like this: int i, j; for (i = 0; i < 23; i++) for (j = 0; j < 80; j++) screen[i][j] = screen[i+1][j]; Six windows like this brought the machine to its knees! Why? Because compilers were stupid in those days, so in machine language, every instance of the inner loop assignment, screen[i][j] = screen[i+1][j], looked kind of like this (Ax and Dx are CPU registers); Fetch the base address of screen from memory into the A1 register Fetch i from stack memory into the D1 register Multiply D1 by a constant 80 Fetch j from stack memory and add it to D1 Add D1 to A1 Fetch the base address of screen from memory into the A2 register Fetch i from stack memory into the D1 register Add 1 to D1 Multiply D1 by a constant 80 Fetch j from stack memory and add it to D1 Add D1 to A2 Fetch the value from the memory address pointed to by A2 into D1 Store the value in D1 into the memory address pointed to by A1 So we're talking 13 machine language instructions for each of the 23x80=1840 inner loop iterations, for a total of 23920 instructions, including 3680 CPU-intensive integer multiplies. We made a few changes to the C source code, so then it looked like this: int i, j; register char *a, *b; for (i = 0; i < 22; i++) { a = screen[i]; b = screen[i+1]; for (j = 0; j < 80; j++) *a++ = *b++; } There are still two machine-language multiplies, but they're in the outer loop, so there are only 46 integer multiplies instead of 3680. And the inner loop *a++ = *b++ statement only consisted of two machine-language operations. Fetch the value from the memory address pointed to by A2 into D1, and post-increment A2 Store the value in D1 into the memory address pointed to by A1, and post-increment A1. Given there are 1840 inner loop iterations, that's a total of 3680 CPU-cheap instructions - 6.5 times fewer - and NO integer multiplies. After this, instead of dying at six teletype windows, we never were able to pull up enough to bog the machine down - we ran out of teletype data sources first. And there are ways to optimize this much, much further, as well. Now, modern compilers will do that kind of optimization for you - IF you ask them to do it, and IF your code is structured in a way that permits it. But there are still circumstances where compilers can't do that for you - for instance, if you're doing non-sequential operations in the array. So I've found it's served me well to use pointers instead of array references whenever possible. The performance is certainly never worse, and frequently much, much better.
1,663,119
1,663,183
Why is my merge sort not working?
It compiles fine, but when it runs, it adds random high numbers to the list, as well as duplicates of existing numbers. I've had a couple of people look over this, and none of them can figure it out. void mergeSort(int list[], int length) { recMergeSort(list, 0, length - 1); } void recMergeSort(int list[], int first, int last) { if (first < last) { int mid = (first + last) / 2; recMergeSort(list, first, mid); recMergeSort(list, mid + 1, last); merge(list, first, last, mid); } } void merge(int list[], int first, int last, int mid) { int arraySize = last - first + 1; int* tempList = new int[arraySize]; int beginPart1 = first; int endPart1 = mid; int beginPart2 = mid + 1; int endPart2 = last; int index = beginPart1; while (beginPart1 <= endPart1 && beginPart2 <= endPart2) { if (list[beginPart1] < list[beginPart2]) { tempList[index] = list[beginPart1]; beginPart1++; } else { tempList[index] = list[beginPart2]; beginPart2++; } index++; } while (beginPart1 <= endPart1) { tempList[index] = list[beginPart1]; index++; beginPart1++; } while (beginPart2 <= endPart2) { tempList[index] = list[beginPart2]; index++; beginPart2++; } for (int i = first; i <= last; i++) { list[i] = tempList[i - first]; } delete[] tempList; }
In function merge(), you're incorrectly calculating the index variable: Assuming begin = 10, mid = 14, end = 19 (for a total array size of 0 .. 19, and you're recMergeSort()ing the higher half), your index = 10, but the tempList array is indexed 0..9 (because arraySize = last - first + 1 == 10). So you're overflowing your tempList array, and when you "merge", you get data corruption. Fix your index variable to be 0-based (rather than beginPart1 based).
1,663,128
1,663,173
Compiler warnings with MySQL++ with release configuration
For some reason I get some warnings about "non dll-interface class" when building with a release configuration, but not debug. I've compared the release and debug configurations, and my ones with the MySQL++ example ones, however I cant see which setting is causing these warnings. 1>c:\sql\mysql 5.0\mysql++-3.0.9\lib\qparms.h(49) : warning C4275: non dll-interface class 'std::_Container_base_aux' used as base for dll-interface class 'std::_Container_base_aux_alloc_real<_Alloc>' 1> with 1> [ 1> _Alloc=std::allocator<mysqlpp::SQLTypeAdapter> 1> ] 1> C:\apps\Microsoft Visual Studio 9.0\VC\include\xutility(377) : see declaration of 'std::_Container_base_aux' 1>c:\sql\mysql 5.0\mysql++-3.0.9\lib\result.h(212) : warning C4275... Code snippet from the warning: class MYSQLPP_EXPORT SQLQueryParms : public std::vector<SQLTypeAdapter> { ... The obvious thing to me seems to be that I'm not using a dll version of the CRT, however since I am ("Multi-threaded DLL (/MD)" for release) this cant be the problem, so must be somewhere else... MYSQLPP_EXPORT is defined as "__declspec(dllexport)" Compiler command line, I made some of the paths shorter for readability, however all the flags etc are the same. /O2 /Oi /GL /I "C:\SQL\MySQL 5.0\\include\\" /I "C:\SQL\MySQL 5.0\mysql++-3.0.9\\lib\\" /D "NDEBUG" /D "_WIN32" /D "_MBCS" /FD /EHsc /MD /Gy /Yu"precompiled.h" /Fp"C:\...\server.pch" /Fo"C:\..." /Fd"C:\...\vc90.pdb" /W3 /nologo /c /Zi /TP /errorReport:prompt And for a MySQL++ example. /Od /I "C:\SQL\MySQL 5.0\\include" /I "..\lib" /D "_CONSOLE" /D "UNICODE" /D "_UNICODE" /FD /EHsc /MD /Fo"C:\SQL\MySQL 5.0\mysql++-3.0.9\vc2008\Release\simple1\\" /Fd"C:\SQL\MySQL 5.0\mysql++-3.0.9\vc2008\Release\simple1.pdb" /W3 /nologo /c /TP /errorReport:prompt
The obvious thing to me seems to be that I'm not using a dll version of the CRT, however since I am ("Multi-threaded DLL (/MD)" for release) this cant be the problem, so must be somewhere else... 1>c:\sql\mysql 5.0\mysql++-3.0.9\lib\qparms.h(49) : warning C4275: non dll-interface class 'std::_Container_base_aux' used as base for dll-interface class 'std::_Container_base_aux_alloc_real<_Alloc>' This is a warning we ignore safely along with C4251 when dealing with code that sends STL across DLL boundaries. The warning is letting you know that if the other dll was built with some other STL version (which it can't figure out off hand) than the footprint of the class is going to differ between the imported/exported versions of the class. I know you are using VS 2008, but MSDN seems to hint that for 2005 your exact situation can be safely ignored: C4275 can be ignored in Microsoft Visual C++ 2005 if you are deriving from a type in the Standard C++ Library, compiling a debug release (/MTd) and where the compiler error message refers to _Container_base. Notice the reference to "debug release" and _Container_base
1,663,157
1,663,198
C++ referring to an object being constructed
In C++ I have a reference to an object that wants to point back to its owner, but I can't set the pointer during the containing class' construction because its not done constructing. So I'm trying to do something like this: class A { public: A() : b(this) {} private: B b; }; class B { public: B(A* _a) : a(_a) {} private: A* a; }; Is there a way to ensure B always gets initialized with an A* without A holding a pointer to B? Thanks
Try this: class A; class B { public: B(A *_a) : a(_a) {}; private: A* a; }; class A { public: A() : b(this) {}; private: B b; }; Since B is contained completely in A, it must be declared first. It needs a pointer to A, so you have to forward-declare A before you declare B. This code compiles under more-or-less current versions of g++.
1,663,284
1,663,389
Is boost::object_pool synchronized?
Is boost::object_pool synchronized?
C++ doesn't specify anything about thread-safety, so if it isn't mentioned it likely doesn't deal with threading. Sometimes, Boost provides things that can be thread-safe out of the box, this is not one of them. Wrap access to the pool in a mutex.
1,663,320
1,663,379
Turning text into executable statements
This is a question out of curiousity for java or c++, I wanted to ask if it is possible to turn any text input into some executable statements? For example say I have a text file with info like: "class: Abc, Param: 32" Now say in C++ or Java I want to read that file and do something like: new Abc(32); How would I do that? Its easy enough to read the value Abc but how do say create a class Abc? Is there a standard way to do that? in both C++ and Java? Main curiosity came from those persistance mechanisms in Java that store object properties in XML file and create an object by reading that XML file, how do they do that? Is that seperate from what I am asking for above? EDIT: This is different from the standard java serialization, i've seen this as solutions for long term persistence where object implementation can change and instead of serializing they store properties including execution statements in XML files which are used to create an object at runtime.
If your goal is to take any text input and run arbitrary commands, then the places to start looking on the JVM are the Java 6 compiler API (http://java.sun.com/javase/6/docs/api/javax/tools/package-summary.html) or JSR 223 (http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting). If your goal is storage and retrieval of information from text file, look at protocol buffers (http://code.google.com/p/protobuf/) or the Java serialization API (http://www.javaworld.com/javaworld/jw-07-2000/jw-0714-flatten.html).
1,663,444
1,663,526
Template specialization problem
I'm trying really hard to made this work, but I'm having no luck. I'm sure there is a work around, but I haven't run across it yet. Alright, let's see if I can describe the problem and the needs simply enough: I have a RGB template class that can take typenames as one of its template parameters. It takes the typename and sends it into another template that creates a classification of its basic type. For example: struct float_type {}; struct bit_type {}; struct fixed_pt_type {}; template <typename T> struct type_specification { typedef float_type type; }; template <> struct type_specification<char> { typedef bit_type type; }; template <> struct type_specification<short> { typedef bit_type type; }; template <> struct type_specification<int> { typedef bit_type type; }; template <> struct type_specification<long> { typedef bit_type type; }; template <> struct type_specification<long long> { typedef bit_type type; }; Then with this, I have a template that calculates Max Values for each of the RGB values based on its bit count: template <int Bits, typename T> struct Max_Values { enum { MaxValue = (1 << Bits) - 1; }; }; template <int Bits> struct MaxValues<float_type> { enum { MaxValue = 1.0; }; }; Then in the actual RGB template class, I have: enum { RMax = Max_Values<RBits, type_specification<T>::type>::MaxValue; GMax = Max_Values<GBits, type_specification<T>::type>::MaxValue; BMax = Max_Values<BBits, type_specification<T>::type>::MaxValue; }; This works really well for me, until I got into the fixed-pt needs. The max value is a bit different and I don't know how to create a type-specification specialization to isolate it out. The only work around I have is the process of elimination and creating specializations for float and double and assuming the general case will be fixed-pt. But there has to be a better way to do this. Here is what I want to do with incorrect code: template <> struct type_specification<fixed_pt_t> { typedef fixed_pt_type type; }; However, fixed-pt-t is a template class that looks like: template <int N, typename T, template <class> class Policy> struct fixed_pt_t So the compiler does not like the specialization without template parameters. Is there a way to specialize my type-specification class to work with fixed-pt-t? It works fine for the general case, just can't isolate it.
Perhaps I'm missing some bigger complication, but is there any reason why you can't just partially specialize the type_specification template? Something like this: template <int N, typename T, template <class> class Policy> struct type_specification< fixed_pt_t<N, T, Policy> > { typedef fixed_pt_type type; };
1,663,562
1,663,576
Multi Including a .h File
In an .h file, I am declaring a global variable as: #pragma data_seg(".shared") #ifndef DEF_VARX #define DEF_VARX int VARX=0; #endif /*DEF_VARX*/ #pragma data_seg() #pragma comment(linker, "/SECTION:.shared,RWS") However if I include this file in multiple cpp files, when I try to compile, I get " error LNK2005: "int VARX" (?VARX@@3HA) already defined in Dll.obj" error. If I include in only one cpp file, no problem is encountered. Isn't #IFNDEF.... check enough for preventing this? Am I missin something?
I think you're supposed to forward declare the variable in the .h and later define it in its shared section in a .cpp, something like: // in a header file #pragma once extern int VARX; // in a .cpp #pragma data_seg(".shared") int VARX=0; #pragma data_seg() #pragma comment(linker, "/SECTION:.shared,RWS")
1,663,655
1,665,821
C++/Qt download file in sync
I want to achieve to download a file in a separate thread and store that file, but I was not able to find an appropriate way to achieve this without evil delay (quite frequent download of small files, so signal+slots are too slow). What I want to achieve: (Pseudo Code) request file; wait for download finishing, timeout or error; save downloaded file; I'd prefer an example with QNetworkAccessManager if possible. Thanks for any tipp. Edit: Just to be clear, I want signal and slots not because of design aswell as the lack of speed. Edit2: This download is only about the download file in sync part, threading is no problem. The problem is that QT does not provide an api for doing that and I am not keen on hotspinning wait. Edit3: Example code like it should work, but does not: QNetworkAccessManager net; QNetworkReply *re (net.get( QNetworkRequest( QUrl( Qstring("www.blah.org/key") ) ) )); if (re->waitForReadyRead(-1)) //! @bug this does not work as supposed, waitForRead returns false and returns INSTANTLY!! qDebug() << "ReadyRead yeha!!!"; if (re->error()) { qDebug() << "Can't download" << re->url().toString() << ":" << re->errorString(); } else { img->load(re->readAll()); qDebug() << "Savin IMG"; } delete re;
I needed something similar but for different reasons. Since QHttp and QNetworkAccessManager are both async what you could do is use a separate event loop, a full example based on QHttp can be found here. It shouldn't be too difficult to modify it for QNetworkAccessManager. It's worth mentioning that your impression that signals/slots are "slow" is probably wrong. Have you actually profiled your code to determine this? Whatever penalty you might be paying for signals/slots it's probably negligible when looking at the amount of time a single file download takes. More so, it's very "non Qt" to do things this way. These classes were designed like this for a reason. At the end of the day if you are indeed suffering from signals/slots (which is again, doubtful), I would recommend not to use Qt for this particular task, maybe plain old C sockets are a better idea (or a thin wrapper around them to save the error handling which might require some extra work).
1,663,864
1,663,981
DLL Shared Data Section Does Not Exist Error
I try to declare a shared data segment in a DLL. I declare the area with: #pragma data_seg(".shared") int varx=0; #pragma data_seg() __declspec(allocate(".shared")) // I found this declspec suggestion in another forum #pragma comment (linker,"/section:.shared,RWS") Also I add SECTIONS .shared READ WRITE SHARED into the def file. However I always get: LINK : warning LNK4039: section '.shared' specified with /SECTION option does not exist error. If I do only one (.def or pragma comment) get only one, if do both get two errors. Anything I miss?
Ive only seen that declspec used in this way: __declspec(allocate(".shared")) int varx=0; I would try writting only this: #pragma comment (linker,"/section:.shared,RWS") __declspec(allocate(".shared")) int varx=0; avoiding declaring an empty section or a multiply defined one
1,663,949
1,664,052
How do I get all permutations of xPy?
I'd like to calculate all the permutations of size Y of a set of size X. That is if I had (1,2,3) and want all permutations of size 2, 3P2, it would be (1,2) (1,3) (2,1) (2,3) (3,1) (3,2). Both the GSL and C++ STL only provide xPx that I can see. Could someone point me at a C/C++ library which can do this or spell out a fast and memory efficient algorithm? I'm trying to solve a very short cryptogram. I've figured out two letters and have decided to do an brute force attack. I have "ouglg ouyakl" and am checking every permutation against a very good dictionary. I've eliminated 2 letters so its 24P7 or 1,744,364,160 possibilities which isn't so bad. I have a Perl program running now, so this will be an interesting test of the total efficiency of programming time + run time. :) (No, I do not just want the answer to the cryptogram.)
I've used this library before (note it is C++) in code that needed to do something similar. It has permutations and combinations, with and without repetition. For your problem, this should suffice (untested...): std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); std::vector<int>::iterator first = v.begin(), middle = v.begin() + 2, last = v.end(); do { // do stuff with elements in range first...middle (but dont change them) } while(next_partial_permutation(first, middle, last));
1,664,028
1,664,225
Why should I use typedefs in C++?
Lets say I have: set<int, less<int> > m_intset; That works, but now I change it to typedef, and I do end up with two lines of code: typedef set<int, less<int> > SetInt; SetInt m_intset; What's the advantage of such a typedef? Am I using it correctly?
Some advantages to using typedef: Simplification: Now, every time you would normally have needed set<int, less<int> >, you only have to type SetInt. Not a big deal if you're only using the set once, but if you've got multiple instances of the same set, or need to access iterators thereof, the shorter form is much easier to read and type. Clarification: set<int, less<int> > doesn't tell me anything about what the variable is used for, just that it's a set of ints. With typedef, you can choose an identifier that explains the purpose of the type, such as Inventory or Coordinates, for example. Abstraction: Programs change. Although you may think you need a set<int, less<int> > now, there's always the possibility that your requirements may change in the future, necessitating a set<unsigned long, less<unsigned long> > or vector<int> or some other change. By using a typedef, you would only have to fix this in one place, and it will affect every instance of SetInt in the program. This is far simpler and less prone to error than manually changing a dozen or more entries in the source files. Due to points 2 and 3 above, typedef can be very powerful when used inside a class or a library, since it can strengthen the separation between interface and implementation which is generally considered good C++ form. Of course, most of these advantages only really show themselves if you're using the same type multiple times in the same program. If you only expect to use the set<int, less<int> > once, typedef is probably overkill.
1,664,054
1,664,120
C++ - syntax for defining/instantiating strings
I am very new to C++ and still trying to learn syntax and best practices. I've defined a method with a single parameter: void foo(const std::string& name) 1) Is this a proper parameter declaration for a function that will be taking in a string defined by the user in, for example, a main method? 2) If this is proper/recommended syntax, what would an instantiation of a sample parameter look like?
I'm not sure if I fully understand your question, but I'll try to clarify it. You use the terminology 'method'. I'm assuming that your method is encapsulated in a class? If so, then :- In your header file (eg. source.h), class dog { ... public: void foo(const std::string &name); ... }; In your source file (eg. source.cpp) void dog::foo(const std::string &name) { // Do something with 'name' in here std::string temp = name + " is OK!"; } In your 'main' function, you can instantiate your 'dog' class, and call the 'foo' function like :- void blah() { dog my_class; my_class.foo("Testing my class"); } If you want a function (ie. a 'method' that is not encapsulated within a class), then what you have is correct. In your source file (eg. source.cpp) void foo(const std::string &name) { // Do something with 'name' in here std::string temp = name + " is OK!"; } If you want to be able to call your function from outside that particular source file, you'll also need to forward declare your function in a header file. In your header file (eg. source.h) void foo(const std::string &name); To call your function, void blah() { foo("Testing my class"); } Hope this helps!
1,664,197
1,665,036
Financial library for C/C++
Do you know of a good open source financial library written in C (preferably) or C++? I already looked at Quantlib, which seems too complicated for me, since I just want some basic computations (total cost of credit, all in-cost credit rate...) Thank you very much!
When programming for financial derivatives, I absolutely loved Bernt Arne Ødegaard's resource here: http://finance.bi.no/~bernt/gcc_prog/recipes/recipes/node1.html It probably has what you want, and then some. If it doesn't, I have to agree with James Black.
1,664,342
1,664,369
Is it possible to use COM smart pointers with the CList collection
I'm attempting to create a CList with a COM smart pointer (one of the wrapper classes generated for _com_ptr_t) as the template parameter: CList<IDispatchPtr, IDispatchPtr> list; However I get several compilation errors similar to: error C2664: 'void __stdcall SerializeElements(class CArchive &,class _com_ptr_t<class _com_IIID<struct IDispatch,&struct __s_GUID _GUID_00020400_0000_0000_c000_00000000004 6> > *,int)' : cannot convert parameter 2 from 'struct IDispatch ** ' to 'class _com_ptr_t<class _com_IIID<struct IDispatch,&struct __s_GUID _GUID_00020400_0000_0000_c000_000000000046> > *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast It compiles when using regular pointers: CList<IDispatch*, IDispatch*> list; Looking at the MFC code that calls SerializeElements it looks like the problem is that it takes a TYPE* and there's no conversion between IDispatch** and IDispatchPtr*. Is there any way around this?
Because of the way operator& is overloaded, you need to wrap the smart pointers in CAdapt<>: CList<CAdapt<IDispatchPtr>, CAdapt<IDispatchPtr> > list;
1,664,372
1,664,469
Best way to store and hash <int, int> key (C++)
My goal is to create an efficient structure to store the most relevant entries of a matrix that would (in a world without memory limitations) be approximately 10^5 x 10^5 and filled with doubles. The matrix is symmetric, so it actually would contain only (10^10)/2 values. I need to access entries many, many times in my simulation, so fast retrieval is critical. To keep the structure manageable, I will delete members that are unlikely to be used. If the index is (int_x1, int_x2), I will often want to delete all pairs containing, e.g., x1. What is the best structure or set of structures for this task? What is a good hash for two ints? For portability, I would like to avoid Boost. I am currently using TR1's unordered_map elsewhere in the program. I was thinking of using unordered_map again with the key pair, but I'm not sure how I would be able to delete entries efficiently this way, and I don't know what a good hash function would look like. I'm a beginning programmer, so please state the obvious.
If the data is going to be pretty sparse, you could use an array of hash tables. hash_map<int,double> matrix[] = new hash_map<int,double>[10000]; for (int i = 0; i < 10000; i++) matrix[i] = new hash_map<int,double>(); Then to look up a value (x,y), you index the array with x and look up y in the hash table. A few things to watch out for: Deleting can get pretty expensive, as you have to iterate through a lot of the hash tables. Total storage can grow as you delete/insert, you should trim() your hash_maps occasionally. it should be easy to take advantage of symmetry.
1,664,502
1,664,559
boost asio: maintaining a list of connected clients
I'm looking for the best way to modify the Boost Asio HTTP Server 3 example to maintain a list of the currently connected clients. If I modify server.hpp from the example as: class server : private boost::noncopyable { public: typedef std::vector< connection_ptr > ConnectionList; // ... ConnectionList::const_iterator GetClientList() const { return connection_list_.begin(); }; void handle_accept(const boost::system::error_code& e) { if (!e) { connection_list_.push_back( new_connection_ ); new_connection_->start(); // ... } } private: ConnectionList connection_list_; }; Then I mess up the lifetime of the connection object such that it doesn't go out of scope and disconnect from the client because it still has a reference maintained in the ConnectionList. If instead my ConnectionList is defined as typedef std::vector< boost::weak_ptr< connection > > ConnectionList; then I run the risk of the client disconnecting and nullifying its pointer while somebody is using it from GetClientList(). Anybody have a suggestion on a good & safe way to do this? Thanks, PaulH
HTTP is stateless. That means it's difficult to even define what "currently connected client" means, not to mention keeping track of which clients are at any given time. The only time there's really a "current client" is from the time a request is received to the time that request is serviced (often only a few milliseconds). A connection is not maintained even for the duration of downloading one page -- rather, each item on the page is requested and sent separately. The typical method for handling this is to use a fairly simple timeout -- a client is considered "connected" for some arbitrary length of time (a few minutes) after they send in a request. A cookie of some sort is used to identify the client sending in a particular request. The rest of what you're talking about is just a matter of making sure the collection you use to hold connection information is thread safe. You have one thread that adds connections, one thread that deletes them, and N threads that use the data currently in the list. The standard collections don't guarantee any thread safety, but there are others around that do.
1,664,751
1,664,768
why C, C++, Java does not use one complement?
I heard C, C++, Java uses two complements for binary representation. Why not use 1 complement? Is there any advantage to use 2 complement over 1 complement?
Working with two's complement signed integers is a lot cleaner. You can basically add signed values as if they were unsigned and have things work as you might expect, rather than having to explicitly deal with an additional carry addition. It is also easier to check if a value is 0, because two's complement only contains one 0 value, whereas one's complement allows one to define both a positive and a negative zero. As for the additional carry addition, think about adding a positive number to a smallish negative number. Because of the one's complement representation, the smallish negative number will actually be fairly large when viewed as an unsigned quantity. Adding the two together might lead to an overflow with a carry bit. Unlike unsigned addition, this doesn't necessarily mean that the value is too large to represent in the one's complement number, just that the representation temporarily exceeded the number of bits available. To compensate for this, you add the carry bit back in after adding the two one's complement numbers together.
1,664,845
1,665,070
Reading a file into an array
I would like to read a text file and input its contents into an array. Then I would like to show the contents of the array in the command line. My idea is to open the file using: inFile.open("pigData.txt") And then to get the contents of the file using: inFile >> myarray [size] And then show the contents using a for loop. My problem is that the file I am trying to read contain words and I don't know how to get a whole word as an element in the array. Also, let's say that the words are divided by spaces, thus: hello goodbye Could be found on the file. I would like to read the whole line "hello goodbye" into an element of a parallel array. How can I do that?
For context, you could have provided a link to your previous question, about storing two lists of words in different languages. There I provided an example of reading the contents of a text file into an array: const int MaxWords = 100; std::string piglatin[MaxWords]; int numWords = 0; std::ifstream input("piglatin.txt"); std::string line; while (std::getline(input, line) && numWords < MaxWords) { piglatin[numWords] = line; ++numWords; } if (numWords == MaxWords) { std::cerr << "Too many words" << std::endl; } You can't have one parallel array. For something to be parallel, there must be at least two. For parallel arrays of words, you could use a declarations like this: std::string piglatin[MaxWords]; std::string english[MaxWords]; Then you have two options for filling the arrays from the file: Read an entire line, and the split the line into two words based on where the first space is: while (std::getline(input, line) && numWords < MaxWords) { std::string::size_type space = line.find(' '); if (space == std::string::npos) std::cerr << "Only one word" << std::endl; piglatin[numWords] = line.substr(0, space); english[numWords] = line.substr(space + 1); ++numWords; } Read one word at a time, and assume that each line has exactly two words on it. The >> operator will read a word at a time automatically. (If each line doesn't have exactly two words, then you'll have problems. Try it out to see how things go wrong. Really. Getting experience with a bug when you know what the cause is will help you in the future when you don't know what the cause is.) while (input && numWords < MaxWords) { input >> piglatin[numWords]; input >> english[numWords]; ++numWords; } Now, if you really one one array with two elements, then you need to define another data structure because an array can only have one "thing" in each element. Define something that can hold two strings at once: struct word_pair { std::string piglatin; std::string english; }; Then you'll have just one array: word_pair words[MaxWords]; You can fill it like this: while (std::getline(input, line) && numWords < MaxWords) { std::string::size_type space = line.find(' '); if (space == std::string::npos) std::cerr << "Only one word" << std::endl; words[numWords].piglatin = line.substr(0, space); words[numWords].english = line.substr(space + 1); ++numWords; } Notice how the code indexes into the words array to find the next word_pair object, and then it uses the . operator to get to the piglatin or english field as necessary.
1,665,018
1,665,034
Memset on vector C++
Is there any equivalent function of memset for vectors in C++ ? (Not clear() or erase() method, I want to retain the size of vector, I just want to initialize all the values.)
Use std::fill(): std::fill(myVector.begin(), myVector.end(), 0);
1,665,269
1,665,297
C++ Newbie in Linker Hell
Using g++ and having linker errors. I have a simple program in split into two modules: main.cpp and Dice.h Dice.cpp. main.cpp: #include <iostream> #include "Dice.h" int main(int argc, char **argv) { int dieRoll = Dice::roll(6); std::cout<<dieRoll<<std::endl; std::cin.get(); return 0; } Dice.h: #ifndef DieH #define DieH namespace Dice { int roll(unsigned int dieSize); } #endif Dice.cpp: #include <ctime> #include <cstdlib> #include "Dice.h" namespace Dice { int roll(unsigned int dieSize) { if (dieSize == 0) { return 0; } srand((unsigned)time(0)); int random_int = 0; random_int = rand()%dieSize+1; return random_int; } } I compile and link these files using g++ as follows: g++ -o program main.cpp Dice.cpp And I get the following linker error: Undefined symbols: "Dice::roll(int)", referenced from: _main in ccYArhzP.o ld: symbol(s) not found collect2: ld returned 1 exit status I'm completely flummoxed. Any help would be greatly appreciated.
Your code is well-formed. Ensure that your don't have conflicting file names, the files exist and contain what you think they do. For example, perhaps you have a Dice.cpp that's empty, and you're editing a newly created one somewhere else. Minimize possible discrepancy by removing unnecessary files; only have main.cpp, dice.h, and dice.cpp. Your errors do not match your code: "Dice::roll(int)". Observe that this is looking for an int, but your functions take an unsigned int. Make sure your header matches. Try the following: g++ main.cpp -c This will generate main.o, the compiled but not-linked code for main. Do the same with dice.cpp: g++ dice.cpp -c You now have two object files that need to be linked together. Do so with: g++ main.o dice.o And see if that works. If not, do the following: nm main.o dice.o This will list all the available symbols in an object, and should give you something like this: main.o: 00000000 b .bss 00000000 d .ctors 00000000 d .data 00000000 r .eh_frame 00000000 t .text 00000098 t __GLOBAL__I_main 00000069 t __Z41__static_initialization_and_destruction_0ii U __ZN4Dice4rollEj U __ZNSi3getEv U __ZNSolsEPFRSoS_E U __ZNSolsEi U __ZNSt8ios_base4InitC1Ev U __ZNSt8ios_base4InitD1Ev U __ZSt3cin U __ZSt4cout U __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ 00000000 b __ZStL8__ioinit U ___gxx_personality_v0 U ___main 00000055 t ___tcf_0 U _atexit 00000000 T _main dice.o: 00000000 b .bss 00000000 d .data 00000000 t .text 00000000 T __ZN4Dice4rollEj U _rand U _srand U _time C++ mangles function names, which is why everything looks so weird. (Note, there is no standard way of mangling names, this is how GCC 4.4 does it). Observe that dice.o and main.o refer to the same symbol: __ZN4Dice4rollEj. If these do not match, that's your problem. For example, if I change part of dice.cpp to be this: // Note, it is an int, not unsigned int int roll(int dieSize) Then nm main.o dice.o produces the following: main.o: 00000000 b .bss 00000000 d .ctors 00000000 d .data 00000000 r .eh_frame 00000000 t .text 00000098 t __GLOBAL__I_main 00000069 t __Z41__static_initialization_and_destruction_0ii U __ZN4Dice4rollEj U __ZNSi3getEv U __ZNSolsEPFRSoS_E U __ZNSolsEi U __ZNSt8ios_base4InitC1Ev U __ZNSt8ios_base4InitD1Ev U __ZSt3cin U __ZSt4cout U __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_ 00000000 b __ZStL8__ioinit U ___gxx_personality_v0 U ___main 00000055 t ___tcf_0 U _atexit 00000000 T _main dice.o: 00000000 b .bss 00000000 d .data 00000000 t .text 00000000 T __ZN4Dice4rollEi U _rand U _srand U _time Note, this gives two different symbols. main.o looking for this: __ZN4Dice4rollEj and dice.o containing this __ZN4Dice4rollEi. (The last letter differs). When trying to compile these mismatched symbols (with g++ main.o dice.o), I get: undefined reference to `Dice::roll(unsigned int)'
1,665,427
2,130,653
Generate C++ code for BNF grammar
I have looked at the following software tools: Ragel ANTLR BNF Converter Boost::Spirit Coco/R YACC ANTLR seems the most straight-forward, however its documentation is lacking. Ragel looks possible, too, but I do not see an easy way to convert BNF into its syntax. What other tools are available that can take BNF input and generate a corresponding, Unicode-friendly, cross-platform, standalone, C++ parser? Many thanks for all suggestions. Edit: Changed Objective-C requirement to C++.
Try boost.spirit 2. The boost spirit user list is very active and answers are quick from the authors.
1,665,459
1,665,507
PushFront method for an array C++
I thought i'd post a little of my homework assignment. Im so lost in it. I just have to be really efficient. Without using any stls, boosts and the like. By this post, I was hoping that someone could help me figure it out. bool stack::pushFront(const int nPushFront) { if ( count == maxSize ) // indicates a full array { return false; } else if ( count <= 0 ) { count++; items[top+1].n = nPushFront; return true; } ++count; for ( int i = 0; i < count - 1; i++ ) { intBackPtr = intFrontPtr; intBackPtr++; *intBackPtr = *intFrontPtr; } items[top+1].n = nPushFront; return true; } I just cannot figure out for the life of me to do this correctly! I hope im doing this right, what with the pointers and all int *intFrontPtr = &items[0].n; int *intBackPtr = &items[capacity-1].n; Im trying to think of this pushFront method like shifting an array to the right by 'n' units...I can only seem to do that in an array that is full. Can someone out their please help me?
You don't need any pointers to shift an array. Just use simple for statement: int *a; // Your array int count; // Elements count in array int length; // Length of array (maxSize) bool pushFront(const int nPushFront) { if (count == length) return false; for (int i = count - 1; i >= 0; --i) Swap(a[i], a[i + 1]); a[0] = nPushFront; ++count; return true; }
1,665,588
1,665,611
Access is Denied for registry
I am playing with the registry programmatically for the first time, and it's not working that well (but at least I haven't destroyed my computer). Specifically, I keep getting back Error 5 (Access is Denied) from RegCreateKeyEx and RegSetValueEx. The thing that is strangest to me is that when HKEY_CURRENT_USER\Software\dir1\Sub Directory already exists, RegCreateKeyEx fails with Error 5, but when it doesn't already exist, it creates it successfully; and then fails on the RegSetValueEx. Am I doing anything wrong in this code? BOOL MyDialog::SaveLocationsToRegistry() { HKEY hkey; DWORD dwDisposition; DWORD dwType, dwSize; LONG result = RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\dir1\\Sub Directory"), 0, NULL, 0, 0, NULL, &hkey, &dwDisposition); if(result == ERROR_SUCCESS) { LPCTSTR szLastFolder = "C:\\Documents and Settings\\user\\My Documents\\Copy of item\0"; dwType = REG_SZ; dwSize = strlen(szLastFolder)+1; LONG setResult = RegSetValueEx(hkey, TEXT("LastFolder"), 0, dwType, (PBYTE)&szLastFolder, dwSize); RegCloseKey(hkey); return setResult == ERROR_SUCCESS; } else { return false; } } Note: The absolute path is only there temporarily. Baby steps ;-)
You're not asking for any access rights. You probably want to specify KEY_WRITE (or something) for the 6th parameter (samDesired). LONG result = RegCreateKeyEx(HKEY_CURRENT_USER, TEXT("Software\\dir1\\Sub Directory"), 0, NULL, 0, KEY_WRITE, NULL, &hkey, &dwDisposition);
1,665,600
1,665,620
How to link against libxerces-c.so.28?
Whenever we specify -lxerces-c, this looks for libxerces-c.so library in the LIBPATH. Q1. Why are lib files then generated as libxerces-c.so.28? Q2. How should we link against such libraries? The only way I can think of is create a soft link libxerces-c.so which links to the file libxerces-c.so.28. I feel this as an overhead to do. Is there any other way around which is better?
The file name has a version number so that you can have one program that uses version 2.8 and a different program that uses version 2.9. This way, adding a new version of the library will not change the behavior of existing programs that use an old library. Normally, there should also be a file libxerces-c.so which is a sym link to the version of the library you want your newly built programs to use. Many Unix package managers will have a separate development package that installs the symlink. It sounds like you don't have the devel package installed.
1,665,905
1,728,038
SetLineSpacing() does not work in DirectWrite - why?
I'm rendering text in Direct2D/DirectWrite, but calling SetLineSpacing() on either TextFormat or TextLayout seems to have no effect. Does anyone know why?
I'm 99% sure that this is a bug. I have done a little playing around with Direct2D lately and also had a problem with SetLineSpacing() on TextLayout, think it is the same as what you are describing, in that case I can confirm that it's not just you. Reopen your bug report on MS Connect, it has been closed.
1,665,989
1,667,095
Making a 2D engine: compiling necessary libraries with the engine instead of the game
I'm making a 2D engine in C++, and I want to be able to supply a .dll and a .lib so that games can just include those and everything is fine and dandy. I've looked at how Ogre does it, and it results in ugliness like this: #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) #else int main(int argc, char *argv[]) #endif { // Create application object ShadowsApplication app; try { app.go(); } catch( Ogre::Exception& e ) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl; #endif } return 0; } #ifdef __cplusplus } #endif While my engine currently does this: MAIN { Game* game = Game::Create(); Engine::Init(); game->Init(); while (Engine::running) { if (Engine::PreRender()) { game->Update(); Engine::Render(); } Engine::ShutDown(); return 0; } } Which means a clean game looks like this: class BouncingBalls : public Game { public: BouncingBalls() { } void Init(); void Update(); }; Game* Game::Create() { return (new BouncingBalls()); } Now, one major drawback: because I'm defining main in the engine instead of the game, I can't put all the necessary libraries in the engine. Every game has to load in a specific set of libraries, which is going to be hell when that list changes. Is there a way to keep the syntax like this while also loading in the .lib's in the engine instead of the game? Thanks in advance. EDIT: It seems things were not clear. My eventual goal is to have a single Visual Studio project that contains all of the engine functions, which compiles to a .lib or a .dll (not a .exe). If someone wants to make a game, he can simply include Engine.lib in his project and Engine.dll in his project folder and get going. It should be as easy as possible to start up a new project, without having to worry about low-level C++.
Why not just rename your MAIN to something like Engine::MainLoop and have the client app call that from their main.
1,666,073
1,666,204
How port WaitForMultipleObjects to Java?
I have some code in C++ for Windows and I intend to port it to Java. But unfortunately it is not so easy as I thought. Could someone help me, please? Please, take a look at algorithm: HANDLE hExitEvent; HANDLE hDataAvailabeEvent; while(true) { WaitForMultipleObjects(); if (hExitEvent is set) break; if (hDataAvailabeEvent) { process chunk of data; if (all data processed) ResetEvent(hDataAvailabeEvent); } } hDataAvailabeEvent can be set from different threads. If all data is processed, then event resets and at calling WaitForMultipleObjects thread will suspend until new data arrives or time for thread exit comes. I've already seen question Waitformultipleobjects in Java but it's not suitable for my situation because I can't process all new data in 1 cycle iteration and processing spreads over some iterations. Thanks in advance!
A simple solution which would seem to fulfill your need is something like: class DataProcessor implements Runnable { private final ExecutorService executor = Executors.newSingleThreadedExecutor(); public void stop { executor.shutdown(); } public void process(final Data data){ executor.execute(new Runnable(){ public void run(){ // process data } }); } } You don't really have any events, but it works more or less the same way. Want to add data to the processing queue? Call process and the executor will process your Data when it is finished with any previous tasks on the queue. Shutting down? Call stop and the executor will finish process everything on the queue, but will not accept any more work. (If you need a more abrupt end, use ExecutorService.shutdownNow).
1,666,093
4,823,889
CPUID implementations in C++
I would like to know if somebody around here has some good examples of a C++ CPUID implementation that can be referenced from any of the managed .net languages. Also, should this not be the case, should I be aware of certain implementation differences between X86 and X64? I would like to use CPUID to get info on the machine my software is running on (crashreporting etc...) and I want to keep everything as widely compatible as possible. Primary reason I ask is because I am a total noob when it comes to writing what will probably be all machine instructions though I have basic knowledge about CPU registers and so on... Before people start telling me to Google: I found some examples online, but usually they were not meant to allow interaction from managed code and none of the examples were aimed at both X86 and X64. Most examples appeared to be X86 specific.
Accessing raw CPUID information is actually very easy, here is a C++ class for that which works in Windows, Linux and OSX: #ifndef CPUID_H #define CPUID_H #ifdef _WIN32 #include <limits.h> #include <intrin.h> typedef unsigned __int32 uint32_t; #else #include <stdint.h> #endif class CPUID { uint32_t regs[4]; public: explicit CPUID(unsigned i) { #ifdef _WIN32 __cpuid((int *)regs, (int)i); #else asm volatile ("cpuid" : "=a" (regs[0]), "=b" (regs[1]), "=c" (regs[2]), "=d" (regs[3]) : "a" (i), "c" (0)); // ECX is set to zero for CPUID function 4 #endif } const uint32_t &EAX() const {return regs[0];} const uint32_t &EBX() const {return regs[1];} const uint32_t &ECX() const {return regs[2];} const uint32_t &EDX() const {return regs[3];} }; #endif // CPUID_H To use it just instantiate an instance of the class, load the CPUID instruction you are interested in and examine the registers. For example: #include "CPUID.h" #include <iostream> #include <string> using namespace std; int main(int argc, char *argv[]) { CPUID cpuID(0); // Get CPU vendor string vendor; vendor += string((const char *)&cpuID.EBX(), 4); vendor += string((const char *)&cpuID.EDX(), 4); vendor += string((const char *)&cpuID.ECX(), 4); cout << "CPU vendor = " << vendor << endl; return 0; } This Wikipedia page tells you how to use CPUID: http://en.wikipedia.org/wiki/CPUID EDIT: Added #include <intrin.h> for Windows, per comments.
1,666,176
1,672,584
Intermediate results using expression templates
in C++ Template Metaprogramming : Concepts, Tools, and Techniques from Boost and Beyond ... One drawback of expression templates is that they tend to encourage writing large, complicated expressions, because evaluation is only delayed until the assignment operator is invoked. If a programmer wants to reuse some intermediate result without evaluating it early, she may be forced to declare a complicated type like: Expression< Expression<Array,plus,Array>, plus, Expression<Array,minus,Array> > intermediate = a + b + (c - d); (or worse). Notice how this type not only exactly and redundantly reflects the structure of the computationand so would need to be maintained as the formula changes but also overwhelms it? This is a long-standing problem for C++ DSELs. The usual workaround is to capture the expression using type erasure, but in that case one pays for dynamic dispatching. There has been much discussion recently, spearheaded by Bjarne Stroustrup himself, about reusing the vestigial auto keyword to get type deduction in variable declarations, so that the above could be rewritten as: auto intermediate = a + b + (c - d); This feature would be a huge advantage to C++ DSEL authors and users alike... Is it possible to solve this problem with the current c++ std. (non C++0X) For Example i want to write a Expression like: Expr X,Y Matrix A,B,C,D X=A+B+C Y=X+C D:=X+Y Where operator := evaluate the expression at the latest Time.
For now, you can always use BOOST_AUTO() in the place of C++0x's auto keyword to get intermediate results more easily. Matrix x, y; BOOST_AUTO(result, (x + y) * (x + y)); // or whatever.