question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
5,193,115
5,193,197
Thread is showing inconsistence result
I am creating 5 thread here using ThrdFunc. Here each thread update the listBox. I was expecting message in this way. Initially come in this way but after some time Thread1:Adding msg Thread2:Adding msg Thread3:Adding msg But after some time I get message like Thread0:Adding msg Thread18967654:Adding msg Thread18967...
Most likely nThreadNo is allocated on the stack. You're giving each thread a pointer to one of it's elements. Once the function creating the threads returns, the array is no longer valid, but the thread functions are still pointing to it. The memory the threads are holding pointers to will most likely be overwritten, ...
5,193,173
5,193,203
getting cout output to a std::string
I have the following cout statement. I use char arrays because I have to pass to vsnprintf to convert variable argument list and store in Msg. Is there any way we can get cout output to C++ std::string? char Msg[100]; char appname1[100]; char appname2[100]; char appname3[100]; // I have some logic in function which s...
You can replace cout by a stringstream. std::stringstream buffer; buffer << "Text" << std::endl; You can access the string using buffer.str(). To use stringstream you need to use the following libraries: #include <string> #include <iostream> #include <sstream>
5,193,243
5,194,906
Importing c++ dll in c# project
I am importing some c++ dll into a c# project, I am using visual studio 2010. I have succeded to import function that are using built-in type, however I am getting error when I have tried to deal with structure. This is a simple example: c++ code typedef long int TDate; typedef struct _TMDYDate { long month; ...
You have to use the CallingConvention property in the [DllImport] attribute, this is Cdecl since you didn't use __stdcall in the native function declaration. While that's wrong, it is not a great explanation for the AV. You need to debug the C code, the AV suggests it has a pointer bug. Project + Properties, Debug, ...
5,193,575
5,193,777
How can I use a class representing opaque bytes in an std::map?
I have some opaque bytes which I want to use in an std::map, both as keys and values. I created a class, OpaqueBytes, which has two (private) members: _data and _size, to store the bytes. My Cocoa background tells me that I would need to implement a hashing function and equality function on the class to use it in a std...
If you need to use OpaqueBytes as a key you will need a strict comparison. This can be a member function or a non-member function. Could use something like this: // assumed a friend bool operator<( OpaqueBytes const& lhs, OpaqueBytes const& rhs ) { int res = memcmp( lhs._data, rhs._data, std::min(lhs_._size, rhs_._s...
5,193,579
5,193,795
How make FILE* from HANDLE in WinApi?
Is there easy way to create FILE* from WinApi HANDLE which points to one end of pipe? Something like we do in unix: fdopen(fd,<mode>);
You can do this but you have to do it in two steps. First, call _open_osfhandle() to get a C run-time file descriptor from a Win32 HANDLE value, then call _fdopen() to get a FILE* object from the file descriptor.
5,193,583
5,193,607
Initial value of primitive data-types
#include <iostream> class MyClass { public: MyClass() : mFirst() { } int mFirst; int mSecond; }; int main() { MyClass mc; std::cout << "mc.mFirst: " << mc.mFirst << std::endl; std::cout << "mc.mSecond: " << mc.mSecond << std::endl; int a; std::cout << "a: " << a << s...
They're (EDIT: With "They" i refer to mSecond and a which are not explicitly initialized) not initialized. Your stack happens to contain 0's so that's the values you get. 8.5/9: If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the ...
5,193,625
5,194,078
Howto get hardware information in Linux using C++
I need to get specifications of hard disk on both Win and *nix machines. I used <hdreg.h> on Linux like this: static struct hd_driveid hd; int device; if ((device = open("/dev/sda", O_RDONLY | O_NONBLOCK)) < 0) { cerr << "ERROR: Cannot open device /dev/sda \n"; exit(1); } if (!ioctl(devic...
Nearly everything in your list has nothing to do with "specifications of hard disk": The number of partitions depends on reading the partition table, and if you have any extended partitions, the partition tables of those partitions. The OS will usually do this bit for you when the device driver loads. Partition inform...
5,193,867
5,194,023
How to expand/"preprocess" C++ template code
To properly debug complex macros in C++ I usually run the preprocessor on them in order to see exactly what the resulting code looks like. Is there a similar way to "preprocess" template code?
One way (compiler-dependent) is to use dumping after each compiler step. I wrote a small program: template<class T> T square(T n) { return n * n; } int main(void) { square<int>(3); square<float>(3.0); } then: g++ -fdump-rtl-all test.cc This get me a bunch of files. Take a look at (in my case) test.cc.218...
5,193,929
5,194,757
C++ non static callbacks and JNA
I am trying to use a C++ API in Java with JNA. This API uses callbacks to handle sessions events. The only resource I found on how to register callbacks with JNA is this, and it deals with C callbacks, and I don't really know how it can be extended to C++ non-static callbacks. EDIT: I just found this resource, I think ...
From the javadoc Function represents a native method, if you want to call a java method you have to create a Callback for each function pointer. If you only use java callbacks and no native Functions you can just replace Function with Callback. (Depending on the calling convention used you might want to use StdCallLibr...
5,193,951
5,194,391
Semaphore On Multiple Producer Single Consumer Problem
I need to suggestion on this case studies on C++. I have taken Queue where multiple Thread 20 Producer thread is writing on it.there is single Consumer thread which will Read from the queue and process it. I am planning to use critical section and Semaphore to achieve synchronization. AddTail-Adding message in the Queu...
There are many ways to write such a queue. For example, you could use a mutex and a condition variable as in my example at http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html Herb Sutter discusses queues in his articles at Dr Dobb's. See http://www.drdobbs.co...
5,194,034
5,194,067
string not printing properly
I've used the following code for getting a string and using its first character to make another string: char gramG[100],aug[100],start; cout<<"\nEnter the grammar:\n"; cin.getline(gramG,100,'.'); start=gramG[0]; aug[0]=start; aug[1]='\''; aug[2]='-'; aug[3]='>'; aug[4]=start; aug[5]=char(13); cout<<aug; cout<<aug[0]; ...
aug is treated as a 0-terminated character array. 0-terminate it. aug[6] = 0;
5,194,119
5,194,328
writing to a file using stream in C++
I want to some text to output to a file. I heard that it is better to stream the data rather than creating a large string and outputing that. Presently I am creating a large string and outputing to a file. Request to provide an sample code on how to stream a data and write to a file using C++. Thanks!
File writing already uses buffering. If it is not efficient for you, you can actually modify the filebuf, eg increase its size or use a custom one. Avoid doing unnecessary flushes of your buffer, which is done with endl. That is the most "abused" feature of file-writing. The simplest way to create a file-stream for out...
5,194,604
5,202,419
Should I use XPath or just DOM?
I have a bunch of hierarchical data stored in an XML file. I am wrapping that up behind hand-crafted classes using TinyXML. Given an XML fragment that describes a source signature as a set of (frequency, level) pairs a bit like this: <source> <sig><freq>1000</freq><level>100</level><sig> <sig><freq>1200</freq><leve...
In general I tend to prefer XPath based solutions for their concision and versatility but, honestly, in your case, I don't think using XPath will bring a lot to your signature. Here is why: Code elegance Your code is nice and compact and it will not get any better with an XPath expression. Memory footprint Unless your ...
5,194,674
5,194,915
byte array at specyfic addres c++
I want to map some part of process memory as byte array. How to do it? I have byte array: byte AmmoBytes[3] And I want this array to start at address 0xXXXXXXX; How to do it?
byte (& a)[3] = *reinterpret_cast<byte (*)[3]>(0xDEADBEEF);
5,194,826
5,194,851
How to optimize this? Pointer to array
How can I optimize this code? pAmmoOffset is pointer to byte array *pAmmoOffset = 0x89; *(pAmmoOffset + 1) = 0x70; *(pAmmoOffset + 2) = 0x04;
Have you measured this code with a profiler and determined it's a bottleneck? If so, sorry, but there's nothing you can do since the compiler has already made it as efficient as it can be.
5,195,035
5,195,155
boost::multi_index_container compile error due to incomplete type on index typedef'ing
I am using the boost::multi_index_container (as follows) and I am running into a compile error when trying to typedef the index: struct del_t { string del_id; string dev_version; }; struct count_container_t { uint32_t count_1; uint32_t count_2; }; struct mic_t { del_t d; uint32_t p; string c; map<uint...
It looks like you may be missing a needed include, possibly for ordered_unique::nth_index.
5,195,046
5,197,727
Troubles with compiling with FLTK framework
I seem to have problems compiling FLTK programms using anything other than the fltk-config script. I have copied the source from the "Hello world" program in the tutorial. When I run fltk-config --compile hello.cpp it prints out g++ -I/usr/local/include -I/usr/local/include/FL/images -mwindows -DWIN32 -DUSE_OPENGL32 -D...
I bet that the fltk-config script is setting environment variables that you have not configured. Check the FLTK documentation and see the proper environment variables you need to set to compile without the helper script. Edit: Did some research Apparently you're not the only one that has linking problems. I found a sim...
5,195,220
5,195,230
tools to determine memory leak in a c/c++ code
On the unix environment, are there any tools which can easily analyse the code and mention there is a chance of memory leakage in certain sections of the code. HPUX/AIX/Solaris
If you're talking about static analysis then there's cppcheck (among many others) If you're talking about a runtime checker (which will be way more accurate and reliable than static analysis) there's valgrind There's loads of other tools available. Check out the links above for more information Purify will work on AI...
5,195,269
5,195,536
typedef'ing function *signature* (not a pointer to), so that it can be reused?
EDIT: MOTIVATION Suppose I define a Handler class as class Handler { public: class Message { /*...*/ }; typedef int (*Callback)(Message *msg); void registerCallback(int msgclass, Callback f); }; A client can do int f1(Handler::Message *msg) { /* handle message */ } int f2(Handler::Message *msg) { /* handle mess...
First, you did not typedef a signature. A signature is everything that identifies a single function. It contains the namespace/class of the function and so on. What you typedef'ed is the type of a function. Like when you typedef int inttype which typedefs the type of an int, you typedef'ed the type of a function. You...
5,195,489
5,195,609
Problems with QStatusBar->showMessage()
I'm writing a Qt GUI Application, but there's a strange error i can't figure out; Here's the whole code: main.cpp #include "LevelEditor.h" int main(int argc, char* argv[]) { LevelEditor editor(argc, argv); editor.go(); return 0; } LevelEditor.h #ifndef LEVELEDITOR_H #define LEVELEDITOR_H #include <QtGui> ...
You can't connect a signal to a slot with different signature. And you are not even using the proper connect syntax. The SLOT part should be: SLOT(showMessage(const QString &)) It's to tell the meta object system what type(s) of parameters to send to the slot, not what concrete data to send. In your case, you can't co...
5,195,568
5,195,737
formatted output to a C++ ostringstream object
cout << setw(20) << setiosflags(std::ios_base::left) << stamp; // this is char stamp[200] dataype. cout << setw(1) << setiosflags(std::ios_base::left) << " "; cout << setw(10) << setiosflags(std::ios_base::left) << appName1; // this is stl string data dtype cout << setw(1) << setiosflags(std::ios_base::left) << ":"; ...
Streams are polymorphic. They all derive from a common base class. That common base class defines most operations. Derived classes just setup the right stream buffer. So use them polymorphically: void write(std::ostream& os) { os << setw(20) << setiosflags(std::ios_base::left) << stamp; os << setw(1) << setiosfl...
5,195,738
5,195,852
Different behavior of shift operator with -O2 and without
Without -O2 this code prints 84 84, with O2 flag the output is 84 42. The code was compiled using gcc 4.4.3. on 64-bit Linux platform. Why the output for the following code is different? Note that when compiled with -Os the output is 0 42 #include <iostream> using namespace std; int main() { long long n = 42; ...
When you use optimization with gcc, it can use certain assumptions based on the type of expressions to avoid repeating unnecessary reads and to allow retaining variables in memory. Your code has undefined behaviour because you cast a pointer to a long long (which gcc allows as an extenstion) to a pointer to an int and ...
5,195,897
5,196,206
a very simple question about opengl, c++ and objects
I have a very simple openGL program in C++. I have made a Sphere object which simply draws a sphere. I want to have a global variable which gets instantiated in main(), i.e. sphere = Sphere(radius,etc), then gets drawn in draw(), i.e. sphere.draw(), but C++ won't let me. Alternatively, if I have the reference to the sp...
You are dealing with two constructor calls: Sphere sphere; This tries to call the default constructor Sphere::Sphere() which is not declared. sphere = Sphere(radius, etc); This calls the constructor taking two arguments, which I presume is the only one provided. Do it like this: include "sphere.h" Sphere *sphere; dr...
5,195,971
5,196,000
Confused about __cdecl and __stdcall calling convention
__cdecl calling convention says that:caller cleanup stack. __stdcall calling convention says that: callee cleanup stack. So i try to test code below: #include <...> char *callee() { char str[] = "abcd"; return str; } int main() { char *str; str = callee(); printf("%s\n", str); return 0; } A...
"Clean up the stack" actually means "adjust the stack pointer so that it matches the changes done to stack pointer when arguments and return address were pushed onto stack". In your example it would be irrelevant who cleans up the stack - you would get the same undefined behavior, because you try to access a stack-allo...
5,195,990
5,197,740
Using boost::accumulators, how can I reset a rolling window size, does it keep extra history?
I am looking at the boost::accumulator framework, specifically a couple of the rolling_window calculations. #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/rolling_mean.hpp> accumulator_set<int, stats<tag::rolling_mean> > acc(tag:...
The best way to reset a boost accumulator is to assign it to a new one. For example: typedef accumulator_set<int, ... template crazyness tags ... > window_acc; window_acc acc; acc(1); acc(2); ... // reset acc = window_acc(); Actually, swap would be preferred here, but accumulator_set doesn't have a swap member =\
5,196,106
5,196,173
How to do a left join with STL vector and STL algorithms with time complexity better than O(n^2)?
I have 2 vectors, which contain, let's say Person (name, surname, etc) objects. I want to take one of the vectors (let's name it "large") then for each element in this vector find corresponding element in second one ("small") and merge some data from "small" vector element to the "large" vector element. This operation ...
If you sort the small vector, you can then get O(n log n) for the merge portion by scanning the large vector and use binary_search to find elements in the small vector.
5,196,253
5,196,304
Boost smart pointers
When should intrusive_ptr be used instead of shared_ptr ?
When you already have a reference counter stored inside the object you're pointing to.
5,197,086
5,197,134
behaviour of tiny c++ structs
If I define a struct like: struct tiny { long t; }; will it be handled like a long in terms of function arguments and alike, in example would the parameter of: void myfunc(tiny x) { ... } be handled like a long parameter by actually being pushed on the stack? So essentially, is the tiny struct only as large as a ...
The memory consumption of a structure is at least the sum of the memory sizes of constituent variables. However, the compiler may add padding between the variables or at the end of the structure to ensure proper data alignment for a given computer architecture
5,197,136
5,197,152
Why is there a "c" prefix in the C++ version of C libs?
math.h -> cmath stdlib.h -> cstdlib I understand the difference between the ".h" version and the "c-prefix" version, but what was the reason to choose to use the "c" prefix?
EDIT: Okay, we have some people who maybe didn't read the question carefully enough, or made assumptions on what the question meant or how answers were to be interpreted. I'm answering the below question here: but what was the reason to choose to use the "c" prefix? To emphasize that it's originally from the C langu...
5,197,366
5,197,385
Call a function from a prototype in C++
How to call a function from a prototype in c++? Any suggestions?
see example ... http://msdn.microsoft.com/en-us/library/a5s9345t(v=vs.80).aspx
5,197,487
5,197,518
How to initialize class members in singleton pattern?
I've a class following singleton approach, but where do i initialize class members if its constructor is private? class MyClass { MyClass() {}; //constructor is private MyClass(const MyClass&); MyClass& operator=(const MyClass&); public: static MyClass& Instance() ...
You can initialize the class members in the constructor itself as usual, even be it private. The constructor is private to the outside world, not to the static member function Instance(). That means, the line static MyClass singleton in Instance() actually invokes default constructor, and that is valid, as Instance() h...
5,197,683
5,197,908
Retrieve output target name as a string at compilation time in C++
I have a project which compiles in multiple platforms... Windows, Unix, Linux, SCO, name your flavor. I would like to stuff the output target's name into a variable in the project source code (the name of the output program, DLL, SO library or whatever) so I can use it in messages as a generic way to reference the com...
If everything is together under one project, you can use a preprocessor macro. To do this in Visual Studio, open up your project properties and go to Configuration Properties > C/C++ > Preprocessor, and add something like PROGRAM_NAME="\"$(ProjectName)\"" to the Preprocessor Defines field (which corresponds to the /Df...
5,197,732
5,197,758
Should one always check, if the new operator worked?
I have two questions about the new operator: Can the new operator fail to allocate memory? Should one test after every use of new, if there really was an object created?
operator new throws a std::bad_alloc exception on failure, unless you're explicitly using the nothrow version. Therefore, don't check the return value: If you arrive at the next line after the constructor call, you can safely assume that the constructor succeeded. But do wrap the appropriately-scoped branch of your co...
5,197,857
5,198,689
Conversion of JSON logging macros to template functions... parameter names needed in code
I was assigned the task of updating a very old project a while back. The first thing I had to do was to expand the existing code to incorporate a new feature. As part of this I modified existing macros to print JSON representations of incoming messages (over CORBA, into C++ structs). I then incorporated boost program_o...
There are some things that you cannot really do without macros, and for some specific contexts macros are the solution. I would just leave the macros as they are and move on to the next task. Well, I would actually try to improve a bit the macros. It is usually recommended not to use ; inside macros, and with macros t...
5,198,026
5,198,078
C++ wrapping templated function
I have a template class A, and a stream operator function for A that is consequently a template function. I have a class B that inherit from A, specifying a type for the template and adding some stuff specific to B. I am writing a stream operator on B that does something specific to B and then falls back to the rest o...
Change your cast to: operator>>(s, (A<int> &)b); Your original cast creates a temporary which you can only get a const reference to.
5,198,035
5,205,517
FFMPEG and convert swf to image?
I want to use ffmpeg to convert swf to png ,and I can't extract image from some kind of swf like: http://rapidshare.com/files/450953994/Movie1.swf and I use this code in bat file(1.bat) cws2fws Movie1.swf 3.swf ffmpeg -i 3.swf -f image2 -vcodec png tese%d.png Please help me!! I only want to convert swf to image also s...
Mencoder doesn't support the compression [swf @ 0xc230a0]Compressed SWF format not supported. Give a try to http://www.swftools.org/download.html (I have tried myself after compiling swftools but without success). swfextract return $ swfextract test.swf Objects in file test.swf: [-i] 1 Shape: ID(s) 1 [-f] 1 Frame: ID(...
5,198,105
5,198,130
Calling a java method from c++ in Android
I'm trying to get a simple Java method call from C++ while Java calls native method. Here's the Java code: public class MainActivity extends Activity { private static String LIB_NAME = "name"; static { System.loadLibrary(LIB_NAME); } /** Called when the activity is first created. */ @Overr...
If it's an object method, you need to pass the object to CallObjectMethod: jobject result = env->CallObjectMethod(obj, messageMe, jstr); What you were doing was the equivalent of jstr.messageMe(). Since your is a void method, you should call: env->CallVoidMethod(obj, messageMe, jstr); If you want to return a result, y...
5,198,113
5,198,644
Is this an appropriate use of Polymorphism?
Consider this syntactically correct(?) pseudocode: class Event { public: virtual int getID() const = 0; virtual int getSize() = 0; virtual void* getData() = 0; virtual void setData() = 0; //(I cannot define data at this level 'cos I don't know what it is yet) } class SpecialEvent : class Event { pu...
I suggest adding process() as a member function of class event. class Event { int getID() const; void process(); //class stuff } class SpecialEvent : class Event { int getSpecialID() const; void process(); //special version of process() //class stuff } class TheProcessingClass { Event eve...
5,198,148
5,198,852
Visual Studio 2008 does not care about base class existence when compiling templates?
It seems that VS 2008 handles class templates with inheritance a bit differently from the other compilers. The following code compiles without any error on VS 2008 (with default options): template <typename S, typename T> class someclass : public non_existent_class { T operator() (S s) const { return T(s); } }; Qu...
This is most likely a consequence of the fact that visual studio does single phase name lookup when it's supposed to do two phase. The non-dependent name "non_existent_class" should fail in the first phase, which happens at the point of definition whether or not the template is ever instantiated. It's a bug, but it's ...
5,198,210
5,198,312
Windows Message for User Locking Screen
I'm working with old-school windows programming in C++, and I need to capture an event in my WndProc which indicates that the user has logged off or locked the screen. update (thanks David Hefernan) I've searched everywhere, but the only thing I've found is the WM_ENDSESSION message - which does not handle screen lock...
The solution is to register for the WM_WTSSESSION_CHANGE and respond to it in your WndProc. According to the documentation of WM_WTSSESSION_CHANGE, the minimum supported OS is XP. Now, the since Windows 2000 is no longer supported, the documentation often says XP is the minumum when in fact the functionality is availab...
5,198,617
5,198,922
Accessing std::vector containing boost::shared_ptr<CustomObj> -> does at() return a copy of shared pointer?
i am new to boost::shared_ptr using it the first time now. I have a std::vector containing boost::shared_ptr which i "filled" with objects created from a custom class. In Code: std::vector<boost::shared_ptr<Foo>> data; The vector is created inside a function on the stack. I want to access some elements inside my vector...
No. It returns a reference. boost::shared_ptr<Foo> obj = data.at(k); But in this statement you are making a copy by creating obj. boost::shared_ptr<Foo>& obj = data.at(k); ^^^ Now there are no copies made. Edit: What about this line? sendObjToThread1(obj); Are you passing be reference or value? ...
5,198,788
5,198,899
Resolving circular dependency in the State Pattern with C++
I'm trying to implement a State Pattern in C++, but have problems with the circular dependency. I have read other related material here - unfortunately it didn't help me. I don't have a lot of experience with C++, so bear with me. The following code is developed on a Ubuntu 10.10 machine in Eclipse Helios CDT: Concrete...
From the looks of the code you've posted, you'll have classes being redefined. Looking at your Failure.cpp file, you have: #include "Failure.h" #include "SelfTest.h" Which will include both of those files, and each of those files include the SystemState.h file. Since the SystemState.h file is included more than once, ...
5,198,908
5,199,028
deleting a pointer to a class which creates an array
Basically I have a class A which creates an array upon construction. class A { public: A (float height, float width, BYTE* data) { setsize(height,width); mydata = CreateNewBuffer(sizes); setdata(data); } ~A() { } void setsize(float height, float width) { sizes.cx = width; sizes.cy = height;...
I assume that mydata is a member of your class (otherwise, what is mydata in the 7-th line of your code?) So, the dynamic array is a member of your class. If you want to destroy it when the containing object is destroyed, you should do exactly that: order the destruction of your member in the destructor of your class. ...
5,199,257
5,980,242
Problem accessing camera when using Boost thread on OSX
I'm trying to use OpenCV to open a camera. This works fine when I open the camera in the main thread, but when I try to open the camera while in a Boost thread, it fails. I haven't been able to google why this happens. I assume it's somehow related to the permissions of the Boost thread. The following works fine: #incl...
I don't use boost a lot, but don't you need to do something to keep main() from exiting while your thread works? Like maybe... int main() { boost::thread trackerThread( boost::bind(openCamera) ); trackerThread.join(); }
5,199,557
5,199,769
Reading a string and integers
What I want to do is read a line from text file which contains a two word string which has a length <= 20 and two integers, for example it may look something like this: Name Surname 1 14 I know that if I read string, the string will be all characters until the white space, however getline() reads the whole line as a s...
Maybe... #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream file( "/home/facu/text.txt", ios::in ); string part1, part2; int num1, num2; if( !file ) cerr << "Cant open " << endl; while( file >> part1 >> part2 >> num1 >> num2 ) { ...
5,199,630
5,199,695
What does the >?= operator mean?
Looking through this C++ BigInt library and found the BigInt.cpp file. At the top there is a a comment at the top about compatibility: This class was written for the g++ compiler and uses some of the g++ extensions (like "long double" and the ">?=" operator). What does that >?= operator do? I can't find a reference t...
It's a GCC extension that was removed in GCC version 4.2 and later. The equivalent of a >?= b is a = max(a,b); There is also a very similar operator a <?= b which means the same as a = min(a, b);.
5,199,716
5,199,770
Class Not Declared?? (C++)
ISBN.cpp:8: error: 'ISBN' has not been declared ISBN.cpp:8: error: ISO C++ forbids declaration of 'ISBN' with no type ISBN.cpp: In function 'int ISBN()': ISBN.cpp:9: error: 'area' was not declared in this scope ISBN.cpp:10: error: 'publisher' was not declared in this scope ISBN.cpp:11: error: 'title' was ...
This might seem obvious, but have you double-checked that you actually include the header file in ISBN.cpp? Maybe, you have accidentally used the same preprocessor constant as include guard for two headers, causing the file with the declaration of ISBN to be effectively ignored? The snippets you posted look fine to me…...
5,200,064
5,200,130
Class member initialisation differences
With respect to the class definition for complex number, I saw two types of definitions: Definition 1 class Complex { private: double re; double im; public: Complex(float r,float i) {re = r; im = i;} ~Complex() {}; }; Definition 2 class Complex { private: double re; double...
It's called an initializer list. In a class's constructor, you can initialize member variables with this syntax. So in this, it's equivalent to putting the statements re = r; im = i; in the body of the constructor. In the case of POD variables such as int, double, and pointer types, there is no difference between the...
5,200,101
5,200,285
Range-based for loops and ADL
The C++0x standard working draft states (section 6.5.4) the following about the begin() and end() calls that are implicit in a range-based for loop: 'begin' and 'end' are looked up with argument-dependent lookup (3.4.2). For the purposes of this name lookup, namespace std is an associated namespace. The way I...
I first reported that this looked like a gcc bug to me. It now appears that even this part of the for-loop specification is unclear, and an inquiry has been opened on the committee. It still looks like the range-based for-loop rules are going to change very shortly: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2...
5,200,160
5,200,180
Simple inheritance question
Suppose I have the following hierarchy: class A { public: A() private: int aa; } class B: public A { public: B() private: int bb; } class D: public B { public: D() private: int dd; } When I type in the following code in my main: D dobj; std::cout<<"Address of D obje...
Why are aptr and &aobj different? First, you are printing out the wrong pointer: &aptr is "the address of aptr," not "the address of the object to which aptr points." You need to print just aptr to print "the address of the object to which aptr points," which is presumably what you really want to do. aptr is a poin...
5,200,163
5,200,409
Cross Validation in libsvm
I'm using libsvm library in my project and have recently discovered that it provides out-of-the-box cross validation. I'm checking the documentation and it says clearly that I have to call svm-train with -n switch to use CV feature . When I call it with -v switch I cannot get a model file which is needed by svm-predict...
Cause libsvm use cv only for parameter selection. From libsvm FAQ: Q: After doing cross validation, why there is no model file outputted ? Cross validation is used for selecting good parameters. After finding them, you want to re-train the whole data without the -v option. If you are going to use cv for estimating qu...
5,200,357
5,503,946
Trilinos sparse block matrix anomalous memory consumption
I am building an application based on distributed linear algebra using Trilinos, the main issue is that memory consumption is much higher than expected. I have built a simple test case for building an Epetra::VbrMatrix with 1.5 million doubles grouped as 5 millions blocks of 3 doubles, which should be about 115MB. Afte...
answer by Alan Williams form the trilinos-users list, in short VBRmatrix is not suitable for such small blocks, as the storage overhead is bigger than the data themselves: The VbrMatrix storage format definitely incurs some storage overhead, as compared to the simple number of double-precision values being sto...
5,200,384
5,205,624
Read data from Wii-balanceboard
Im trying to get the output from a Wii Fit (balance board). I can find the device via the C++ Bluetooth enumerators but attempts to connect via a windows socket are failing. Im wondering if anyone has had success in such a direction (C++, windows) I'd love to hear how you did it.
The Wii Balance Board is a HID device. To understand communications with the Balance Board, you need to know a little bit about Bluetooth HID. There's good information on WiiBrew about the Wiimote and the Wii Balance Board. I don't think you can use Windows Sockets to connect to a HID device. The Windows Socket Blue...
5,200,418
5,201,028
Destroying threads in Openmp (C++)
Is it possible to destroy the threads created by OpenMP? When the program starts, there is only the one thread. After the parallelized section multiple threads remain since there is a thread pool. Is there any way to destroy this pool after the parallel section is run? I ask because I'm using OpenMP in a dynamic libr...
At this point in time, the OpenMP specification doesn't give the user any ability to control when threads are destroyed. What you are saying is very interesting and hasn't been brought up during any of the OpenMP language committee meetings to discuss the specification. Can you give more information about what you ar...
5,200,572
5,200,585
What does "const" mean (in context) at the end of a function definition?
Possible Duplicate: What is the meaning of a const at end of a member function? If my class definition is as follows: type CLASS::FUNCTION(int, const char*) const What does the last const after the closing bracket mean, and how do I apply it to the function: type CLASS::FUNCTION(int var1, const char* var2) { }
It means that this function does not modify the observable state of an object. In compiler terms, it means that you cannot call a function on a const object (or const reference or const pointer) unless that function is also declared to be const. Also, methods which are declared const are not allowed to call methods whi...
5,200,640
5,200,668
Threading a Shared Model with pointers
I have a vector of pointers to objects created with new. Multiple threads access this vector in a safe manner with various gets/sets. However, a thread may delete one of the objects, in which case another thread's pointer to the object is no longer valid. How can a method know if the pointer is valid? Options 1 and 2 a...
#3 will not work. Deleting a pointer and setting it to NULL doesn't affect other pointers that are pointing to the same object. There is nothing you can do with raw pointers to detect if the object is deleted. #1 is effectively a pointer to a pointer. If you always access it through that pointer and are able to lock...
5,200,663
5,200,682
Virtual Functions: Iterating over a vector<Base Class> that is populated with subclass objects
Short Description: I am iterating over a vector calling a virtual function on every object in the vector in order to execute a sequence of actions. The vector is of the base class as is the iterator. All the objects are children. When the virtual function is called it executes the base class's function. (Really) Lon...
The class vector<Behavior> makes copies of whatever you store inside it, using the copy constructor Behavior::Behavior(const Behavior&);. This destroys the polymorphism. You need to use a pointer or smart pointer in the container instead: vector<Behavior*> m_Behavior; // I will take care of new and delete vector<shar...
5,200,780
5,200,942
Dynamically allocate image in a shared_ptr each frame
I'm trying to use shared_ptr for the first time here, but I'm having some trouble doing this. I want to get am IplImage every frame and allocate to a shared_ptr class member, releasing the last image. It's something like this: class Detector { public: void Detector::updateImage { main_image_.reset(...
I assume that you're seeing this error in a debug build? Which method of allocating memory does cvCreateImage() use? new or malloc()? boost::shared_ptr uses delete to destroy the memory so there might be a chance that your system detects that the data wasn't allocated the "right way", ie by using new. If that's the cas...
5,200,879
5,200,931
Printing prime numbers from 1 through 100
This c++ code prints out the following prime numbers: 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97. But I don't think that's the way my book wants it to be written. It mentions something about square root of a number. So I did try changing my 2nd loop to for (int j=2; j<sqrt(i); j++) but it di...
Three ways: 1. int main () { for (int i=2; i<100; i++) for (int j=2; j*j<=i; j++) { if (i % j == 0) break; else if (j+1 > sqrt(i)) { cout << i << " "; } } return 0; } 2. int main () { for (int i=2; i<100; ...
5,201,036
5,201,075
While creating linked lists how do I assign value for a node?
#include <iostream> using namespace std; int main() { struct list { string name; int age; double height; list *next; }; list *first,*temp,*temp2; for (int i=0 ;i<4;i++) { list *newlist; newlist = new list; cout << " Enter the name : "; ...
I did your homework, spend some attention on the comments: #include <iostream> // you forgot to include string! #include <string> using namespace std; // type definitions usually go outside the main function! struct list { string name; int age; double height; list *next; }; int main() { // mark the beginn...
5,201,038
5,201,068
Using C or C++ to write a Linux shell
I need to write a Linux shell for a school project. We can use C or C++. I am a little more comfortable with C++, and since I'm working with a partner, the object-oriented aspect of it is helpful. However, I suspect that for some reason C is better, and that most if not all Linux shells are written in C and not C++. Wh...
the only difference I'd say is the dependency on libstd-c++ if you end up using STL and stuff. Plain C implementation if done correctly will run on bare minimum system requirements (libc only)
5,201,175
5,201,181
In C# how do I declare a base class as being private?
I know how to do this in C++: class myClass : public baseClass1 private baseClass2 ... How do I do likewise in C#? This is what I have so far in C# public class myClass : baseClass1, baseClass2 How do I specify that baseClass2 is private?
C# does not support multiple inheritance and it does not support private inheritance either.
5,201,401
5,201,479
How can i create COM (in C++) server in VS2010?
recently i want to create some COM Servers for my study project, i can use DLLs but i want to try COM. I'm new to this, i wonder if any one can provide some information about creating COM Server (in VS2010), thank you.
MSDN would be good starting point: Walkthrough: Creating a COM Server Using a Text Editor
5,201,440
5,201,448
Seg Fault (Whats Wrong, strcpy)
In GDB I get: (gdb) backtrace 0 0xb7d91544 in strcpy () from /lib/libc.so.6 1 0x08048982 in ISBN::ISBN(char const*, ISBNPrefix&) () 2 0x08048d4a in main () (gdb) From this code: ISBN::ISBN(const char* str, ISBNPrefix& list) { if(isValid(str)) { isSet = true; sprintf(*isbnStr,"%s",str); ...
isbnStr is an array of strings (or more specifically character pointers), not an array of characters. I think you meant to do char isbnStr[11];
5,201,619
5,201,635
Right Justifying output stream in C++
I'm working in C++. I'm given a 10 digit string (char array) that may or may not have 3 dashes in it (making it up to 13 characters). Is there a built in way with the stream to right justify it? How would I go about printing to the stream right justified? Is there a built in function/way to do this, or do I need to ...
You need to use std::setw in conjunction with std::right. #include <iostream> #include <iomanip> int main(void) { std::cout << std::right << std::setw(13) << "foobar" << std::endl; return 0; }
5,201,696
5,261,496
Gauss Elimination for NxM matrix
/* Program to demonstrate gaussian <strong class="highlight">elimination</strong> on a set of linear simultaneous equations */ #include <iostream> #include <cmath> #include <vector> using namespace std; const double eps = 1.e-15; /*Preliminary pivoting strategy Pivoting function */ double pivot(vector<vector...
(optional) Understand this. Do some examples on paper. Don't write code for Gaussian elimination yourself. Without some care, the naive gauss pivoting is unstable. You have to scale the lines and take care of pivoting with the greatest element, a starting point is there. Note that this advice holds for most linear alg...
5,201,818
5,201,831
output void function to txt
I am only in my second quarter of c++ so please keep answers simple.... I have a pretty messy program with linklist, class, and file i/o I am pretty much done with the program but I cant get it to output to a .txt It might have been my bad coding layout, since outputting slipped my mind when I wrote this. the function ...
If the function does its own file I/O, it's going to be tough (that's why the "separation of concerns" software design guideline exists, it's apparently being violated here). Overloading operator << will not help, there's no return value from the function for such an operator to put anywhere. If you can modify the fun...
5,201,824
5,201,840
what is the difference between user-defined conversion and user-defined operator?
In the context of operator overloading, what is the difference between user-defined conversion and user-defined operator?
"User-defined conversions allow you to specify object conversions with constructors or with conversion functions. User-defined conversions are implicitly used in addition to standard conversions for conversion of initializers, functions arguments, function return values, expression operands, expressions controlling ite...
5,201,844
5,201,951
Computing memory usage?
Let us consider the following factorial example : #include <iostream.h> int factorial(int); void main(void) { int number; cout << "Please enter a positive integer: "; cin >> number; if (number < 0) cout << "That is not a positive integer.\n"; else cout << number << " factorial is:...
For my second answer (prompted by the comments to my first answer), you could use a function that computes how much of the stack has been touched. Here's one that hopefully doesn't make too many assumptions about the nature of the stack on a given architecture. It assumes a descending stack, which is a fairly safe bet ...
5,202,142
5,202,547
Static variable initialization over a library
I am working on a factory that will have types added to them, however, if the class is not explicitly instiated in the .exe that is exectured (compile-time), then the type is not added to the factory. This is due to the fact that the static call is some how not being made. Does anyone have any suggestions on how to fix...
As a general rule of thumb, an application do not include static or global variables from a library unless they are implicitly or explicitly used by the application. There are hundred different ways this can be refactored. One method could be to place the static variable inside function, and make sure the function is c...
5,202,175
5,202,200
Will using shared library in place of static library effect memory usage?
I am linking against 10 static library. My binary file size is getting reduced when I am using dynamic library. As I know using dynamic library will not reduce memory usage. But my senior told me that using shared library will also reduce memory usage ? (when multiple process are running for the same executable code...
In your example, dynamic libraries won't save you much. When you fork your process on a modern OS all the pages are marked copy on write rather than actually copied. So your static library is already shared between your 10 copies of your process. However, where you can save is when the dynamic library is shared betwee...
5,202,974
5,203,018
What is the difference between boost::bind and boost::lambda::bind?
I can see that there are two different bind libraries for Boost, one "standalone", that can be used by including boost/bind.hpp, and another by including boost/lambda/bind.hpp. What's the difference between these two?
Have a look at the explanation here: http://boost.org/doc/libs/1_46_0/doc/html/lambda/s08.html#id2143701 They have overlapping functionality but with semantic differences, they can't be used interleaved.
5,203,011
5,203,033
#undef main gives no result
I'm working with MVisualC++ 2010 and when I try to undefine the "main", there's no result and the console launches as usual. I was expecting some missing entry point error or something. Why is that? #undef main int main() { }
main isn't a #define in the first place. Your #undef changes nothing at all. #define foo bar tells the preprocessor "replace all occurences of foo with bar". #undef foo tells the preprocessor "foo has no special meaning anymore, leave it as is" If you want a linker error, rename main to e.g. main2, or do e.g. this: vo...
5,203,519
5,203,556
How to find function that never called
Possible Duplicate: Find never-called functions Hello I know that similar question was already asked Find never-called functions but maybe someone have some other solutions?That don't require use of external programs. I am working in c++
No, there isn't a way of doing this built into Visual Studio. You will need a third-party program. Asking again isn't going to change anything. The duplicate question that you link to was asked and answered well after Visual Studio 2008 was available. Someone would have suggested something if it existed. It's difficult...
5,203,704
5,203,717
Expecting input from std::cin (Unix C++)
Possible Duplicate: Detect if stdin is a terminal or pipe in C/C++/Qt? I'm writing a command line application that expects data as either a command line argument, or from cin. Is there a way to check if the user piped some data in the application ($ ./myapp < test.txt), and only display a prompt for keyboard input i...
isatty(STDIN_FILENO) will return whether standard input is a terminal (tty), i.e. interactive.
5,203,719
5,203,732
What is the way to separate command line output (processing from user interaction) on Unix?
I'm writing a console application in which user interaction might be necessary (prompt for keyboard input, cli arguments etc.), but I want to keep it separate from the result of the processing (which goes to cout, in a way that it can be piped to some other application). How can I achieve this, if I can't just send all...
When your stdout is piped somewhere else, the only way to show something on the terminal (apart from maybe things like curses and dialog) is stderr.
5,203,737
5,203,756
C++, how to control program flow with keyboard input
I have a main routine that loops infinitely. By changing bool variables using keyboard input, I want to be able to control whether certain if{} statements within that loop are getting called. I found this thread: C non-blocking keyboard input, but it seems excessively laborious and complicated for seemingly basic func...
You'll have to use the OS/Firmware/Framework/environment API to get input events, or use a library that do this for you. Anyway, there is no built-in way of doing this in C++. I often use OIS in games. It's cross-platform and easy to use. Not sure it's useful for other cases than games but it does the job for you.
5,203,917
5,203,969
Identifying the next character in a string is capital or not
I am writing a C++ program. I have an array of char array trans[20][100]. Actually each string of trans is a transition of a grammar(Programming language translators). I want to check for each string in trans whether there is a Non-terminal after a '.' i.e. i want to check if in the strings there is a '.' followed by a...
If you operate on ASCII char, then you could test if the int value of the char is between 65 and 90. See the ASCII table.
5,204,004
5,204,016
Member template function. Why doesn't this compile?
I whant to iterate in a member function over a list. In this code sample I am getting compiler error in for-line: Expected ; before it, it not declared, end not declared. Why? The function is even not used in code! template <class T> bool Settings::saveSimpleList( QString k, const T & l ){ //... for ( T::Co...
Do this: for (typename T::ConstIterator it = l.constBegin(), end =l.constEnd(); it != end; ++it ) { QString itemValue = QVariant( *it ).toString(); //... } When writing T::ConstIterator, the compiler can either interpret that as "the static member ConstIterator of type T" or as "the type defined as ConstIterat...
5,204,287
5,204,296
vector initialization in constructor
Is it necessary to initialize ; - vector<string> - vector<string*> in constructor ?
No. Default initialization will be fine. For vector<string *> you will however need a destructor, a copy constructor and an assignment operator in order to properly delete/copy the string * elements in your vector<string *> member variable.
5,204,424
5,205,029
searching vector [ error included version & orginal code & Makefile ]
It gives so many error, why ? How can I fix it ? My real code ; int SearchUserName ( string searched, vector<User *> list ) { vector<User *> :: iterator it ; for ( it = list.begin() ; it < list.end ( ) ; ++it ) { const string tmp = (*it) -> getUsername() ; if ( tmp == searched ) return 1 ; } ...
You're only compiling one file. something like main: foo.o bar.o $(CXX) -o $@ foo.o bar.o listing all your object files
5,204,578
5,204,594
Is it possible to implement events in C++?
I wanted to implement a C# event in C++ just to see if I could do it. I got stuck, I know the bottom is wrong but what I realize my biggest problem is... How do I overload the () operator to be whatever is in T, in this case int func(float)? I can't? Can I? Can I implement a good alternative? #include <deque> using nam...
If you can use Boost, consider using Boost.Signals2, which provides signals-slots/events/observers functionality. It's straightforward and easy to use and is quite flexible. Boost.Signals2 also allows you to register arbitrary callable objects (like functors or bound member functions), so it's more flexible, and it h...
5,204,687
5,205,209
CUDA & VS2010 problem
I have scoured the internets looking for an answer to this one, but couldn't find any. I've installed the CUDA 3.2 SDK (and, just now, CUDA 4.0 RC) and everything seems to work fine after long hours of fooling around with include directories, NSight, and all the rest. Well, except this one thing: it keeps highlighting ...
You cannot do this... #include "kernel.cu" Now you're asking the Visual Studio CPP compiler to compile the .CU file as though it was a header. You need to have a header file that declares doStuff() and include the header not the definition. The following might be helpful. http://www.ademiller.com/blogs/tech/2010/12/...
5,204,717
5,204,978
Hooking Win32 windows creation/resize/querying sizes
I'm trying to "stretch" an existing application. The goal is to make an existing application become larger without changing the code of that application. A cosntraint is that the stretched application will not "notice" it, so if the application query a created window size it'll see the original size and not the resized...
Unfortunately, queries for window size aren't handled by messages -- they are direct API calls such as GetWindowRect -- so they can't be intercepted by standard Windows hooks. You might want to look into the Detours API, which allows you to hook arbitrary Win32 functions. (You can find a tutorial on Detours here)
5,204,744
5,208,248
gdb local variables in a function
Is there a way in gdb to check the local variables of a member function and also the class private members. Sometimes, I need to know which variables are local to the function and which ones are class variables. Best, Umut
info local will print the values of all local variables (see info args if you also want function parameters) print *this will show the member variables.
5,204,758
5,204,850
Why does it work? SFINAE
template<class T, class U> struct is_convertible { typedef char yes; typedef struct {char _[2];}no; static yes test(U); static no test(...); enum {value = (sizeof(test(0)) == sizeof(yes)) ? 1 : 0}; //THE PART I'M INTERESTED IN IS (test(0)). Why 0 (zero) works here? }; Please see comment in th...
Code "works" when it meets its specification. This code does not meet the specification implied by the function name, and no clearer specification has been given. Currently, the code yields is_convertible<T, U>::value true when U is copyable and an implicit conversion exists in the context of struct is_convertible from...
5,204,818
5,204,931
simple openGL program fails to link in ubuntu
i'm trying to get into opengl programming, but fail to compile my first very very simple program. the linking process fails every time. i found this answer on stackoverflow, and have had all packages installed and told g++ which libraries to link against. here's my sample program: #include <GL/glut.h> #include <GL/gl.h...
might be order - either reorder libs, or put them after opengl.cpp
5,204,862
5,204,926
C++ MySQL Sql syntax error while syntax is correct
my C++ program reads a file with sql query and tries to execute it. When I execute the query using phpmyadmin, it works, but when executed in my program, it ends up with the following error: Code: ifstream create_file ("create.sql"); if (create_file.is_open()) { char * create; int length; ...
You can't put multiple statements in a single mysql_query call. You need to execute them one at a time, by default at least. See the mysql_query docs.
5,205,012
5,208,127
Debugging attached process with gdb - how to escape from a loop
I am debugging code that looks like this: while (true){ // do something ... size_t i = foo(); // <- bp set here if (flag_set) break; } // More code follows here ... I want to break at the foo() function call, invoke it a few times and then jump out of the while loop completely (lets assume that we are guara...
You want the advance command, which takes the same arguments as the break command. Using your code as an example (but with line numbers added): 10 while (true){ 11 // do something ... 12 size_t i = foo(); // <- bp set here 13 if (flag_set) break; 14 } 15 16 // More code follows here ... 17 someFunction(); Say...
5,205,105
5,205,121
What does C++ using mean inside a class?
What does it mean to have a using inside a class definition? class myClass { public: [...] using anotherClass::method; };
That declaration unhides a base class member. This is most often used to allow overloads of a member function. Example: class Base { public: void method() const; }; class Derived : public Base { public: void method(int n) const; // Without the using, you would get compile errors on d.method(); using Base...
5,205,139
5,205,409
Problem inheriting BST into black-red tree
Since black red tree is a binary search tree I have decided to use inheritance for implementation. Here is how in short node inheritance looks in my code: struct BST_node { // public interface here int key; BST_node* left; BST_node* right; BST_node* parent; }; struct BRT_node : BST_node { // public ...
What's wrong with putting all the data members in BRT_node? struct BRT_node { int key; BRT_node* next; BRT_node* prev; BRT_node* parent; NodeColour colour; }; This way, you get to keep the "nice syntax" of node->left = node->parent;. The problem with using inheritance here is because the red-black ...
5,205,207
5,205,250
How to work with large numbers when writing and reading a file?
I have written a codes to write my data from one input file to another output file, I used to read all lines of my input file while (!inputfile.eof()) but in my output file, the last line is missing. So I would like to know, how to prevent this error? My second question is: for writing data into file, I used Outputf...
Okay, based on comments, the intent here has (at least I hope) become reasonably clear: to convert pairs of numbers in text format to binary format, and be able to verify that the converted numbers accurately represent the originals. There are a number of ways to do that, but the first thing to keep in mind is that no ...
5,205,216
5,205,293
Const variables in c++
AFAIK we cannot change a value of a constant variable in C. But i faced this interview question as below: In C++, we have procedure to change the value of a constant variable. Could anybody tell me how could we do it?
Under the circumstances, I think I'd have explained the situation: attempting to change the value of a variable that's const gives undefined behavior. What he's probably asking about is how to change a variable that isn't itself const, but to which you've received a pointer or reference to const. In this case, when you...
5,205,252
5,205,586
Reading unicode text files in Visual C++
I'm trying to read a simple unicode (UTF-16) text file with just some numbers in Visual C. This seemed like a trivial task, but I can't get it to read the file in correct encoding. My file looks like this: 1337 42 23 Since it's unicode, it also has the 0xFF 0xFE BOM mark at the beginning. I've tried wifstream() and fw...
The Microsoft CRT supports BOM auto-detection since VS2005. You enable it by using the "ccs" attribute in the mode argument. Like this: FILE * f = _wfopen(L"c:\\temp\\test.txt", L"rt, ccs=UNICODE"); It falls back to ansi if the file doesn't have a BOM. You can use "UTF-8" or "UTF-16LE" for troublemakers like that. ...
5,205,277
5,205,406
about before function in typeinfo
I am reading modern C++ design. Following is the text snippet taken from typeinfo description. The before member function introduces an ordering relationship for type_info objects. Using type_info::before, you can perform indexing on type_info objects. If you want to sort type_info objects, again you must actu...
"Indexing" here means using it as the key in an ordered container, such as std::set or std::map. These require a comparison functor to order the keys. You'll also need to use pointers to type_info, rather than the objects themselves, since they are not copyable. It could be achieved like this: struct type_info_before {...
5,205,491
5,205,571
What's the difference between "STL" and "C++ Standard Library"?
Someone brought this article to my attention that claims (I'm paraphrasing) the STL term is misused to refer to the entire C++ Standard Library instead of the parts that were taken from SGI STL. (...) it refers to the "STL", despite the fact that very few people still use the STL (which was designed at SGI). Parts of ...
The "STL" was written by Alexander Stepanov in the days long before C++ was standardised. C++ existed through the 80s, but what we now call "C++" is the language standardised in ISO/IEC 14882:2014 (and earlier versions, such as ISO/IEC 14882:2011). The STL was already widely used as a library for C++, giving programmer...
5,205,567
5,205,653
How to document a function object with doxygen?
How should I document a function object (AKA functor) with doxygen? It feels misleading to just document it as a regular class. I find it much better to think of a function object as a function with a closure than a callable class. Is there a way to document a function object that fits with my preferences? class Adde...
Give it class documentation, put the word functor in the first sentence (preferably as the first word) and skip the operator() documentation if the meaning is obvious. Mind you: the meaning is often not obvious if operator() is overloaded.
5,205,593
5,205,603
static struct in C/C++
static struct K { int x; }; Is this valid in C and C++?
Valid in C. Ill-formed in C++ In C++, specifiers extern/static can only be applied to names of objects or functions Check out C.1.5 Clause 7: declarations (7.1.1) ISO C++03
5,206,080
5,206,652
C++ - Overload templated class method with a partial specilization of that method
There are a few questions already similar to this already on stack overflow, but nothing that seemd to directly answer the question I have. I do apologise if I am reposting. I'd like to overload a few methods of a templated class (with 2 template parameters) with a partial template specialisation of those methods. I ha...
The particular problem you're sketching is easy: template< class T > inline T foo( T const& v ) { return v; } template<> float foo( float const& v ) { return v+0.5; } Then call foo from your Test::Set implementation. If you want the full generality, then similarly use a helper class with static helper member function...
5,206,297
5,206,428
documentation generator for vc++ 2010
I am looking for a plugin(s) for VS2010 that will allow me to: Document my code easily. Browse that documentation. Export it into some format or other. I was looking for a sort of front-end for doxygen + a documentation browser, but found nothing. Any other such tool will be great, it doesn't have to be doxygen, alth...
Why don't you just use the official Doxygen GUI? The documentation is usually generated within seconds and it can generate very nice HTML files.