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
6,230,048
6,230,136
C++ Linking with Methods Defined in the Class Definition
For curiosity's sake, if you put the method definition inside the class definition in the header, and the compiler doesn't inline it, then what object file or files is that method put into for accessing during the linker phase? Is it put in every .obj file that includes the header, and then extra copies are thrown away...
If the compiler rejects inlining some member function that is defined in-line in the body of the class or is defined as an inline function outside the body of the class, the compiler will insert a compiled version of the function in every .obj file that uses that function. Note that this is different from inserting a c...
6,230,135
6,230,157
How to create Character based arrays in Turbo C++?
I was trying some C++, but I'm too new to this and you can say that this is my first day at C++. So I was trying to create a function but I was stuck with arrays! When I create a Character based array like this : char x[7][7] = {"sec","min","hr","day","week","month","year"}; And when I try to fetch the data from it l...
Since you have 7 values, and the array is indexed from 0, you only need to count up to 6, not 7. Modify your for loop as for (i=0;i < 7;i++). (< instead of <=.) You're going over the end of the array, which may give you garbage data or may just crash your program.
6,230,180
6,230,257
Can sort() in C++ have a n^2 performance?
When trying to estimated the performance of a program, I always treated sort() function as a worst-performance-n^2 function. However, I came across a Wikipedia page: sort(C++) Which states that the GNU C Library sort() uses some hybrid sorting algorithm called Introsort first, then do insertion sort. The corresponding ...
The use of quicksort and introsort (which is a variant of the former, with guaranteed O(n log n) performance achieved by switching to heapsort on worst case inputs) in place of other theoretically better algorithms like mergesort is due to the fact that the average case is the same, and the constants much lower (in the...
6,230,269
6,230,297
3-promise rule for functions
I need help remembering what book I read this from, It might have been Effective C++ or something, but I don't remember. I was reading something that basically stated that functions have 3 promises: Validate input parameters to make sure they meet the expected input requirements Guaranteed to respect & maintain invari...
The name of the concept is Design by Contract: Expect a certain condition to be guaranteed on entry by any client module that calls it: the routine's precondition—an obligation for the client, and a benefit for the supplier (the routine itself), as it frees it from having to handle cases outside of the precondition. ...
6,230,274
6,230,289
lvalue required as increment operand error
#include <stdio.h> int main() { int i = 10; printf("%d\n", ++(-i)); // <-- Error Here } What is wrong with ++(-i)? Please clarify.
-i generates a temporary and you can't apply ++ on a temporary(generated as a result of an rvalue expression). Pre increment ++ requires its operand to be an lvalue, -i isn't an lvalue so you get the error.
6,230,288
6,230,534
Am I converting local space to world space coordinates properly?
I'm trying to create a bone and IK system. Below is the method that is recursive and that calculates the absolute positions and absolute angles of each bone. I call it with the root bone and zero'd parameters. It works fine, but when I try to use CCD IK I get discrepancies between the resulting end point and the calcul...
This looks wrong. float vecX = sin(realStartAngle); float vecY = cos(realStartAngle); Swap sin() and cos(). float vecX = cos(realStartAngle); float vecY = sin(realStartAngle);
6,230,350
6,230,632
Keeping std::list iterators valid through insertion
Note: This is not a question whether I should "use list or deque". It's a question about the validity of iterators in the face of insert(). This may be a simple question and I'm just too dense to see the right way to do this. I'm implementing (for better or worse) a network traffic buffer as a std::list<char> buf, and...
if (readpos == buf.begin()) { buf.insert(buf.end(), newdata.begin(), newdata.end()); readpos = buf.begin(); } else { --readpos; buf.insert(buf.end(), newdata.begin(), newdata.end()); ++readpos; } Not elegant, but it should work.
6,230,376
6,230,656
Why virtual function can't be unimplemented when allocated with 'new'?
struct A { virtual void foo(); // unused and unimplemented virtual void bar () {} }; int main () { A obj; // ok obj.bar(); // <-- added this edition A* pm = (A*)malloc(sizeof(A)); // ok A* pn = new A; // linker error } For objects on stack it works fine. But for allocation on heap with new (not m...
Firstly, this code is not compilable, since in C++ void * cannot be implicitly converted to A *. An explicit cast is required. Secondly, the example with malloc is completely irrelevant. malloc allocates raw memory, with has absolutely no relation to any specific types. In this case malloc knows noting about any A and ...
6,230,448
6,230,473
Is it possible to have a templated constructor like 'template<class T> X(){}'?
struct X{ template<class T> X(){} }; Is it possible to instantate such a type?
Yes, it is possible to have such a constructor, but it's impossible to call it. All the template parameters of a templated constructor must be deduced from the parameter list or have a default value. In Your example you can't instantiate the class. [temp.mem] [ Note: Because the explicit template argument list follows...
6,230,690
6,230,725
Visual C++ copy char array into char array
Need help with copying array object to a temp array object using a for loop (see code + comments below)..... Thanks in advance!!!! int counter; char buffer[] = "this is what i want 0 ignore the rest after the zero"; // char command[sizeof(buffer)]; for ( counter = 0; counter < sizeof(buffer); counter++...
http://ideone.com/haCBP Your code is working fine: output: this is what i want this is what i want Edit: That being said, you need to initialize your output buffer: char command[sizeof(buffer)]={}; // now the string will be null-termiated // no matter where the copy ends
6,230,869
6,230,958
Tiny numbers in place of zero?
I have been making a matrix class (as a learning exercise) and I have come across and issue whilst testing my inverse function. I input a arbitrary matrix as such: 2 1 1 1 2 1 1 1 2 And got it to calculate the inverse and I got the correct result: 0.75 -0.25 -0.25 -0.25 0.75 -0.25 -0.25 -0.25 0.75 But when I tried mu...
You've got numbers like 0.250000000000000005 in your inverted matrix, they're just rounded for display so you see nice little round numbers like 0.25.
6,230,893
6,231,268
Developing C++ concurrency library with "futures" or similar paradigm
I'm working on a C++ project that needs to run many jobs in a threadpool. The jobs are failure-prone, which means that I need to know how each job terminated after it completes. Being a Java programmer for the most part, I like the idea of using "futures" or a similar paradigm, akin to the various classes in Java's uti...
Futures are both present in the upcoming standard (C++0x) and inside boost. Note that while the main name future is the same, you will need to read into the documentation to locate other types and to understand the semantics. I don't know Java futures, so I cannot tell you where they differ, if they do. The library in ...
6,230,901
6,236,699
linker says _IsolationAwareLoadLibrary is undefined - any ideas?
I added some boost stuff* to my code and the linking phase failed with: error LNK2019: unresolved external symbol _IsolationAwareLoadLibraryA@4 referenced in function "void * __cdecl boost::interprocess::winapi::load_library(char const *)" (?load_library@winapi@interprocess@boost@@YAPAXPBD@Z) Can anyone help me figur...
It turned out the project I used had a "ISOLATION_AWARE_ENABLED=1" added to preprocessor definitions. Removing it fixed the linker error. Not sure whether this won't cause any other problems though. The disturbing fact is that I'm wasting lots of time just resolving various issues related to building my project with th...
6,230,954
6,231,189
linker error using external FreeVerb C++ classes in iOS project
i'm trying to use the freeverb reverberation library in an audio synthesis project. i've added the source files to the Xcode project, but when i want to use a class from the library, i get a linker error: Undefined symbols for architecture i386: "fv3::nrevb_::nrevb_()", referenced from: -[FreeVerbModule .cxx_construc...
Are you experiencing a 32 vs. 64 bit issue as discussed here?
6,231,104
6,231,195
Behavior of the C++ extraction operator when used to read into a string
I was working with some C++ code, and noticed some code of the following form: ss >> str; where ss is a stream (a stringstream, in this case), and str is a string. What is the defined behavior of this code? Specifically, what is the value of str after this is executed?
Unless the skipws flag is set in ss.flags() (it is by default, but you can unset it), white space is skipped (and not copied into str), then ss copies text from the input until either a white space or end of file is encountered (or it runs out of memory, or it reads std::string::max_size characters). What is white spac...
6,231,162
6,233,308
OpenCV: is it possible to perform openGL pixel shading with it?
How to execute OpenGL pixel shaders on top of openCV images structures? is there any library or plugin for OpenCV for that?
I won't include setting up a OpenGL context, performing actual render operations etc. Consider this as an outline in pseudo code just trying to give you an idea on how you could do it (assuming you'd like to reuse the ouput in OpenCV: At first you create a texture (has to be done once only, of coirse), then you upload ...
6,231,206
6,231,224
"lib" Prefix on Libraries
From http://www.adp-gmbh.ch/cpp/gcc/create_lib.html: Note: the library must start with the three letters lib and have the suffix .a. Is this an operating system convention, or a gcc/ar quirk? Xcode seems to be able to create libraries without the prefix. What's it doing differently?
You can name a library whatever you want, but if you want gcc's -l flag to find the right one, you need to name it the way that link describes. For example: gcc -o myapp myapp.c -lm Will compile myapp.c, link the resulting object with libm.a, and output an executable called myapp. These days, there might be a more ...
6,231,336
6,231,369
Is is possible to use std::map in C++ with a class without any copy operator?
I'm using a Class (Object) that doesn't have any copy operator : it basically cannot be copied right now. I have a std::map<int,Object> objects variable that lists objects with an int identifier. How could I add an Object to this map without having to use copy operators? I tried objects.insert(std::pair<0,Object()>);...
In C++03, objects that are stored in STL containers must be copyable. This is because a STL container's std::allocator actually uses the placement version of the new operator to copy construct the objects in pre-allocated memory blocks, and that requires the existence of a copy-constructor to copy the actual instance ...
6,231,494
6,235,366
Shrinking QDialog With Function Call
I have a dialogue that is created and managed by the central application. The dialogue generates widgets at runtime and has a member function to restore the dialogue to its default arrangement, I.e. button box at the top and a single widget on the bottom. This restore function is called while the dialogue is hidden. I ...
I'm guessing there's a problem with your use of deleteLater here. The child widgets will only get deleted once you go back to the main event loop, and that will only happen after restore() is finished (i.e. after you've called adjustSize). Have you tried removing the child widgets from whatever layout they're in before...
6,231,520
6,231,529
Does re-use of file pointers cause a memory leak?
It's been several years since I've dealt with C++, so bear with me... I have a memory leak in my program which causes a run-time error. Could this be causing the error? I have a global variable FILE *fp; In a callback funciton, I have: fp = fopen(filen,"w"); // do some writing fclose(fp); This process is repeated sev...
This approach won't cause any memory leaks so long as the fopen is always followed by a fclose before the nextfopen call. However if this is indeed what's happening I would question the need for a global variable. It's much safer overall to make this a local and pass it around to the functions which need to output i...
6,232,066
6,232,083
problem with passing custom array to function (c++)
I have an array of type T which I pass as a pointer parameter to a function. The problem is that I can't write new data to this array properly, without getting memory violation at the second try. In this code I read integers from a text file and pass them to the function (part of template class of type T), in order to ...
*apBuf[i] = var; This is parsed as if it was written: *(apBuf[i]) = var; This is obviously not what you want; apBuf is a pointer to a pointer to an array; you are treating it as a pointer to an array and you are dereferencing the ith element of it. What you really mean is: (*apBuf)[i] = var; *apBuf gives you "the o...
6,232,294
6,232,526
Which compiler is right? 'template' before templated return type needed?
This snippet (taken from this question) compiles fine with g++ (as seen), so long the template before the return type is there. In contrast, VC10 does not compile that code with the following error: error C2244: 'A::getAttr' : unable to match function definition to an existing declaration If I remove the template, VC...
GCC is right. AttributeType is a dependent template-name which is followed by angle bracket <, so the keyword template is required here to remove the ambiguity1, making it clear to the compiler that what is followed is a template-name. The rule is mentioned in §14.2/4: When the name of a member template specializati...
6,232,369
6,232,678
Making template class get another class as <T> and consider it as data type (C++)
I suppose to do some unusual stuff. I have a class template: template<class T> class CFile I want to build another class which would have a member of int type, class foo { private: int memb; } when I pass the "foo" class as "< T >" to "CFile", foo is supposed to simply act as integer. I need ideas how to implem...
What I think you're trying to do is for class foo to act as an integer. For this effect you need to provide: A constructor that can create a foo from an int. An overloaded cast operator that implicitly casts your foo class to an int. You would have something like this: class foo { public: foo() {} // Create a foo w...
6,232,562
6,232,592
Can I create a C++ "zap" function that works on a pointer if it hasn't had memory allocated to it?
I have a zap() function written to deallocate a 1-d array as follows. void zap(double *(&data)) { if (data != NULL) { delete [] data; data = NULL; } return; } I was under the impression that if data != NULL would not try to deallocate memory that had never been allocated, but I think I am...
Pointers do not get magically initialized to 0, only when they are global or static. You need to do so: double *xvec = NULL; double *yvec = NULL; If you do not, they contain random junk that was left on the stack where they are created. And this junk is most of the time not NULL. Also, you do not need to check against...
6,232,642
6,232,912
Call Hierarchy Eclipse feature in Vim?
I am considering migrating from eclipse to vim for c++ development- I've recently "rediscovered" Vim, and finally went beyond the basics. I'm loving it, but there are still a few features that I use constantly in Eclipse that I'd also like to see in Vim. One of them is call hierarchy. It's extremely helpful to know whe...
https://stackoverflow.com/questions/149558/recommended-vim-plugins-for-c-coding A combination of the cscope and taglist plugins (linked from above) should give you what you want. Possibly cctree. All of these have problems with templates, however. Also check out eclim
6,232,667
6,232,704
C++: how to use a template on both classes and primitives?
I have a question about templates that can be used with parameters that are either a class or a primitive type. Here's some sample code: (Note: I have real code that's more complex, the following code is useless but it reproduces the same issue) template<typename T> class Foo { T value; public: Foo() {} const T&...
It is perfectly legal to bind temporaries to const references as you do in setValue(). Intel C++, which issues this remark, is not being helpful in this case. EDIT: I am guessing that TI compiler is based on Intel, which, for me, issues the following diagnostic on that line: test.cc(28): remark #383: value copied to te...
6,232,741
6,232,791
ofstream ifilestream and using cin to get an array of chars?
So I am learning how to use streams to make files of my own type, I have a simple version of it working like this struct Appointment { Appointment() { } // //and int to represent a certain doctor int doctorID; // an enum to be made later int year; // 1950 - 2050 100 years total int month; // 0 - 11 int day...
To input a string that contains spaces, use cin.getline(), which reads up to a newline: char doctorID[20]; ... cout << "\nEnter a Doctor ID :" << endl; cin.getline(appoint.doctorID, 20); If you want a string whose size is determined at runtime, you should use std::string, which can be dynamically resized. However, if...
6,232,844
6,232,881
Segmentation fault in File I/O
I have written a code to read a file, store it in a structure and just display it. But somehow it is giving me a segmentation fault and I dont know why. Can someone please help me? Output: file: /home/neel/map2.txt file opened Start Intersection a->road: 4 a->roadId[0]: 1 a->lane[0][0]: 2 a->lane[0][1]: 2 a->roadId[1...
Your lane is an array of 2 elements, however when i reaches 2 in your inner loop you are trying to print a->lane[2][0], which doesn't exist.
6,232,864
6,232,894
Which C/C++ Compilers do enterprises use on Linux?
I have been using the GCC Compiler for months, which is great, and works very well. But I wonder which C++ Compiler do big/medium enterprises use for high optimizations/performance in Linux (x86, PowerPC...). It may seem a very stupid question, but I havent found the answer anywhere. As far as I know, the best PowerPC ...
In the places I have worked we have always used gcc, even for embedded applications/software. Performance improvements are much more likely to come from your code rather than your compiler choice anyway!
6,232,887
6,232,913
Multiple projects referencing MFC: "use mfc in a static library" vs "use mfc in a shared dll"?
Using Visual Studio 2010 C++. I have a project which uses MFC and I am statically linking to MFC. I am in the process of trying to extract the non-GUI functionality into a separate static library project. Because I want to use CStrings in my library project (debatable whether I should, but for the sake of argument) ...
You don't need to link a library project, so there won't be an extra copy of MFC being linked in. You'll be creating a dependency on the MFC library from your static library, but that's normal. As long as the .exe project includes both libraries, everything will come out all right in the end.
6,233,085
6,233,157
C++ pure virtual methods
Consider this demo program: #include <stdio.h> class Base { public: virtual int f(int) =0; virtual int f(){ return f(0); } virtual ~Base(){ } }; class Derived : public Base { public: int f(int i) { return (10 + i); } }; int main(void) { Derived obj; printf("%d\n", obj.f(1)); ...
The reason is, that the defined f (in Derived ) hides the f functions from the Base class. The solution is to add using. Like this: class Derived : public Base { public: int f(int i) { return (10 + i); } // vvvvvvvvvvvvvv using Base::f; };
6,233,120
6,233,296
protobuf: consecutive serialize and deserialize to/from socket
My simple communication between C++ client and C# server got stuck after a message was serialized to socket (SerializeToFileDescritor). C++ client: Person person; person.set_id(54321); person.set_name("bla"); person.mutable_address()->set_line1("sdfa"); person.mutable_address()->set_line2("asdfsdfa"); cout...
The default behaviour for a root object is to consume all data to the end of the stream. And since you don't close the stream, that end never comes. If your intention is to send multiple objects down the same socket (which is pretty normal) then you need to give it a clue. The most common approach would be to prefix ea...
6,233,123
6,233,205
Passing thread routine multiple variables & stack size
In examples on the web, calls to CreateThread typically pass a pointer to a struct for LPVOID lpParameter, and you use that pointer to access the struct itself. #include <Windows.h> #include <stdio.h> struct Point { float x,y,z ; } ; DWORD WINAPI threadStartPoint( LPVOID data ) { Sleep( 1000 ) ; Point *p = (Poi...
CreateThread accepts only one type of function, the one that takes a single LPVOID parameter. There's no way to communicate to kernel32.dll, which is the code that calls your thread function, that it should call it with any other parameter list. The kernel always calls the function the same way. You'll just have to con...
6,233,132
6,233,155
C++ compiler error: ambiguous call to overloaded function
string aux; int maxy,auxx=0; cin>>aux; maxy= (int)sqrt(aux.size()); I'm geting: 1> error C2668: 'sqrt' : ambiguous call to overloaded function 1> could be 'long double sqrt(long double)' 1> or 'float sqrt(float)' 1> or 'double sqrt(double)' Why?
string::size() returns size_t, and sqrt doesn't accept it in any of its versions. So the compiler has to cast, and cannot choose to what - all of them are OK. You have to put explicit cast: maxy = (int)sqrt((double)aux.size());
6,233,325
6,255,483
Easiest way to add a GUI to C++ app
I am producing a piece numerical software in C++ and want to add a GUI (mainly for Windows). I know how to produce GUIs using comfortable editors in modern languages like Java or .NET. Now my question is what is the easiest and most comfortable way to add a GUI frontend for my program. In the choice of the tools am com...
The statements about ISO C++ in this answer's comments are poorly edited. None of the solutions presented here would impose on the computational code a requirement of changing to a different dialect of C++. The GUI code itself might be another story. The answers about using Windows Forms with managed C++ are probably t...
6,233,359
6,233,385
base64 to reduce digits required to encode a decimal number
I have to manage an ID of some objects. I need these ID be unique. I have the constraint that these ID can't be too long in term of digits required Is base64 is a nice way to reduce the number of digits required to encoding an ID ? EDIT: langage : c++ data type : integer , then convert in a std::string
Each character in Base64 can represent 6 bits, so divide your ID length by 6 to see how many characters it will be. Binary data is 8 bits per byte so it will always be shorter, but the bytes won't all be readable. Base64 will make the ID readable, but it still won't be good if the ID needs to be hand entered, like a ke...
6,233,656
6,233,739
Segmentation fault when run as root?
My c++ program gives me a seg fault when I run as root from my computer but not when I start a remote session. My program run from my computer only as a user. What can be the problem? I wrote my program for an embedded device and I'm using this to compile: gcc -Werror notify.cc -o notify `pkg-config --libs --cflags gtk...
You might want to run your program under valgrind. I wrote a tiny program that writes outside of an allocated array: $ valgrind ./segfault ==11830== Memcheck, a memory error detector ==11830== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. ==11830== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun wit...
6,233,879
6,233,897
Move or Named Return Value Optimization (NRVO)?
Lets say we have the following code: std::vector<int> f() { std::vector<int> y; ... return y; } std::vector<int> x = ... x = f(); It seems the compiler has two approaches here: (a) NRVO: Destruct x, then construct f() in place of x. (b) Move: Construct f() in temp space, move f() into x, destruct f(). Is the c...
The compiler may NRVO into a temp space, or move construct into a temp space. From there it will move assign x. Update: Any time you're tempted to optimize with rvalue references, and you're not positive of the results, create yourself an example class that keeps track of its state: constructed default constructed mo...
6,233,916
6,233,938
C++ multiple file error
i have been attempting to pass an object into a function that belongs to a class both classes are in there own files...but when i try to pass the object as an argument for the function prototype it gives me an error saying that the object doesn't exist... ill provide some pseudo code to demonstrate my problem //class 1...
You'll need to include Class2's header file in Class1.h. That is: ////////////////// //Class1.h #include "Class2.h" class Class1 { public: void function(Class2 arg); }; If you are only using a pointer to Class2 as an argument, then you can forward declare Class2 instead of including the header, that is: ////////...
6,233,990
6,234,006
What is wrong with following C++ code (regarding shared_ptr)
I am trying to get up to speed with using shared_ptr, but I can't seem to figure out why the following code wont compile. In the header file, private member declaration: std::map<std::string, str::tr1::shared_ptr< std::vector<int> > > *_myMap; In the constructor, trying to instantiate an object of the above: _myMap = ...
You cannot have posted your code verbatim. Your header must say std::map<std::string, std::vector<int> > *_myMap; Are you sure you're building properly? Try a fresh build.
6,234,300
6,234,741
C++ accessing a function from in a class, receiving functions as a parameter
i have two questions that are fairly small and related so i will put them both in the same question. i have been experimenting with classes and i was attempting to access a class in another file that wasn't in a class so for example. //class 1 .cpp void Class1::function1()//another error { function() } //main.cp...
How to access a function in another file? Depends on the type of function, there can be to cases: 1. Accessing class member functions in another file(Translation Unit): Obviously, you need to include the header file, which has the class declaration in your caller translation unit. Example code: //MyClass.h class M...
6,234,457
6,234,481
Using XML files to store data
If i'm going to use a XML file to store some information, Am I going to need a XML Parser that read/write data? Can i just use string manipulation functions and why not?
You could conceivably use string manipulation functions, as that's what XML libraries end up using anyway. XML documents are just long strings in a special format. However, unless you know a lot about XML (and what is and isn't valid XML), using an XML parser/serializer now will save you a lot of trouble later on. T...
6,234,762
6,234,805
How Can I return second element of stack without pop() function in C++?
I need help for return second element of stack without pop() ? but I don't know how can I use. my code : stack<int> st; st.push(10); st.push(20); st.top(); // return 20 How do can I make this function is return 10 without pop(); Thanks. P.S. sorry for my English.
I presume you're trying to emulate a stack-based machine? Here's the only way to do it with std::stack: stack<int> st; st.push(10); st.push(20); int top = st.top(); // return 20 st.pop(); int second = st.top(); // return 10 st.push(top); If you want other behavior you'll have to do your own implementation of stack tha...
6,234,817
6,234,906
Large static data member, inheritance, and performance
I'm not too sure how to ask this question. I need to store a ton of data into a vector at the beginning of the program, but only once. I tried putting that vector, my_vect, inside a constructor in a base class to load all the data into it, but the problem is, that data needs to be used by the derived classes that will ...
Why do you need to inherit from the singleton to use the data it provides? You can make a singleton as the data provider, and make the other classes use it to access the data. In fact, you don't even need a singleton. Just make an ordinary class with a static field and a static method to initialize the field. Then call...
6,234,912
6,235,058
C++ Pass by const reference syntax
I know the topic of pass by reference vs. pass by pointer is heavily covered... Pretty sure I understood all the nuances until I read this: http://carlo17.home.xs4all.nl/cpp/const.qualifier.html which reads (in case the link goes dead) The prototype for foobar can have any of the following footprints: void foobar(TYPE)...
If TYPE is a #define for something like int*, the placement of const does matter. In that case you will get const int* or int* const depending on the placement of const. If TYPE is a typedef or a template parameter, the const will affect the whole type either way. To me this looks more like another argument against ma...
6,235,057
6,235,182
Interacting(get itemcount, loop, click each item) with CUSTOM listview control?
I am trying to interact with custom listview class, the class along with its instance is recognized by winapi but for sure it has problem interacting with it. What i am trying to do is get item count then click on each(when required) but WinApi is unable to do anything about this. int nMaxItems = ListView_GetItemCount(...
Since it's a custom control, and not the standard Windows control, it is under no obligation to honor the same set of messages that the standard controls respond to. If it doesn't recognize the same messages that the OS provides, then you'll just have to find out what mechanism, if any, it does provide for external cod...
6,235,381
6,235,423
Running class method in another class method
i would like to run a function method of a class inside another function method of another class. I wrote the following code as an example and it compiles and return the expected values. My question is if this is the correct way of preforming a computation of class method inside another class method... Regards #includ...
There are two straightforward ways to do this. One of them, the one you chose, is to pass an external class object to another object method. The other is to encapsulate an object inside of another object and to call it directly from a method of the enclosing class. There may be more esoteric ways of doing this, but t...
6,235,460
6,235,482
C++ Intellisense doesn't work (not even Ctrl+Space), no function name, no parameter list, nothing
I have recently install the C++ in order to re-learn the language (have done some small project on it). One thing that really annoys me is that the auto-complete function when implementation doesn't work anymore. More specifically the auto-completing of the parameters and function name. I have already declared my c...
Make sure you are not targeting the .NET framework (compiler option /clr ) Otherwise it should work for all native C++ programs
6,235,555
6,235,569
Get size of a std::string's string in bytes
I would like to get the bytes a std::string's string occupies in memory, not the number of characters. The string contains a multibyte string. Would std::string::size() do this for me? EDIT: Also, does size() also include the terminating NULL?
std::string operates on bytes, not on Unicode characters, so std::string::size() will indeed return the size of the data in bytes (without the overhead that std::string needs to store the data, of course). No, std::string stores only the data you tell it to store (it does not need the trailing NULL character). So it wi...
6,235,875
6,236,088
Finding an element in partially sorted array
I had a following interview question. There is an array of nxn elements. The array is partially sorted i.e the biggest element in row i is smaller than the smallest element in row i+1. How can you find a given element with complexity O(n) Here is my take on this: You should go to the row n/2.And start compare for examp...
Your solution indeed takes O(n log n) assuming you're searching each row you parse. If you don't search each row, then you can't accurately perform the binary step. O(n) solution: Pick the n/2 row, instead of searching the entire row, we simply take the first element of the previous row, and the first element of the ne...
6,235,907
6,236,167
How is `>>>` lexed in C++0x?
>>> is lexed as >> >. But what happens if the first > closes a template argument list, should the result be equivalent to > > > or > >>? It does matter in the following code: template<class T> struct X { }; void operator >>(const X<int>&, int) { } int main() { *new X<int>>> 1; }
The text of the FDIS says Similarly, the first non-nested >> is treated as two consecutive but distinct > tokens It cannot unlex tokens and relex. So this will be a > > >. Note that the input to a C++ implementation is first lexed into preprocessing tokens, and then those tokens are converted into C++ tokens. So firs...
6,235,924
6,236,012
Force derived class to override at least one virtual function
Imagine this simple base class: struct simple_http_service { virtual reply http_get(…); virtual reply http_post(…); virtual reply http_delete(…); // etc. }; I'd like to prevent the user from deriving from this class without overriding at least one of these and prevent them from instantiang simple_http_service ...
That sounds like a really odd constraint. By all means protect the user from incorrect usage, but don't try to prohibit things that you just "can't see the point of". If there's no point in deriving from your class without overriding any of the three functions, then let the user override as many or as few function as h...
6,235,949
6,235,964
Where can i find collection of various common File Extension structure?
Suppose i want to fstream some image file like jpeg, i'd need to know its internal structure, and how it is stored. Therefore, i just want to know if there exist some website that collect information on structure of each file extension? There's only website such as filext.com that tell us about what kind of file it is....
http://www.wotsit.org/ Has descriptions for many file formats. You will have a hard time implementing parsers for "all common file extensions" though. You are probably going to have better success using libraries, or depending what you are trying to do, using OS-specific file info functions. Maybe even supporting an ex...
6,236,020
6,236,573
transfer int over network
I am new to network programming so I have a question: is it safe to send an integer (let's assume 16 bit integer because 32 has issue with "endianess") in my case between C++ and C# and how do that? In my program I cast int to char (I know is is lower than 255) and send it. However, I would like to send 32 int. I tried...
If you are writing with protobuf-net, the WithLengthPrefix methods will do this for you. I'd be more than happy to help with this (I'm the author). Btw, the reason it is throwing an exception is that a varint value by itself is not normally valid in a protobuf stream. The system will override this in the case of WithLe...
6,236,159
6,237,562
Could a set of function differing in the name depending on the operand types called theoritically statically polymorphic in C language?
Does a set of functions doing exactly one word but differing in the name like atoi , atol, atoll etc called theoretically polymorphic? For example I have a function say swap which needs to operate on different kind of data types. So i have one function/operation for which i have different implementations, but unfortuna...
In my opinion it is not incorrect, because the polymorphism and other object oriented terminologies are not something which is language dependent, and is a concept. Now, different languages provide different features with which the implementation of an object model is much easier, and some features are only possible wh...
6,236,262
6,236,562
How to access a variable from another class in Qt?
I am trying to implement in Qt a main window which has 2 widgets: one area where I draw some points and one list box where I write all the points with their respective coordinates. And I would like to implement the function "delete point" of a button on the main window, i.e. when I press the button then the point selec...
I'm suspecting you've got two RenderArea widgets hanging around for some reason. You're connecting ui->displayWidget's signal, but acting on the area widget for the delete. Shouldn't you be calling ui->displayWidget->deletePoint or connecting area's signal? As for the repaint, you should call the widget's update() meth...
6,236,468
6,236,516
calling kernel32.dll function without including windows.h
if kernel32.dll is guaranteed to loaded into a process virtual memory,why couldn't i call function such as Sleep without including windows.h? the below is an excerpt quoting from vividmachine.com 5. So, what about windows? How do I find the addresses of my needed DLL functions? Don't these addresses change with every ...
The article you quoted focuses on getting the address of the function. You still need the function prototype of the function (which doesn't change across versions), in order to generate the code for calling the function - with appropriate handling of input and output arguments, register values, and stack. The windows.h...
6,236,684
6,236,739
Optimizing subset sum implementation
I'm working on a solution to a variant of the subset sum problem, using the below code. The problem entails generating subsets of 11 ints from a larger set (superset) and check if it matches a specific value (endsum). #include <stdio.h> #include <stdlib.h> #include <assert.h> int endsum = 0, supersetsize = 0, done = 0...
One way to only generate unique subsets is to add the elements from the superset in order, and use an additional argument to permute (eg. supersetPos) to indicate where you are in the superset. This generates sorted permutations which will be unique. EDIT: Code that AFAIK runs correctly on your sample: #include <stdi...
6,236,743
6,238,201
Wrapping parts of boost::asio in a C library - for use on embedded Linux
I'm looking for a good ( and simple ) sockets library that I can incorporate into an XMPP client I am building in C for embedded Linux. Lots of people have recommended boost::asio, and since I am already familiar with C++ and some aspects of boost - I thought I might wrap this up into a C library to be called from my c...
Using Boost ASIO to implement a C interface does sound a bit complicated and mismatched. How about starting with something more native to C, like libevent? I know it's not the same, but it's a start, and socket programming is well supported in C itself.
6,236,760
6,236,788
String Comparision without Special Character
I have strings having special characters e.g. "ravi", "Ravi" ,"!ravi","ravi...","RaVi)" etc.. I want all these to be treated as same. How to achieve this. Can be in shell script, C,C++,JAVA. Thanks, Ravi.
Java: str.toLowercase().replace("[^a-zA-Z]", "") will render them all in lowercase with special chars removed and therefore all equal() Edited to cover everything not alpha as "special"
6,236,799
6,236,830
How to separate inner class of template class into other file
I want to do: typedef MyTemplateClass<Type01, Type02> TClass; TClass t; TClass::InnerClass i; i.test(); i think the solution could be: template <typename A, typename B> class MyTemplateClass { public: class InnerClass { //here I can do stuff with A and B A test() { return 0; } }; frien...
You can't. In a nutshell. Templates must be wholly defined before instantiation- that means that whatever you do, you'll have to define the inner class in the template class anyway.
6,236,824
6,237,773
Using Boost.Spirit.Qi with custom lexer
I dug through the whole documentation and couldn't find an example. All the examples either parse character data or use Spirit.Lex. Forgive me if I missed something. Can someone give an example for, or point to a tutorial on, how to use Boost.Spirit.Qi with my custom lexer? E.g.: vector<MyTokenType> tokens = GetTokens...
You will have to do sevaral things: a) expose the token sequence as a range of iterators, which will have to be passed to parse/phrase_parse b) add a default conversion operator to your token type exposing the token id struct token { operator int() const { return id; } }; that allows to use qi::char_(ID) as a pars...
6,236,827
9,353,971
Assertion failure in Luabind
I am currently having problems using Luabind to interface a Lua scripted AI with a C++ game. I call an update function inside a loop (once per frame) and this function retrieves informations from C++ functions registered in Luabind. My problem is as follows : After a variable, non predictible time, there is an assertio...
I had this problem a few days ago. In my particular case, the implicitly created Lua table that held all the methods that had been overridden in Lua for each object was being garbage collected, while the underlying C++ object was not. Because of this, if you tried to call a Lua member function from a C++ object, it wou...
6,236,833
6,237,383
Exact real arithmetic and lazy list performance in C++/Haskell
I recently came across the subject of exact real arithmetic after reading this paper and this paper. I have found a number of papers that discuss realizations of exact arithmetic using signed digit streams. The use of infinite streams for arbitrary precision leads to nice practical implementations in functional languag...
is there something inherently slow about a signed digit/lazy stream representation that causes the bad performance, or is it Haskell? What is it that makes it slow? Would it be possible to implement a signed digit stream representation using lazy streams in C++ that achieves (significantly) better performance than its...
6,236,880
6,236,896
Question about EXC_BAD_ACCESS error in std::vector::push_back on a pointer
std::vector sure is great, hey? I'm getting an EXC_BAD_ACCESS in using push_back to add an element, though. (I had a similar problem once, looked it up on SO, solved! Sadly, this appears to be a different issue.) class BackgroundGroupsHandler { public: void addBeat(Beat *b); vector<beat_display_group*> grou...
The problem is most likely that the BackgroundGroupsHandler that you are calling addBeat on is NULL or otherwise an invalid pointer. The problem shows up in the std::vector code because you are using groups, which will be invalid due to the BackgroundGroupsHandler being invalid.
6,236,881
6,236,988
Naming conflicts between different libraries
I'm trying to compile my program with two statically linked libraries: SFML and PhysFS. However, at the linking phase I get the following errors: eror LNK2005: _inflatePrime already defined in sfml-graphics-s.lib(inflate.obj) error LNK2005: _inflateGetHeader already defined in sfml-graphics-s.lib(inflate.obj) erro...
Both libraries seems to have preferred to include the zlib library instead of having a dependency on it. I'd try to build them without this inclusion and link the executable with zlib.
6,236,929
6,236,935
How do we rotate a figure in 2d in openGL with respect to a point (other than the origin)?
Using the glrotatef() function rotates the figure by a specified angle with respect to the origin. How do I rotate the same figure with respect to another point without making use of transformation matrices manually? Thanks! void display(){ glClear(GL_COLOR_BUFFER_BIT); gluOrtho2D(0,499,0,499); glMatrixMode...
Basically: If you want to rotate around P, translate by -P (so that P moves to the origin), then perform your rotation, then translate by P (so that the origin moves back to P). glTranslatef(P.x, P.y, P.z); glRotatef(angle, A.x, A.y, A.z); glTranslatef(-P.x, -P.y, -P.z); (Note: This is in "reverse order" because the l...
6,237,214
6,237,728
Extract long from arbitrary bitset subsequence
Is there a way to extract a CPU word size long subsequence of bits from a bitset efficiently without iterating over each bit individually? Something like #include <bitset> #include <iostream> using namespace std; int main() { bitset<100> b; // Do something with b // ... // Now i want ...
You could create a constant bitset mask that only has the bottom N bits set, eg like this: bitset<100> const mask((unsigned long) -1); Then you can do ((b >> 50) & mask).to_ulong() to extract the bits. If your definition of "word" isn't the same as unsigned long, a different mask will be needed. (I changed your left s...
6,237,300
6,237,333
Search in array or switch? For a cipher by substitution
I'm coding a classical cipher by substitution in C++, using all the printable characters in ASCII, and I'm wondering which is faster? A search in an array (edit: a non associative one, just something like letters[] = {'a', 'b', ...); (linear or binary) or a switch statement? The compiler can optimize the switch, doesn'...
There's certainly a chance that a sufficiently smart compiler could optimize the switch to be a lookup, which would be faster than a binary search. But you could do that optimization yourself and get short code: char alphabet[] = { 'Z', 'E', 'B', 'R', 'A', 'S', 'C', 'D', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', ...
6,237,374
6,237,434
How can i check if a template is compiled out?
Is there a simple way to check if my template has been optimized out? After using #define HIDE_IT the code in play is below. I'm sure this code is optimized out so i get 0 overhead from defining Property<SomeType> but i like to check if possible (without going into assembly. Trivial code is hard enough to read after th...
There's no other way other than looking at the assembly. The only way it can be "optimised out" is by inlining those functions, and you can only check that by looking at the source. That being said, on any modern compiler you can be pretty sure that those functions will be inlined in optimised code.
6,237,403
6,237,487
c++ inheritance darray from array
i do this in the education purpose. such is idea: i have class Array. I inheritance it in class Darray, and add necessary dimension it likes so: main.cpp int main(int argc, char *argv[]) { Array obj; obj.output(); DArray obj2; obj2.output(); return 0; } header class Array { pub...
There are no memory leaks, but there is one mismatch between new and delete: You're using new[] here: for(i=1;i<sizem;i++) z[i]=new int[sizem]; but you're using delete (not delete[]) here: for(int i=1;i<sizem;i++) delete z[i]; With that changed to delete[] z[i];, there are no warnings from valgrind: ==29235==...
6,237,577
6,237,653
How to display a dialogbox inside a tab control page?
How do i set another dialogbox visible inside the tab thats currently open in the Tab Control object? I'm creating the Tab Control in the Visual Studio 2008 resource editor (or how its called?), i created IDD_FORMVIEW dialogbox for the tab control. I know how to initialize the tab texts, handle the currently selected t...
All the 'tab pages' which are dialogues should be set as children to the tab that is created. When a tab is changed you will get a notify message which you can handle in your DialogProc like this: case WM_NOTIFY: { switch( ( ( LPNMHDR ) lParam) -> code ) { case TCN_SELCHANGE: { if( TabCtrl_GetCurSel( ( ( ...
6,238,216
6,238,310
Store or reflect on the "reference level" of a variable
Is there a way in C++ to reflect on the "number of levels of pointer" of a variable, (for example, int* a is 1 level, int** b is 2 levels, and int c is 0 levels) ..Other than using typeid and parsing the string that comes out of that? The reason I'm asking is I am using pointers to member functions, and I need to know ...
You could use std::is_pointer from the type_traits header in TR1 (which uses partial specialization to produce an answer), but it might be simpler to just use overload resolution. Here's an example, assuming void return, no arguments, and no need to handle more than one level of indirection: template <typename T, typen...
6,238,544
6,238,551
Implicit cast of class derived from template base class
I've got a problem with implicit casting, templates and inheritance from template classes. The following is what I extracted from my project, I have left out that some classes are even abstract, but it does not have to do with the case. class A {}; class B : public A {}; template <typename T> class Base {}; class Deri...
This is not possible. Base<A> has no relation to Base<B>, regardless of the relation between A and B.
6,238,547
6,238,685
Reference level part 2
Expanding on this question, it looks like I did not provide enough detail. I have an object called CallbackObject that is designed to contain an object instance, and the information of what function to invoke, and the parameters to pass at invokation time. template <typename objectType, typename memberFuncti...
Here's an example helper function, assuming void return, one argument, and no need to handle more than one level of indirection: template <typename T, typename F, typename A> inline void invoke(T& obj, F func, const A& arg) { (obj.*func)(arg); } template <typename T, typename F, typename A> inline void invoke(T* o...
6,238,651
6,238,667
C++ Database Access With No Required Installation
I am looking for a database that can I run SQL statements on without having to have a database server installed. I.e. I need the ability to select/insert/update a database given only the database file and any external libraries. Here is my situation: I am using C++ to parse through a number of oddly-formatted binary ...
You cannot go wrong with SQLite here. It is small enough to be embedded in many apps (see e.g. here for a list of famous apps ranging from Photoshop to Apple Mail + Safari, Dropbox, Firefox, Chrome, Skype and more), yet complete enough to cover most SQL aspects you may need. Great support too, and wide coverage in ter...
6,238,693
6,238,800
Get File Name via Index
I want to get a file from the index... so say there was a folder, and I wanted to get the first file in that folder and put the name in a string. Is there a function for that?
The FindFirstFile API function returns what the file system considers to be the first file in the directory. If you want some later file, proceed to call FindNextFile the appropriate number of times. In any case, call FindClose afterward. For NTFS, directories store their file names in sorted order. It might not be the...
6,238,799
6,239,078
Manipulating JPEG images pixel-per-pixel using Mini Jpeg Decoder
I want to manipulate JPEG images with C++ using the decoder Mini Jpeg Decoder. The problem is: I want to read pixel per pixel, but the decoder only returns an imageData-array, similar as libjpeg does. I can't make a method like this: char getPixel(char x, char y, unsigned char* imageData) { //...??? } The return ...
As far as I can tell, the Decoder class delivers a byte array of color values with the GetImage() method. So you could write a function that looks like this: char getLuminance(Decoder* dec, int x, int y) { if(x < 0 || y < 0 || x >= dec->GetWidth() || y >= dec->GetHeight()) { throw "out of bounds"; } ...
6,238,811
6,238,889
Creating a window that can only be dragged within the parent window
I have a WIN32/C++ app and I want to create child windows in it that cannot be dragged out of the parent window. I want these windows to be owner-drawn, if it matters anyway. Should be simple enough; I'm looking for some basic guidance and tips regarding the subject.
It seems that you want to make an MDI app. This is much easier using a higher level framework such as MFC, WinForms, VCL etc., but can, of course, be done with plain Win32. The MSDN documentation can be found here: Multiple Document Interface.
6,238,917
6,238,926
single character c-style string full of junk
It's a shame I can't figure out such basic thing about c++, but c-style strings are acting as I wouldn't expect. For example, I create it like this: char* cstr = new char[1]; It's initialized to: Íýýýýý««««««««îţ . Like normal, I can set just first char because others are not really existing (or I thought that they ar...
All C-style strings are null-terminated. So, a string initialized using new char[1] leaves you space for no characters. You can't set the first character to anything but \0, otherwise normal string operations will keep reading into memory until they find a zero. So use new char[2] instead.
6,238,931
6,238,989
How to overload the subscript operator with swig Python
I have a class which contains a std::vector<Foo> where Foo is a class containing a key, value, comment, etc. Please note that there is a reason why I am using a vector and not a dictionary. I have overloaded the subscript operator in C++ such that foos["Key Name"] will search through the vector for a Foo object with ke...
In straight Python, if you want to overload the subscript operator, you would create a __getitem__ and __setitem__ class method. As a simple example: class MyClass(object): def __init__(self): self.storage = {} def __getitem__(self, key): return self.storage[key] def __setitem__(self, key,...
6,239,084
6,239,263
create CvMat from a C++ vector of CvPoint2D32f
I am trying to create a CvMat data structure using cvMat() in OpenCV. The last parameter of cvMat() expects a void* to the data. My data is stored in the following data structure vector<vector<CvPoint2D32f>> data; I expected data.at(0) to work as the last parameter, but the compiler says that it can not convert to vo...
data.at(0) has vector<CvPoint2D32f> type, but you need pointer to the first element of that vector. Try: &(data.at(0).at(0)) Also keep in mind, that vector<vector<CvPoint2D32f>> is not a two dimensional array of CvPoint2D32f. It is more like "vector of references" to one dimensional arrays.
6,239,169
6,239,241
Dynamic array of objects
I'm aware that I could use something called std::vector, but I'm afraid it's not possible because of the course restrictions. I need to make a dynamic extensible array of objects. The array should grow and grow when new objects need to be stored. Here is the class that the array belongs to: class TransactionList { ...
You should add a maxTransactions variable, which would indicate the allocated length of your trans* array, and initialize both ammountTransactions and maxTransactions with 0. Your array would automatically double its size when we reach the limits of trans void TransactionList::add(Transaction & newTrans) { if(amou...
6,239,346
6,239,472
Dynamic bit vector in C/C++
I am looking for an off-the-shelf dynamic bit vector in C or C++ that I can use. Unfortunately for various reasons I cannot use the BoosT libraries at the moment. std:bitvector looks promising but it is templated so I cannot set the length of the bit vector dynamically. Can anyone advise? Thanks!
You don't have to put a dependency onto all of boost and its installation process just to use dynamic_bitset. If the class suits your purposes, copy the source files for it specifically into your project tree and put it in a separate namespace called "boostcopy" (or something like that). On a similar note, I made my o...
6,239,499
6,239,559
Does everything go inside a class?
I have another rudimentary question. I somewhat recall hearing that everything in C++ goes inside a class. Then I hear that classes shouldn't be used where possible. So my question goes: When do you make classes and when do you not? (an example or two would be cool) And a random side-question: When is it appropriate to...
In C++ everything need not go inside a class(as opposed to Java where everything does go inside a class). You should make a class when you want to represent some real world entity for example a person, a customer, an user, animal, car etc. You require to store some data about the entity and have some functions relate...
6,239,630
6,239,654
Trouble with const/non-const overload resolution
I have a class that looks something like this: class ClassA { public: float Get(int num) const; protected: float& Get(int num); } Outside of the class, I call the Get() function. float foo = classAInstance.Get(i); I expect this to call the public version, but instead Visual Studio errors out: error C2248...
It's true, overload resolution takes place before accessibility checks. Section 13.3 of the standard ([over.match]) says: Overload resolution is a mechanism for selecting the best function to call given a list of expressions that are to be the arguments of the call and a set of candidate functions that can be calle...
6,239,721
6,240,269
Where exactly in memory is count of allocated memory thats being used by delete?
int* Array; Array = new int[10]; delete[] Array; The delete knows the count of allocated memory. I Googled that it stores it in memory, but it's compiler dependent. Is there anyway to use get this count?
There are likely one or two counts of the number of elements in such an allocation depending upon the type and the implementation that you are using though you can't really access them in the way you probably want. The first is the accounting information stored by the actual memory manager that you are using (the libra...
6,239,970
6,241,802
Unprotected get function in multithreaded system - needs volatile?
I'm working on a multi threaded program that provides access to one side of an interprocess communication system. Having never used volatile, I'm trying to figure out its proper usage. I understand that (the relevant part) volatile tells the compiler that the variable it's applied to might be written to outside of the ...
The "some people" you refer to are entirely correct. The use of volatile does guarantee that the memory location is read or written each time you do that in the code. It does not guarantee that the value is current or seen by other threads that might run on a separate core or separate CPU. For that you need a memory ba...
6,240,039
6,240,085
glActiveTexture ARB was not found
hi everyone ive got quite an error here it seems like c++ is not finding glActiveTextureARB(GL_TEXTURE0_ARB); im using codeblocks and i've got glext.h so whenever i right click glActiveTextureARB and find declaration it actually finds it... ive got a 64bits system and ive tried putting glext.h in the GL folder and als...
glActiveTextureARB is an extension function. As such under the Windows plattform it does not suffice to include glext.h to make it usable. You also have to define a function pointer and load it with PFNGLGETACTIVETEXTUREARB __myglextActiveTextureARB; #define glActiveTextureARB __myglextActiveTextureARB void initGLexte...
6,240,207
6,240,220
C++: Calling the virtual function of the derived class
Suppose I have a class with a virtual function and a derived class that implements the virtual function in a different way. Suppose I also have a vector of the base class used to store derived classes. How would I execute the virtual function of a derived class in the vector without knowing in advance what the derive...
You can't. The objects in the vector will have been sliced -- any derived-class instance data will have been chopped off, so calling the method would be a super-bad idea. If, on the other hand, you have a vector of pointers to base, then you simply call the virtual method, and the derived-class version will be invoked....
6,240,256
6,240,278
What is sourceannotations.h?
Visual studio keeps including sourceannotations.h to my C++ projects. This file seems to be .NET, and I am not using CLR (only native C++). I wanted to take preprocessed .cpp file to check it in external tool (like clang or cppcheck) but they don't support MS syntax.
According to here, source annotations are used to reduce code defects and it does not seem specific to .Net.
6,240,271
6,247,404
Selectively compiling in code outside of a macro
Is it possible to selectively compile in certain sections of code with templates, or is this limited to the preprocessor? For example, if I wanted to remove a section of code with the preprocessor, I know I can do: #if 0 static const char[] hello_world = "hello, world"; #endif Is there anyway to do the same with templ...
Given your edit, it seems like you're making this a lot harder than it has to be. Where you define your macro, provide an #ifdef block there, and chose how you define it. #ifdef NDEBUG #define unittest(NAME) static void dummy_func_##NAME() #else #define unittest(NAME) \...
6,240,332
6,240,347
What data structure to use
I'm looking for the proper data structure for this scenario. I have boost available to use. The code was originally in C#, and I was using a queue there, but I don't believe that was an appropriate choice, and there isnt a C++ equivalent for C#'s queue as far as I can tell. I'm looking at the following properties in te...
std::deque seems to meet all of your requirements. If performance is a real issue for you, you should read GMan's answer to Pre-allocate space for C++ STL queue .
6,240,660
6,240,864
How to read gmon.out?
How do I read gmon.out in Windows? Windows can't so much as open the file, so gmon.out options doesn't quite work in the command-line window.
gprof is the tool that reads a gmon.out file and displays information from it.
6,240,890
6,240,916
overloading virtual operator -> ()
This is just an experiment code. struct B { virtual B* operator -> () { return this; } void foo () {} // edit: intentionally NOT virtual }; struct D : B { virtual D* operator -> () { return this; } void foo () {} }; int main () { B &pB = *new D; pB->foo(); // calls B::foo() ! } I know that operator has ...
I think it is invoking D::operator->, but the return value is being treated as a B*, so B::foo() is being called. This is an artifact of how covariant return types behave.
6,240,894
8,285,659
Is there a reason on not allowing lambdas to deduce the return type if it contains more than one statement?
Taken from the C++0x FDIS (n3290): If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). If a lambda-expression does not include a trailing-return-type, it is as if the trailing-return-type denotes the following type: if the compound-statement is of the form { attri...
There's no technical reason for this. IIRC it was already implemented by the GCC C++ maintainer and he said it's trivial to implement. The committee is very conservative about accepting features into the Standard so they went with this simple form of deduction and will later hopefully accept a more powerful form. See ...
6,240,944
6,240,972
Classes as parameter of function c++
I wrote a bunch of crypto algorithms as classes and now I want to implement encryption modes (generalized modes shown in wikipedia, not the specific ones in the algorithms' specifications). How would I write a function that can accept any of the classes? edit: here's what i want to accomplish class mode{ private: ...
Well, how about template<class AlgorithmType> class mode{ private: AlgorithmType _algo; public: mode(const AlgorithmType& algo) : _algo(algo) {} }; ? No need for mode and key parameters, as the algorithm can be created by the user: mode<YourAlgorithm> m(YourAlgorithm(some_key,some_mode));
6,240,950
6,240,980
Platform independent /dev/null in c++
Possible Duplicate: Implementing a no-op std::ostream Is there any stream equivalent of NULL in c++? I want to write a function that takes in a stream if the user wants to have the internal outputted to somewhere, but if not, the output goes into some fake place void data(std::stream & stream = fake_stream){ str...
Edit: Taken from @Johannes Schaub - litb's mail here with slight modifications: template<typename Ch, typename Traits = std::char_traits<Ch> > struct basic_nullbuf : std::basic_streambuf<Ch, Traits> { typedef std::basic_streambuf<Ch, Traits> base_type; typedef typename base_type::int_type int_type; typed...
6,240,995
6,241,049
Tic Tac Toe C++ algorithm debugging help
Please help me understand why this isn't working. I don't know if there is a bug in my code, or whether my algorithm is fundamentally logically flawed. My algorithm is based on minimax, but I've forgone a heuristic evaluation function for a more simple technique. Because of the simplicity of plain 3x3 tic tac toe, I...
I think you'll see where the problem is if you make evaluate return the score rather than using return-by-reference. Evaluate should be minimaxing, but right now I think it's doing some weird sum of the leaf nodes because of the side-effect of additions and subtractions. Why summing up the scores is not correct Suppose...
6,241,146
6,241,219
Abstract factory with abstract parameters?
I'm trying to design a good entity creation system with an abstract factory (as per http://www.dofactory.com/Patterns/PatternAbstract.aspx) but I'm struggling when it comes to instance specific parameters. For example: I have two abstract factories, one for creating a projectile, and one for creating a crate Now the fa...
A couple options: Rethink your usage An abstract factory is useful if it separates the user of the factory from how the exact type is produced. The abstract factory doesn't have any restrictions on what it produces, just that it is abstract. It can return a non-abstract type, or an abstract type that isn't at the ver...