question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,095,705
1,095,752
Using Boost::ref correctly..?
How can I get this to compile? The error is when I start using boost::ref(). I thought boost::ref is used to pass reference to C++ algorithm classes? list<Object> lst; lst.push_back(Object(1,2.0f)); lst.push_back(Object(3,4.3f)); struct between_1_and_10 { int d; void operator() (Object& value) { value.a += 5; value.b -= 3.3f; cout << d << endl; d += value.a; } }; between_1_and_10 val; val.d = 4; for_each(lst.begin(), lst.end(), boost::ref(val)); // Problem is here printf("rg"); EDIT Here's the compiler error as people suggested: 1>c:\program files (x86)\microsoft visual studio 9.0\vc\include\algorithm(29) : error C2064: term does not evaluate to a function taking 1 arguments 1> c:\users\swangrun\desktop\minescout work\feat-000-gettargetimages\minescouttest\maintest.cpp(102) : see reference to function template instantiation '_Fn1 std::for_each<std::list<_Ty>::_Iterator<_Secure_validation>,boost::reference_wrapper<T>>(_InIt,_InIt,_Fn1)' being compiled 1> with 1> [ 1> _Fn1=boost::reference_wrapper<main::between_1_and_10>, 1> _Ty=Object, 1> _Secure_validation=true, 1> T=main::between_1_and_10, 1> _InIt=std::list<Object>::_Iterator<true> 1> ]
This what you really want: for_each(lst.begin(), lst.end(), boost::bind<void>(boost::ref(val),_1 ) ); EDIT: Some explanation upon the OP's request. Recall that for_each() takes a function, but you were merely passing it a reference to your struct (yes, the struct has it's operator() overloaded but you were not passing that). bind() basically "exposes" the function inside your struct. EDIT2: Explanation of the "_1" can be found in the comments below.
1,096,072
1,096,080
Convert struct to unsigned char *
How can I convert the following struct to unsigned char*? typedef struct { unsigned char uc1; unsigned char uc2; unsigned char uc3; unsigned char uc5; unsigned char uc6; } uchar_t; uchar_t *uc_ptr = new uchar; unsigned char * uc_ptr2 = static_cast<unsigned char*>(*uc_ptr); // invalid static cast at the previous line
You can't use a static_cast here since there is no relationship between the types. You would have to use reinterpret_cast. Basically, a static_cast should be used in most cases, whereas reinterpret_cast should probably make you question why you are doing it this way. Here is a time where you would use static_cast: class Base { }; class Derived : Base { }; Base* foo = new Derived; Derived* dfoo = static_cast<Derived*>( foo ); Whereas here is where you would probably need a reinterpret_cast: void SetWindowText( WPARAM wParam, LPARAM lParam ) { LPCTSTR strText = reinterpret_cast<LPCTSTR>( lParam ); }
1,096,207
1,096,224
C++: Replacing part of string using iterators is not working
I am writing a simple program, which is trying to find next palindrome number after given number. As for now, I am stuck at this point: string::iterator iter; // iterators for the string string::iterator riter; //testcases is a vector<string> with strings representing numbers. for (unsigned int i = 0; i < testcases.size() ; ++i) { iter = testcases[i].begin(); riter = testcases[i].end(); while ( !isPalin(testcases[i]) ) { //isPalin(string) is a function //which is checking if given string //is a palindrome //if n-th digit from the end is different from the //n-th digit, then I want to replace latter one, so they will //be the same. if ( *iter != *riter ) { testcases[i].replace(riter, riter, *iter); } ++iter; // advancing forward iterator; --riter; // advancing backward iterator; } cout << testcases[i] << " -> ok\n"; } When I am compiling this one using Microsoft Visual Studio 2008, I am getting this error: Compiling... main.cpp .\main.cpp(53) : error C2664: 'std::basic_string<_Elem,_Traits,_Ax> &std::basic_string<_Elem,_Traits,_Ax>::replace(unsigned int,unsigned int,const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 1 from 'std::_String_iterator<_Elem,_Traits,_Alloc>' to 'unsigned int' with [ _Elem=char, _Traits=std::char_traits, _Ax=std::allocator ] and [ _Elem=char, _Traits=std::char_traits, _Alloc=std::allocator ] No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called Am I doing something stupid or am I missing something? I would be grateful for any help / suggestion.
About the code you have: Why don't you just assign the values at the end of the two iterators? if ( *iter != *riter ) { *riter = *iter; } As Oli pointed out, there are other problems in the code, the first of which is the fact that you are setting riter to be string.end(), witch is a non-dereference-able iterator. end() iterators are always one past the end, and thus the use above will try to write beyond the assigned memory. Maybe you should try using .rbegin() instead. It will provide a reverse iterator pointing to the last element that moves towards the beginning of the string as you increment it. On the algorithm: If your intention is finding the next number that is a palindrome, I am not sure that the algorithm you have implemented is correct. As an example, if the input number is 123456 the algorithm will detect that it is not a palindrome and will convert to 12345_1_ which is smaller than the original number.
1,096,291
1,096,358
How to format my own objects when using STL streams?
I want to output my own object to a STL stream but with customized formatting. I came up with something like this but since I never used locale and imbue before I have no idea if this makes sense and how to implement MyFacet and operator<<. So my questions are: does this make sense and how to implement MyFacet and operator<< ? The following is a simplified example which shows you what I want to do. struct MyObject { int i; std::string s; }; std::ostream &operator<<(std::ostream &os, const MyObject &obj) { if (????) { os << obj.i; } else { os << obj.s; } } MyObject o; o.i = 1; o.s = "hello"; std::cout.imbue(locale("", new MyFacet(MyFacet::UseInt))); std::cout << o << std::endl; // prints "1" std::cout.imbue(locale("", new MyFacet(MyFacet::UseString))); std::cout << o << std::endl; // prints "hello"
Well, a locale is generally used to allow different output/input formatting of the same object based on the local (the specified locale in fact) formatting which is present. For a good article on this see: http://www.cantrip.org/locale.html. Now maybe its because your example above is quite simplified, but to me it looks like you are trying to come up with a clever way to switch between printing one part of an object or another. If that is the case it might be simpler do just overload the stream operator for each type and use the if switch externally. Anyway, I'm not going to pretend that I'm an expert in facets and locales but have a look at that article, its pretty thorough and will give you a better explanation than I will!
1,096,341
1,096,349
Function pointers casting in C++
I have a void pointer returned by dlsym(), I want to call the function pointed by the void pointer. So I do a type conversion by casting: void *gptr = dlsym(some symbol..) ; typedef void (*fptr)(); fptr my_fptr = static_cast<fptr>(gptr) ; I have also tried reinterpret_cast but no luck, although the C cast operator seems to work..
Converting a void* to a function pointer directly is not allowed (should not compile using any of the casts) in C++98/03. It is conditionally supported in C++0x (an implementation may choose to define the behavior and if it does define it, then it must do what the standard says it should do. A void*, as defined by the C++98/03 standard, was meant to point to objects and not to contain function pointers or member pointers. Knowing that what you are doing is heavily implementation dependent, here is one option that should compile and work (assuming 32 bit pointers, use long long for 64 bit) on most platforms, even though it is clearly undefined behavior according to the standard: void *gptr = dlsym(some symbol..) ; typedef void (*fptr)(); fptr my_fptr = reinterpret_cast<fptr>(reinterpret_cast<long>(gptr)) ; And here is another option that should compile and work, but carries the same caveats with it as the above: fptr my_ptr = 0; reinterpret_cast<void*&>(my_ptr) = gptr; Or, in Slow motion... // get the address which is an object pointer void (**object_ptr)() = &my_ptr; // convert it to void** which is also an object pointer void ** ppv = reinterpret_cast<void**>(object_ptr); // assign the address in the memory cell named by 'gptr' // to the memory cell that is named by 'my_ptr' which is // the same memory cell that is pointed to // by the memory cell that is named by 'ppv' *ppv = gptr; It essentially exploits the fact that the address of the function pointer is an object pointer (void (**object_ptr)()) - so we can use reinterpret_cast to convert it to any other object pointer: such as void**. We can then follow the address back (by dereferencing the void**) to the actual function pointer and store the value of the gptr there. yuk - by no means well-defined code - but it should do what you expect it to do on most implementations.
1,096,482
2,147,201
How to access Firefox's DOM (or HTML content) from outside firefox
I have a question: My program will search FireFox windows opened by user. When a user open Firefox and enter any site, I want to search for a keyword in that page's HTML content. How can I access Firefox's Active Tab's DOM (or HTML content) from outside firefox using my C++ program. Is it possible? If so, can you give me some idea or links? If it is not possible, how can I copy text to clipboard within Firefox without installing / setting up anything? Best regards, Nuri Akman
There is no built-in way to access the DOM of a web page inside Firefox from an external program. You can write an extension that implements some sort of IPC (using sockets or whatever) and communicate with that, but not built-in to Firefox.
1,096,615
1,096,648
Automatic Java to C++ conversion
Has anyone tried automatic Java to C++ conversion for speed improvements? Is it a maintenance nightmare in the long run? Just read that is used to generate the HTML5 parsing engine in Gecko http://ejohn.org/blog/html-5-parsing/
In general, automatic conversions from one language to another will not be an improvement. Different languages have different idioms that affect performance. The simplest example is with loops and variable creation. In a Java GC world, creating objects with new is almost free, and they dive into oblivion just as easily. In C++ memory allocation is (generally speaking) expensive: // Sample java code for ( int i = 0; i < 10000000; ++i ) { String str = new String( "hi" ); // new is free, GC is almost free for young objects } Direct conversion to C++ will result in bad performance (use of TR1 shared_ptr as memory handler instead of GC): for ( int i = 0; i < 10000000; ++i ) { std::shared_ptr< std::string > str( new std::string( "hi" ) ); } The equivalent loop written in C++ would be: for ( int i = 0; i < 10000000; ++i ) { std::string str( "hi" ); } Direct translation from a language to another usually ends with the worst of both worlds and harder to maintain code.
1,096,700
1,096,743
Instantiate class from name?
imagine I have a bunch of C++ related classes (all extending the same base class and providing the same constructor) that I declared in a common header file (which I include), and their implementations in some other files (which I compile and link statically as part of the build of my program). I would like to be able to instantiate one of them passing the name, which is a parameter that has to be passed to my program (either as command line or as a compilation macro). The only possible solution I see is to use a macro: #ifndef CLASS_NAME #define CLASS_NAME MyDefaultClassToUse #endif BaseClass* o = new CLASS_NAME(param1, param2, ..); Is it the only valuable approach?
This is a problem which is commonly solved using the Registry Pattern: This is the situation that the Registry Pattern describes: Objects need to contact another object, knowing only the object’s name or the name of the service it provides, but not how to contact it. Provide a service that takes the name of an object, service or role and returns a remote proxy that encapsulates the knowledge of how to contact the named object. It’s the same basic publish/find model that forms the basis of a Service Oriented Architecture (SOA) and for the services layer in OSGi. You implement a registry normally using a singleton object, the singleton object is informed at compile time or at startup time the names of the objects, and the way to construct them. Then you can use it to create the object on demand. For example: template<class T> class Registry { typedef boost::function0<T *> Creator; typedef std::map<std::string, Creator> Creators; Creators _creators; public: void register(const std::string &className, const Creator &creator); T *create(const std::string &className); } You register the names of the objects and the creation functions like so: Registry<I> registry; registry.register("MyClass", &MyClass::Creator); std::auto_ptr<T> myT(registry.create("MyClass")); We might then simplify this with clever macros to enable it to be done at compile time. ATL uses the Registry Pattern for CoClasses which can be created at runtime by name - the registration is as simple as using something like the following code: OBJECT_ENTRY_AUTO(someClassID, SomeClassName); This macro is placed in your header file somewhere, magic causes it to be registered with the singleton at the time the COM server is started.
1,096,931
1,097,215
Overloaded member function pointer to template
I'm trying to store member function pointers by templates like this: (This is a simplified version of my real code) template<class Arg1> void connect(void (T::*f)(Arg1)) { //Do some stuff } template<class Arg1> void connect(void (T::*f)()) { //Do some stuff } class GApp { public: void foo() {} void foo(double d) {} }; Then I want to do like the following for every overloaded methods in GApp: connect(&GApp::foo); Calling this for foo() is ok, but how can I call this for foo(double d)? Why isn't the following working? connect((&GApp::foo)(double)); It will give me syntax error : 'double' should be preceded by ')' I don't understand the syntax which must be used here. This may be a stupid qustion, but can any one help me on this?
Your code as written doesn't compile. I've make some "assumptions" about what you wanted to do, and have changed the code. To summarise, you can call the correct function by explicitly specifying the function parameter type: connect<double> (&GApp::foo); If the connect methods are members of a class template, then it is only necessary to specify the class type once: template <typename T> class A { public: template<class Arg1> void connect(void (T::*f)(Arg1)) { //Do some stuff } void connect(void (T::*f)()) { //Do some stuff } }; class GApp { public: void foo() {} void foo(double d) {} }; int main () { A<GApp> a; a.connect (&GApp::foo); // foo () a.connect<double> (&GApp::foo); // foo (double) } UPDATE: In response to the new code sample, all the information is being passed in. The "rare" case is the 'signal_void' case as this is where the signal has a template argument, but the member function doesn't. Therefore we special case that example and then we're done. The following now compiles: template <class Arg = void> class signal {}; signal<double> signal_double; signal<> signal_void; // Arg1 is deduced from signal<Arg1> and then we use it in the declaration // of the pointer to member function template<class T, class Arg1> void connect ( signal<Arg1>& sig, T& obj, void (T::*f)(Arg1) ) {} // Add special case for 'void' without any arguments template<class T> void connect (signal<> & sig, T& obj, void (T::*f)()) {} void bar () { GApp myGApp; //Connecting foo() connect(signal_void, myGApp, &GApp::foo); // Matches second overload //Connecting foo(double) connect(signal_double, myGApp, &GApp::foo); // Matches first overload }
1,097,062
1,097,225
How does visual studio know which cpp files to rebuild when an include file is changed?
In some of my VS 2005 projects, when I change an include file some of the cpp files are not rebuilt, even though they have a simple #include line in them. Is this a known bug, or something strange about the projects? Is there any information about how VS works out the dependencies and can I view the files for that? btw I did try some googling but couldn't find anything about this. I probably need the right search term...
I've experienced this problem from time to time, and with other IDEs too, not just VS. It seems thatv their internal dependency tree sometimes gets out of whack with reality. In these cases, I've found deleting pre-compiled headers (this is important) and doing a complete rebuild always solves the problem. Luckily, it doesn't happen often.
1,097,126
1,106,420
Implement user activity logger in old application?
How to go about implementing a user activity logger in MFC application.To get to know what are all the features are used most in an existing application.
You can override the windows procedure of your application window: class CMyMainWindow { void LogUsageData(UINT message); virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { LogData(message); return CWnd::WindowProc(message, wParam, lParam); // route message to message map } } Note that the task is not so trivial: LogUsageData should discard most messages, focusing only on the ones defined in the message map. However, this should be a good place to start.
1,097,185
1,097,194
What is the simplest way to write a timer in C/C++?
What is the simplest way to write a timer in C/C++? Hi, What is the simplest way to write a timer, say in C/C++? Previously I used a for loop and a do-while loop. I used the for loop as a counter and the do-while loop as a comparison for "end of time". The program worked as I wanted it to, but consumed too much system resources. I'm looking for the simplest way to write a timer. Thank you! EDIT: The program works on a set of servers both Linux and Windows, so it's a multiplatform environment. I dont want to use the unsleep or sleep function as I'm trying to write everything from scratch. The nature of the program: The program counts power time and battery time on systems. EDIT2: OK, it seems that this caused some confusion so I'm going to try to explain what I have done so far. I've created a program that runs in the background and powers off the system if it's idle for a certain amount of time, it also checks for the battery life on a specific system and goes to stand by mode if the system has been running on battery for a while. I input the time manually so I need a timer. I want to write it from scratch as it's a part of a personal project I've been working on.
Your best bet is to use an operating system primitive that suspends the program for a given amount of time (like Sleep() in Windows). The environment where the program will run will most likely have some mechanism for doing this or similar thing. That's the only way to avoid polling and consuming CPU time.
1,097,236
1,097,413
pthread_cond_timedwait linking error with clock_gettime on Solaris 10
I have a bit of code which used pthread_cond_wait which looks like this: struct timespec ts; clock_getttime(CLOCK_REALTIME, &timS); ts.tv_sec += delay; pthread_mutex_lock(&a_mutex); pthread_cond_timedwait(&thread_cond, &a_mutex,&timS); pthread_mutex_unlock(&a_mutex); But I get a linker error on compilation, undefined symbol clock_gettime ... first referenced in (the file with that code) This is the only linker error I get; if I comment out this block of code it compiles, so the pthread library is loading. I read somewhere that I need the -lc flag set, which I have done but it appears that I need to set something else too. Does anybody know what? This is on Solaris 10, using Sun's 5.8 compiler.
The -lc answer is wrong. You need to add -lrt (presumably real time..?)
1,097,479
1,098,357
Name resolution in templates
I was reading about the template name resolution here. Just to get the feel of the things I replicated the code like this: void f (char c) { std::cout<<"f(char)\n"; } template <class T> void g(T t) { f(1); f(T(1)); f(t); d++; } double d; void f(int n) { std::cout<<"f(int)\n"; } void test() { std::cout<<"First call\n"; g(1); std::cout<<"Second call\n"; g('a'); } int main() { test(); return 0; } According to the article linked I should have a compiler error for the d++ statement. Also for the first call of g(1), I should have one call of f(char) followed by two calls of f(int) and for the second call I should get three calls of f(char). However, when I compiled this using Vs2008, it compiled fine without any errors. Also, the output was: First call f(int) f(int) f(int) Second call f(int) f(char) f(char) I am now wondering which one is correct? The article I am linking to or the VS2008 output? Any clue which is correct?
Also for the first call of g(1), I should have one call of f(char) followed by two calls of f(int) and for the second call I should get three calls of f(char). This is not the expected result with a Standard compliant compiler. Since both time you call it with a fundamental type, you will not get name lookup at the instantiation context for the function call. Name lookup at instantiation context only happens for argument dependent lookup (called lookup using associated namespaces). Both of int and char do not have argument dependent lookup, an thus all the function calls you do will call f(char) after you removed the d++ line. Since i understand you won't possibly just believe me, here is the Standard quote, out of 14.6.4.2: For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that: For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found. For the part of the lookup using associated namespaces (3.4.2), only function declarations with external linkage found in either the template definition context or the template instantiation context are found. Note that the article uses a defective example of the Standard (at 14.6/9) (and note that examples are non-normative: They can't change or state rules. Their purpose entirely is illustrative). The defect has been fixed and is incorporated into the upcoming Standard. See this defect report. As you see, you will have to change from int / char to some user defined type (enums or classes) too see the effect of lookup in instantiation context. Read this answer Order affects visibility for more information.
1,097,576
2,873,703
Load Excel data into Linux / wxWidgets C++ application?
I'm using wxWidgets to write cross-plafrom applications. In one of applications I need to be able to load data from Microsoft Excel (.xls) files, but I need this to work on Linux as well, so I assume I cannot use OLE or whatever technology is available on Windows. I see that there are many open source programs that can read excel files (OpenOffice, KOffice, etc.), so I wonder if there is some library that I could use? Excel files it needs to support are very simple, straight tabular data. I don't need to extract any formatting except column/row position and the data itself.
I can say that I know of a wxWidgets application that reads Excel .xls and .xlsx files on any platform. For the .xlsx files we used an XML parser and zip stream reader and grab the data we need, pretty easy to get going. For the .xls files we used: ExcelFormat, which works well and we found the author to be very generous with his support. Maybe just some encouragement to give it a go? It was a couple of days work to get working.
1,097,579
1,103,912
How do I get the VS debugger to display the type name of an object member?
The Visual Studio autoexp.dat syntax allows you to display ‘the name of the most-derived type of the object’ with the 'special format' <,t>, which is very helpful if you have lots of derived types. From the syntax, I assumed that you could do the same thing for members, such as <member,t>, but when I try that the preview only shows ??? Are there ways to display the name of a member’s type in the preview? I’d like to be able to do it in the [autoexpand] section, and also in the [visualizer] section (for different objects of course).
I have found a way to do it, but it's not a very elegant solution: Write an [AutoExpand] entry for the member type which includes the <,t> directive. Then when you display the member with <member> it will show the same information as it does for the member type on its own, including its type name. It's not a great solution, because I don't really want to have to dispay the type information every time when the member type appears on its own, but it does give me the information I was after.
1,097,733
1,097,751
How to Convert Address to Function Pointer to Call Method
I wanted to call Test1() Method Within WaitAndCallFunc() Function. Code: typedef void (*func)(); void StartTimer(void* pFuncAddr); void WaitAndCallFunc(void* pPtr); void WaitAndCallFunc(void* pPtr) { int i = 0; int nWaitTime = 3; while(1) { Sleep(1000); // I want pPtr to call Test1 Function; if(i == nWaitTime) break; } _endthread(); } void StartTimer(void* pFuncAddr) { _beginthread(WaitAndCallFunc, 0, pFuncAddr); } void Test1(); int main(int argc, char* argv[]) { StartTimer(Test1); Sleep(5000); return 0; } void Test1() { cout << "Testing Thread\n"; }
I'm not sure I understand what your question is exactly, but try this: ((func)pPtr)();
1,097,771
1,098,968
getsockopt() returns EINPROGRESS in non blocking connect()+select() flow
Update: My bad. The error I am getting is ECONNREFUSED and not EINPROGRESS. After checking the error variable I've found that it is greater than 0, I printfed errno instead of error. Of course errno is EINPROGRESS because it value didn't change since the call to connect(). Question answered. Thanks folks. I am using the the the same piece of code as in Stevens' UNIX Network Programming non >blocking connect() example: Setting socket to nonblocking Initiate nonblocking connect() Check for immediate completion Call select() with timeout and wait for read or write readiness When select() returns with value greater than 0 do getsockopt(socket, SOL_SOCKET, SO_ERROR, &error, &len). The error I am getting is EINPROGRESS. The code is executed on rhel5 server. Any ideas why I am getting this error? Code snippet: flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); if ((retVal = connect(sockfd, saptr, salen)) < 0) if (errno != EINPROGRESS) return (-1); if (retVal == 0) { // restore file status flags fcntl(sockfd, F_SETFL, flags); return 0; } FD_ZERO(&rset); FD_SET(sockfd, &rset); wset = rset; tval.tv_sec = nsec; tval.tv_usec = 0; if ((retVal = select(sockfd + 1, &rset, &wset, NULL, &tval)) == 0) { // timeout close(sockfd); errno = ETIMEDOUT; return (-1); } if (retVal < 0) { // select() failed return (-1); } if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) { len = sizeof(error); error = 0; if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) return (-1); if (error > 0) //<<<<< error == EINPROGRESS >>> { close(sockfd); errno = error; return (-1); } } else { return (-1); } // restore file status flags fcntl(sockfd, F_SETFL, flags);
Shucks....I give up. I tried and tried but could not find a problem with your code. So, all I offer are some suggestions and hypothesis. Use FD_COPY to copy rset to wset. Can you do a getsockopt when the first connect fails. I am suspecting that Select is returning 0 and because of above, somehow your writefd set is set and doing a getsockopt is returning you the stale error from the previous connect. IMO, a subsquent connect should return EALREADY (although it could be platform dependant) Please do the above (and downvote me if I am wrong about using FD_COPY) and share the results
1,097,785
1,097,861
start exe as non admin from admin exe
When my app updates it needs admin rights and pops the uac prompt up and this is all good. However when it restarts it self its still in admin mode and thus every thing it does has admin rights. The problem comes when the next time the app is started its a normal user and thus cant read any of the files that where made before. How do a start an exe as a normal user from an admin priviladge exe? Visual studio 2008 vista / win 7
Here is an article that describes how to start non-elevated process from an elevated one.
1,097,880
1,097,915
reading bytes directly from RAM C++
Can anyone explain the following behaviour to a relative newbie... const char cInputFilenameAndPath[] = "W:\\testerfile.bin"; int filesize = 4584; char * fileinrampointer; fileinrampointer = (char*) malloc(filesize); ifstream fsInputFileStream; fsInputFileStream.open(cInputFilenameAndPath, fstream::in | fstream::binary); fsInputFileStream.read((char *)(fileinrampointer), filesize); for(int f=0; f<4; f++) { printf("%x\n", *fileinrampointer); fileinrampointer++; } I was expecting the above code to rread the first 4 bytes of the file I just read into memory. In the loop I am just displaying the current byte pointed to by the pointer then incrementing the pointer ready to display the next byte. When I run the code I get: 37 ffffff94 42 ffffffd2 The values are correct but every other value seems to be padded up to a 64 bit number. Because I'm asking it to display the value indicated by a 'char sized' pointer, I was expecting char size results but every other result comes out as a long long. If I asign *fileinrampointer to an unsigned __int8 it leaves me with the value I want (without the leading 1s) which solves the problem, but I'm just wondering if anyone can explain what is happening above?
The expression *fileinrampointer is of type signed char, and it is being promoted to a signed int while being passed to printf. Thus, the sign bit propagates. Later on, you print it out with %x which means unsigned int in hex, which causes you to print all the 1's (as opposed to correctly interpret them as a part of a 2's complement signed integer). Also, ffffffd2 is 8 hex digits which means it's a 32bit signed integer. If you declare fileinrampointer as unsigned char or unsigned __int8 the sign bit doesn't propagate during promotion. You may as well leave it signed and cast it printf("%x\n", static_cast<unsigned char>(*fileinrampointer) ); ISO/IEC 9899:1999 6.5.2.2: 6 . If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions. [...] [...] 7. If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after last declared parameter. The default argument promotions are performed on trailing arguments. This clearly backs up my statement that this is integer promotion, and not printf interpretation. Also see ISO/IEC 9899:1999 7.15.1.1 glibc manual A.2.2.4 glibc manual 12.12.4 securecoding.cert.org
1,097,969
1,097,989
How can web technology be used for a C++ application GUI?
Can web technologies be used for a desktop application written in a traditional language like C++? I'd guess that they can, though I've not been able to find any evidence of this. I understand Adobe Air can make desktop apps using Flash, but it uses web languages like php etc. What I'd like to do is to be able to build my GUI elements - edit boxes, sliders, menus and so on, using html/CSS - instead of native widgets - in an application that is otherwise built in the conventional way - using Visual Studio for example. Does anyone know if this has been done, if there's any software that makes it easier, or if there are any objections to this approach?
Qt is moving in this direction, with CSS-like styling and a forthcoming "declarative" UI mechanism. In addition, you can drive your app with Javascript via QtScript. You could also use QtWebKit to provide an HTML based UI, it's possible to bridge between C++ code and Javascript too.
1,098,303
1,098,875
What makes Scala's operator overloading "good", but C++'s "bad"?
Operator overloading in C++ is considered by many to be A Bad Thing(tm), and a mistake not to be repeated in newer languages. Certainly, it was one feature specifically dropped when designing Java. Now that I've started reading up on Scala, I find that it has what looks very much like operator overloading (although technically it doesn't have operator overloading because it doesn't have operators, only functions). However, it wouldn't seem to be qualitatively different to the operator overloading in C++, where as I recall operators are defined as special functions. So my question is what makes the idea of defining "+" in Scala a better idea than it was in C++?
C++ inherits true blue operators from C. By that I mean that the "+" in 6 + 4 is very special. You can't, for instance, get a pointer to that + function. Scala on the other hand doesn't have operators in that way. It just has great flexibility in defining method names plus a bit of built in precedence for non-word symbols. So technically Scala doesn't have operator overloading. Whatever you want to call it, operator overloading isn't inherently bad, even in C++. The problem is when bad programmers abuse it. But frankly, I'm of the opinion that taking away programmers ability to abuse operator overloading doesn't put a drop in the bucket of fixing all the things that programmers can abuse. The real answer is mentoring. http://james-iry.blogspot.com/2009/03/operator-overloading-ad-absurdum.html None-the-less, there are differences between C++'s operator overloading and Scala's flexible method naming which, IMHO, make Scala both less abusable and more abusable. In C++ the only way to get in-fix notation is using operators. Otherwise you must use object.message(argument) or pointer->messsage(argument) or function(argument1, argument2). So if you want a certain DSLish style to your code then there's pressure to use operators. In Scala you can get infix notation with any message send. "object message argument" is perfectly ok, which means you don't need to use non-word symbols just to get infix notation. C++ operator overloading is limited to essentially the C operators. Combined with the limitation that only operators may be used infix that puts pressure on people to try to map a wide range of unrelated concepts onto a relatively few symbols like "+" and ">>" Scala allows a huge range of valid non-word symbols as method names. For instance, I've got an embedded Prolog-ish DSL where you can write female('jane)! // jane is female parent('jane,'john)! // jane is john's parent parent('jane, 'wendy)! // jane is wendy's parent mother('Mother, 'Child) :- parent('Mother, 'Child) & female('Mother) //'// a mother of a child is the child's parent and is female mother('X, 'john)? // find john's mother mother('jane, 'X)? // find's all of jane's children The :-, !, ?, and & symbols are defined as ordinary methods. In C++ only & would be valid so an attempt to map this DSL into C++ would require some symbols that already evoke very different concepts. Of course, this also opens up Scala to another kind of abuse. In Scala you can name a method $!&^% if you want to. For other languages that, like Scala, are flexible in the use of non-word function and method names see Smalltalk where, like Scala, every "operator" is just another method and Haskell which allows the programmer to define precedence and fixity of flexibly named functions.
1,098,723
1,105,742
Eclipse-CDT: Whats the best way to add a custom build step?
I have a file in my project which I need to compile using an external tool, and the output of that is a pair of .c and .h files. Whats the best way to integrate this into my Eclipse-CDT build? Ideally I can reference the external tool using a relative path Ideally Eclipse will know if I change this file that it needs to re-run the external tool I've tried out adding something to the 'Builders' section under Project Properties with mixed results. thx Alex
I got this working well by adding a 'Builder' of type 'Program'. Right click on the project, Click Properties, Click New ..., Add the location of the file you want to execute, as well as any command line arguments.
1,098,752
1,098,773
Forward "Pre-declaring" a Class in C++
I have a situaion in which I want to declare a class member function returning a type that depends on the class itself. Let me give you an example: class Substring { private: string the_substring_; public: // (...) static SubstringTree getAllSubstring(string main_string, int min_size); }; And SubstringTree is defined as follows: typedef set<Substring, Substring::Comparator> SubstringTree; My problem is that if I put the SubstringTree definition after the Substring definition, the static method says it doesn't know SubstringTree. If I reverse the declarations, then the typedef says it doesn't know Substring. How can I do it? Thanks in advance.
You could define it inside the class: class Substring { private: string the_substring_; public: // (...) typedef set<Substring, Substring::Comparator> SubstringTree; static SubstringTree getAllSubstring(string main_string, int min_size); };
1,098,966
1,099,080
Universal less<> for pointers in C++ standard
Many times I needed a set of pointers. Every time that happens, I end up writing a less<> implementation for a pointer type - cast two pointers to size_t and compare the results. My question is - is that available in the standard? I could not find anything like that. Seems like common enough case... Update: it seems that the upcoming standard fixes all of the problems with less<> provided for pointer types and unordered_set included, too. In a few years this question will be moot. In the mean time, the current standard has no "legal" solution to this, but size_t cast works. Update for update: well, I'll be gobsmacked! Not only std::map<void *, int, std::less<void*> > myMap; works, but even std::map<void *, int > myMap; as well. And that's in gcc 3.4.1 . I've been doing all the these casts for nothing, and litb is perfectly right. Even the section number he cites is exactly the same in the current standard. Hurray!
Two pointers can be compared with using the comparison function objects less, greater etc. Otherwise, using blanket operator< etc, this is only possible if the pointers point to elements of the same array object or one past the end. Otherwise, results are unspecified. 20.3.3/8 in C++03 For templates greater, less, greater_equal, and less_equal, the specializations for any pointer type yield a total order, even if the built-in operators <, >, <=, >= do not. No need to explicitly specialize and manually casting to size_t: That would lower the portability even, since the mapping of reinterpret_cast from pointers to integers is implementation defined and is not required to yield any order. Edit: For a more detailed answer, see this one.
1,099,208
1,099,214
if - else vs if and returns revisited (not asking about multiple returns ok or not)
With regards this example from Code Complete: Comparison Compare(int value1, int value2) { if ( value1 < value2 ) return Comparison_LessThan; else if ( value1 > value2 ) return Comparison_GreaterThan; else return Comparison_Equal; } You could also write this as: Comparison Compare(int value1, int value2) { if ( value1 < value2 ) return Comparison_LessThan; if ( value1 > value2 ) return Comparison_GreaterThan; return Comparison_Equal; } Which is more optimal though? (readability, etc aside)
Readability aside, the compiler should be smart enough to generate identical code for both cases.
1,099,334
1,099,483
add custom context menu to hosted web browser control
I am hosting a web browser control, and want to provide my own context menu. Ideally, I want to present my own context menu, that contains the original browser's context menu (with all addins etc.) as a sub menu. If that's not possible / to tricky, I'd be ok with e.g. normally showing my context menu, and showing the original one when the user presses SHIFT. Do I need to implement IDocHostUIHandler? if yes, how do I specify a custom context menu, how can I force the original one? How do I get the control to use my implementation? The control is created as such (error handling omitted): HRESULT hr=AtlAxCreateControlEx( L"Shell.Explorer",m_wndWebCtrl.m_hWnd, NULL,NULL,(IUnknown**)&unk, IID_IWebBrowser2, NULL); // (IPersistStreamInit*)this); hr = AtlAdviseSinkMap( this, true); IUnknownPtr unk; AtlAxGetControl(m_wndWebCtrl.m_hWnd, &unk); IWebBrowser2Ptr browser2 = unk;
Yes, you do need to implement IDocHostUIHandler. Ok, i guess you could intercept right-clicks, keystrokes, and that other message that'll normally display a context menu... But that's probably gonna break badly sooner or later; at very least, i'd expect it to break accessibility. Once you've intercepted IDocHostUIHandler::ShowContextMenu(), you have the option of returning S_OK to squelch the built-in menu after showing your own. You can use the normal Win32 menu routines for this purpose, a custom control, or even fancy HTML if that's what does it for you. Per the documentation, enough context is provided to allow you to determine what element context is requested for, and what the default context menu would be. Unfortunately, I know of no way to get a handle to the built-in menu. You could probably fake it by showing your context menu and then returning S_FALSE if the user chose the "original" option, but even then there's no way to attach the resulting menu to an existing popup menu (which really should be gone by the time you return anyway if you're running the modal-loop common to such popups). It is possible to add options to the built-in menus. You should be able to use GetKeyboardState() to determine the state of the shift key when the menu was requested. Assuming you only want a subset of the normal browser functionality anyway, you might be better served by just re-implementing the options you want (back, forward, print) and invoking the appropriate command if the user chooses them. Alternately, if you only want normal menus in a very specific scenario (for instance: editing commands in a textarea), use the ShowContextMenu() arguments to identify this and only then return S_FALSE to trigger the default. I've had pretty good luck with this latter technique; after all, they are supposed to be context menus...
1,099,379
1,099,536
How to create a global parameters object
Here's a common, simple task: Read configuration settings from a configuration file, save the settings (e.g. as a hash) in an object, access this object from various objects that need to access the configuration parameters. I found this implementation for the ConfigFile class implementation and it works. My question is: what is the best way to make an instance of this class available from my other classes and be thread safe, avoid static initialization order fiasco, etc. My current approach is to construct it in main() using // Read face detection related parameter values from the configuration file. string configFileName = "detection_parameters.txt"; try { parameters = ConfigFile( configFileName ); } catch(ConfigFile::file_not_found) { cerr << "configuration file not found: " << configFileName << endl; exit(-1); } and then make parameters a global variable. But I also read that singletons should be used instead of global variables. How can the singleton be instantiated with the file name? This must be such a common task that I think there must be a generally accepted good way of doing it? I would appreciate if someone can point me to it. Thanks, C
If you're going to roll-your-own, I would recommend using the Singleton design pattern for your configuration class. Have the class itself store a static pointer of its own type, and the constructor be private so one would be forced to use the static getter to get the one instance of the class. so a mock-up (that may not compile, an is missing the fun Config functionality, but should illustrate the point) class Config { public: static Config * getConfig(); static void setConfigFileName(string filename); private: Config(); static string m_filename; static Config * m_configInstance; }; In case I'm not being clear, the getConfig() would look at m_configInstance. If it isn't a valid one, then it would create one (has access to the private constructor) and store it in m_configInstance so every subsequent call would access the same one. So your main() would use setConfigFileName(), then any class would just have to call Config::getConfig() and then call the operations on it. A lot cleaner than a standard global variable. Blast - in the time I spent writing this, other people have suggested the singleton design pattern too. Ah well - hope the additional explanation helps.
1,099,427
1,190,933
Can one unroll a loop when working with an integer template parameter?
I have the following code: template <int size> inline uint hashfn( const char* pStr ) { uint result = *pStr; switch ( size ) { case 10: result *= 4; result += *pStr; case 9: result *= 4; result += *pStr; ... ... case 2: result *= 4; result += *pStr; } return result; } This code is a hash function for DNA sequences of certain lenghts where the length is a template parameter. It is an unrolled loop with a switch statement to jump in at the right spot. The size is however a constant since it is a template parameter. Could I specialize this for certain size values? Maybe with something like: template <int 2> inline uint hashfn( const char* pStr ) { uint result = *pStr; result *= 4; ++pStr; result += *pStr; return result; }
I would tend to do it recursively with templates. E.g. : template<class TOp,int factor> struct recursive_unroll { __forceinline static void result( TOp& k ) { k(); recursive_unroll<TOp,factor-1>::result( k ); } }; template<class TOp> struct recursive_unroll<TOp,0> { __forceinline static void result( TOp& k ) {} }; struct op { op( const char* s ) : res( 0 ), pStr( s ) {} unsigned int res; const char* pStr; __forceinline void operator()() { res *= 4; res += *pStr; ++pStr; //std::cout << res << std::endl; } }; char str[] = "dasjlfkhaskjfdhkljhsdaru899weiu"; int _tmain(int argc, _TCHAR* argv[]) { op tmp( str ); recursive_unroll<op,sizeof( str ) >::result( tmp ); std::cout << tmp.res << std::endl; return 0; } This produces optimal code for me. Without __forceinline the code is not properly inlined. You should always bench your code before using such optimizations. And then you should look at the assembly and decipher what your compiler already does for you. But in this case, it seems to be an boost (for me). __forceinline is a Microsoft Visual Studio specific extension. The compiler should generate optimal code, but for this it doesn't. So here I used this extension.
1,099,436
1,099,461
Inheriting from std::exception, ambiguity in definitions of std::exception
So I am a little confused, I have been looking around trying to determine an appropriate way of inheriting from std::exception for my own type. Now according to cplusplus.com (and i know this isn't necessarily the standard, thats why I'm asking), std::exception is a base class with no members. However, after looking at my implementation of the standard library (VS 2005), the class std::exception is quite clearly defined with two member variables: class _CRTIMP_PURE exception { // base of all library exceptions ... private: const char *_m_what; int _m_doFree; }; Now is this standard to have these members included within the base class std::exception, my understanding was that it isn't. My reason for asking is that my derived exception class really only needs a single string for its information, thus this implementation would work fine. However, I'm worried that this is non-standard, and as such I might be better off inheriting from std::exception and adding the appropriate members + copy/assignment code myself.
The std::exception class is defined as: namespace std { class exception { public: exception() throw(); exception(const exception&) throw(); exception& operator=(const exception&) throw(); virtual ~exception() throw(); virtual const char* what() const throw(); }; } That is the contract that you have to live up to when it comes to substitutability. The Standard defines the specifics of each member. The only one that usually requires consideration is that what() returns a "null-terminated multi-byte string, suitable for display as a wstring". The other part is obeying and ensuring the throw() contract.
1,099,513
1,099,740
Threadsafe Vector class for C++
Does anyone know a quick and dirty threadsafe vector class for c++? I am multithreading some code, and I believe the problem I have is related to the way the vectors are used. I plan to rewrite the code, but before I go crazy redoing the code, I would like to test it with a threadsafe vector to be sure. I also figure if such a thing is out there, it would be much easier than writing my own version.
This is difficult because of algorithms. Suppose you wrapped vector so that all its member functions are serialised using a mutex, like Java synchronized methods. Then concurrent calls to std::remove on that vector still wouldn't be safe, because they rely on looking at the vector and changing it based on what they see. So your LockingVector would need to specialize every template in the standard algorithms, to lock around the whole thing. But then other algorithms like std::remove_if would be calling user-defined code under the lock. Doing this silently behind the scenes is a recipe for locking inversion as soon as someone starts creating vectors of objects which themselves internally take locks around all their methods. In answer to your actual question: sorry, no, I don't know of one. For a quick test of the kind you need, I recommend that you start out with: template <typename T> class LockedVector { private: SomeKindOfLock lock; std::vector<T> vec; }; Then drop it in as a replacement container, and start implementing member functions (and member typedefs, and operators) until it compiles. You'll notice pretty quickly if any of your code is using iterators on the vector in a way which simply cannot be made thread-safe from the inside out, and if need be you can temporarily change the calling code in those cases to lock the vector via public methods.
1,099,601
1,099,756
ifstream seekg beyond end does not return eof in VS 2008 Express?
In VS 2005, I have some code that looks like this: ifs.open("foo"); while (!ifs.eof()) { ifs.read(&bar,sizeof(bar)); loc = ifs.tellg(); loc += bar.dwHeaderSize; // four byte boundary padding if ((loc % 4) != 0) loc += 4 - (loc % 4); ifs.seekg(loc,ios::beg); } ifs.close(); The code worked fine in VS 2005, but it fails in VS 2008 Express. From what I can tell, VS 2008 is not returning eof() after the code seeks to the end of the file. Am I missing something? I fixed it by adding an explicit check to see if the seek location exceeded the file size, but I want to be sure I understand ifstream correctly.
The EOF flag is only triggered after you attempt to read past the end of file. Reading upto the end of file will not trigger it. This is why most code looks like this: while(ifs.read(&bar,sizeof(bar))) { // Do Stuff } If the result of the read() goes upto the EOF the loop will be entered. If the result of the read() goes past the EOF the loop will NOT be enetered NOTE: read() will only go past the EOF if there are zero bytes left in the file. Otherwise it will read upto the end of the file. So The loop is always entered if there was somthing left in the file. The reason is the result of the read (the return value) is a reference to the stream. If the stream is used in a boolean context (such as the if test expression) it is converted into a type that can be used in such a context. The result of this conversion tests the EOF flag (in addition to a couple of others) and returns the quivalent of false if EOF is true. Note: This techniques works better if you overload the operator << for your Bar class as this should read in exactly what it needs for the object without going past the EOF. It is then easier to make your objects read exactly upto the end of the file without going over. The thing I worry about with read is what should happen if read() wants 10 bytesand there are only 5 bytes in the file, what happens with the partially filled object? If you want to continue using your style the code should look like this: ifs.open("foo"); while (!ifs.eof()) { ifs.read(&bar,sizeof(bar)); if (ifs.eof()) { break; } // Do Stuff }
1,099,717
1,099,803
C++ Encapsulation Techniques
I'm trying to properly encapsulate a class A, which should only be operated on by class B. However, I want to inherit from class B. Having A friend B doesn't work -- friendship isn't inherited. What's the generally accepted way of accomplish what I want, or am I making a mistake? To give you a bit more color, class A represents a complex system's state. It should only be modified by B, which are actions that can be applied to change class A's state.
I assume you want to allow descendants of B to access A directly? If A and B are tightly coupled, you can make A a protected class definition within B itself, instead of being an independent definition. E.G. class B { protected: class A { }; }; Another idea is to create protected methods on B that delegate their actions to A. E.G. class A { friend class B; private: void DoSomething(); }; class B { protected: void DoSomething(A& a) { a.DoSomething(); } };
1,100,432
1,100,524
Performance impact of using write() instead of send() when writing to a socket
I am working on writing a network application in C++ on the Linux platform using the typical sockets API, and I am looking at 2 alternative ways of writing a byte array to a TCP stream: either by calling write(), or by calling send(). I know that, since this is Linux, the socket handle is simply a file descriptor, and therefore it is valid to perform read() and write() calls on the socket, however the sockets API also provides the send() and recv() functions to perform the same tasks. I am therefore wondering if there is any particular reason to choose one class of functions over the other - are the send/recv functions optimized for network writing/reading, do they perform better, etc? Or is it really arbitrary which functions I use? Do read() and write() behave properly in all cases? Thanks for any insights!
There should be no difference. Quoting from man 2 send: The only difference between send() and write() is the presence of flags. With zero flags parameter, send() is equivalent to write(). So long as you don't want to specify and flags for send() you can use write() freely.
1,100,561
1,100,606
"stable_sort()ing" a STL <list> in C++
I think the question title is clear enough: is is possible to stable_sort() a std::list in C++? Or do I have to convert it to a std::vector? I'm asking because I tried a simple example and it seems to require RandomAccessIterators, which a linked list doesn't have. So, how do I stable sort a std::list()? EDIT: sample code that gives me an error: #include <list> #include <algorithm> // ... list<int> the_list; stable_sort(the_list.begin(), the_list.end()); g++ gives me around 30 lines of errors (too long to paste), with some of them referring to RandomAccessIterators (and something called _merge_sort_loop). It's a little weird, since I've seen some merge sort implementations for linked lists and they are pretty much 'sequential'.
std::list::sort is already stable. From the standard, section 23.2.24: "Notes: Stable: the relative order of the equivalent elements is preserved."
1,100,671
1,100,738
Error in std::list::sort with custom comparator (expected primary-expression before ')' token)
The title is the main question. The exact scenario (I am 'using namespace std;'): void SubstringMiner::sortByOccurrence(list<Substring *> & substring_list) { list::sort(substring_list.begin(), substring_list.end(), Substring::OccurrenceComparator); } This is the comparator definition: class Substring { // ... class OccurrenceComparator { public: bool operator() (Substring * a, Substring *b); } }; Implementation of the comparator is intuitive and trivial. I am also using a very similar comparator in a std::set and it works fine. When I add the sortByOccurrence() funcion it gives me the error in the title. What should I do? EDIT: I'm now trying to pass Substring::OccurrenceComparator() as the comparator, and am getting the following error: g++ -Wall -g -c substring_miner.cpp -o obj/subtring_miner.o substring_miner.cpp: In function ‘void SubstringMiner::sortByOccurrence(std::list<Substring*, std::allocator<Substring*> >&)’: substring_miner.cpp:113: error: no matching function for call to ‘std::list<Substring*, std::allocator<Substring*> >::sort(std::_List_iterator<Substring*>, std::_List_iterator<Substring*>, Substring::OccurrenceComparator)’ /usr/include/c++/4.3/bits/list.tcc:303: note: candidates are: void std::list<_Tp, _Alloc>::sort() [with _Tp = Substring*, _Alloc = std::allocator<Substring*>] make: *** [substring_miner] Error 1 My code line is now: list<Substring *>::sort(substring_list.begin(), substring_list.end(), Substring::OccurrenceComparator()); I can't remove the template or it gives me an error saying that template parameters were wrong.
list member sort is a non-static function so must be called on a list instance. substring_list.sort( Substring::OccurrenceComparator() ); Edit: You can't use the free function std::sort as it requires random access iterators which list iterators are not.
1,100,917
1,101,161
iPhone OpenGL ES incorrect alpha blending
I have a problem with incorrect alpha blending results with openGL ES on iPhone. This is my code for creating texture object: glGenTextures(1, &tex_name); glBindTexture(GL_TEXTURE_2D, tex_name); glTextImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, GL_RGBA, GL_UNSIGNED_BYTE, tex_data); 'tex_data' is loaded from raw RGBA8888 data packed with zlib. It loads as it should, wich i've checked with a debugger. This is my code for setting up texture before rendering: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, tex_name); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); I've uploaded a sample of what I've expected and what I've got here: sample . In the sample most of the texture in the bottom is pitch-black with 70% opacity. However openGL renders it as gray. This problem affects all of my textures I use blend with. I've tested the code on windows with use of OGLES PVRVFrame and the results are as expected: black is rendered as black.
Found the problem. I've forgot to set opaque property of CAEAGLLayer of EAGLView to YES.
1,101,028
1,101,639
Display 32bit bitmap - Palette
I have an image data in a buffer(type - long) from a scanner which is 32 bit. For example, buffer[0]'s corresponding pixel value is 952 which is [184, 3, 0, 0] <-[R,G,B,A]; I want to display/Paint/draw on to the screen; I am confused when i tried to read about displying bitmaps. I looked at win32 functions, CBitmap class, windows forms (picture box) etc I am hard to understand the general idea/appraoch for displaying this buffer data on to a application window. I have constructed the BITMAPFILEHEADER AND BITMAPINFOHEADER; Has the pixel data in a buffer, (unsigned char *)vInBuff whose size is vImageSz; //construct the BMP file Header vBmfh.bfType = 19778; vBmfh.bfSize = 54+vImageSz;//size of the whole image vBmfh.bfReserved2 = 0; vBmfh.bfReserved1 = 0; vBmfh.bfOffBits = 54;//offset from where the pixel data can be found //Construct the BMP info header vBmih.biSize = 40;//size of header from this point vBmih.biWidth = 1004; vBmih.biHeight = 1002; vBmih.biPlanes = 1; vBmih.biCompression = BI_RGB; vBmih.biSizeImage = vBmih.biWidth*vBmih.biHeight*4; vBmih.biBitCount = 32; vBmih.biClrUsed = 0; vBmih.biClrUsed = 0; 1.What is that i should be doing next to display this? 2 What should i be using to display the 32bit bitmap? I see people using createwindows functions, windows forms, MFC etc; 3.I also understand that BitBlt,createDIBSection, OnPaint etc are being used? I am confused by these various functions and coding platforms? Please suggest me a simple approach. 4.How can i create a palette to display a 32 bit image? Thanks Raj EDITED TRYING TO IMPLEMENT DAVE'S APPROACH, CAN SOMEBODY COMMENT ON MY IMPLEMTATION. I couldn't continue to the bitblt as i donot have two HDC, i donot know how to get this one? Any help please DisplayDataToImageOnScreen(unsigned char* vInBuff, int vImageSz) // buffer with pixel data, Size of pixel data { unsigned char* vImageBuff = NULL; HDC hdcMem=CreateCompatibleDC(NULL); HBITMAP hBitmap = CreateDIBSection(hdcMem, (BITMAPINFO*)&vBmih, DIB_RGB_COLORS, (void **)&vImageBuff, NULL, 0); GetDIBits(hdcMem, hBitmap, 0, 1, (void**)&vImageBuff, (BITMAPINFO*)&vBmih, DIB_RGB_COLORS); memcpy(vImageBuff,vInBuff,vImageSz); }
Here's a simplified approach you can try, broken down into steps: BITMAPINFO bitmapinfo = { 0 }; bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapinfo.bmiHeader.biWidth = 1004; bitmapinfo.bmiHeader.biHeight = -1002; bitmapinfo.bmiHeader.biPlanes = 1; bitmapinfo.bmiHeader.biCompression = BI_RGB; HBITMAP hBitmap = CreateDIBSection(NULL, &bitmapinfo, DIB_RGB_COLORS, (void **)&vImageBuff, NULL, 0); Now party on vImageBuff and then cache hBitmap somewhere so that within your wndproc you can then in the WM_PAINT handler: select hBitmap into temp compatible HDC call BitBlt(..., SRCCOPY) from the compatible HDC to the window's HDC. the other parameters should be obvious. don't try to stretch or do anything fancy at first. remember to select the original dummy bitmap into the temp HDC before destroying it. If you aren't seeing results try looping through vImageBuff and just set every pixel to RGB(255, 0, 0), or something like that, just to sanity check the rest of the logic. If nothing is drawing make sure that the alpha component for each pixel is 255. If you're getting a garbled image then you need to double-check pixelformat, stride, etc.
1,101,135
1,101,156
writing list of dynamic array to file in binary form>
I want to write a structure which has a list of integer id. The list can be of varying length. typedef struct ss_iidx_node { int totalFreq; vector < int > docIDList; }s_iidx_node; Now, I wish to write this structure in a file and read it back. How can I do it? Wrting is done: fwrite(&obj,sizeof(s_iidx_node),1,dat_fd2); When I read it back, it gives garbage value. It seems it storing only the strating and ending position of stl vector...which on reading is garbage? Any idea how to do it Thanks
Though I'd rather see an approach based on an explicit serialisation, you could try: fwrite(&obj.totalFreq,sizeof(int),1,dat_fd2); fwrite(&obj.docIDList[0],sizeof(int),obj.totalFreq,dat_fd2); Assuming totalFreq == docIDList.size(), it's a spurious variable, so a better implementation would be: size_t size=obj.docIDList.size(); fwrite(&size,sizeof(size_t),1,dat_fd2); fwrite(&obj.docIDList[0],sizeof(int),size,dat_fd2); My preferred implementation would be: size_t size=obj.docIDList.size(); fwrite(&size,sizeof(size_t),1,dat_fd2); for (size_t i=0;i<size;i++) { int id=obj.docIDList[i]; fwrite(&id,sizeof(int),1,dat_fd2); }
1,101,239
1,101,562
Is it possible to customize the Visual Studio autoformat?
I'm using Visual Studio to develop a C/C++ library. I would like to know if there is a way to customize the autoformat tool (Ctrl+K,F) so that: It automatically break lines that are bigger than 120 columns Format a function/method parameter the following way: void myFunction(int parameterA, float parameterB, string paramterC) Format the brackets the following way: void myFunction() { // Code goes here... } To summarize, I want something similar to what Eclipse does with it's autoformat (Ctrl + Shift + F) that can be customized by editing a XML file.
If those options are not good enough for you get UniversalIndentGUI it is a frontend for a whole slew of code formatting engines, you should be able to get the style that you want from it
1,101,599
1,101,650
Good C++ string manipulation library
I'm sorry for flaming std::string and std::wstring. They are quite limited and far from being thread safe. Performance wise, they are not that good too. I miss simple features: Splitting a string into array/vector/list Simple & intuitive case-insensitive find & replace Support for i18n without worrying about string or wstring Conversion to and from int, float, double Conversion to and from UTF-8, UTF-16 & other encodings Thread-safe/reentrant Small footprint & no dependencies Highly portable & cross-platform I've found Qt QString to be useful and also found CBString http://bstring.sourceforge.net/bstrFAQ.shtml Any other suggestions & comparisons? Thank you.
The C++ String Algorithms Library from Boost has pretty much all of the features you need.
1,101,876
1,102,093
Best Data Structure for Genetic Algorithm in C++?
i need to implement a genetic algorithm customized for my problem (college project), and the first version had it coded as an matrix of short ( bits per chromosome x size of population). That was a bad design, since i am declaring a short but only using the "0" and "1" values... but it was just a prototype and it worked as intended, and now it is time for me to develop a new, improved version. Performance is important here, but simplicity is also appreciated. I researched around and came up with: for the chromosome : - String class (like "0100100010") - Array of bool - Vector (vectors appears to be optimized for bool) - Bitset (sounds the most natural one) and for the population: - C Array[] - Vector - Queue I am inclined to pick vector for chromossome and array for pop, but i would like the opinion of anyone with experience on the subject. Thanks in advance!
I'm guessing you want random access to the population and to the genes. You say performance is important, which I interpret as execution speed. So you're probably best off using a vector<> for the chromosomes and a vector<char> for the genes. The reason for vector<char> is that bitset<> and vector<bool> are optimized for memory consumption, and are therefore slow. vector<char> will give you higher speed at the cost of x8 memory (assuming char = byte on your system). So if you want speed, go with vector<char>. If memory consumption is paramount, then use vector<bool> or bitset<>. bitset<> would seem like a natural choice here, however, bear in mind that it is templated on the number of bits, which means that a) the number of genes must be fixed and known at compile time (which I would guess is a big no-no), and b) if you use different sizes, you end up with one copy per bitset size of each of the bitset methods you use (though inlining might negate this), i.e., code bloat. Overall, I would guess vector<bool> is better for you if you don't want vector<char>. If you're concerned about the aesthetics of vector<char> you could typedef char gene; and then use vector<gene>, which looks more natural. A string is just like a vector<char> but more cumbersome.
1,102,007
4,456,422
Broken std::map visualiser in VS2005
I'm using the Intel compiler and visual studio and I can't seem to debug values that are in maps. I get a quick preview which shows the size of the map but the elements only show up as "(error)", I'll illustrate with a quick example, i've generated a map with a single entry myMapVariable[6]=1; if I mouse over I get this "myMapVariable 1" and in the watch window I get the same thing and expanding on the plus gives a single child entry which says name = "(error)" and value = 0 (which is wrong). I've added a line to my autoexp.dat debugging file which shows the raw member variables under the child called [raw members]. I've pretty much reached the limits of my ability to dig into this further without help so I would ask if anyone here can provide some insights.
I have never been able to fix this problem using Intel, but I have now moved to the latest visual studio compiler VS2010 and this is no longer a problem. I'm marking this as the answer because I don't want to leave unanswered questions lying around.
1,102,156
1,106,542
Handling binary dependencies across platforms
I've got a C++ project where we have loads and loads of dependencies. The project should work on Linux and Windows, so we've ported it to CMake. Most dependencies are now included right into the source tree and build alongside the project, so there are no problems with those. However, we have one binary which depends on Fortran code etc. and is really complicated to build. For Linux, it's also not available as a package, but only as precompiled binaries or with full source (needs a BLAS library installed and several other dependencies). For windows, the same library is available as binary, building for Windows seems even more complicated. The question is, how do you handle such dependencies? Just check in the binaries for the supported platforms, and require the user to set up his build environment otherwise (that is, manually point to the binary location), or would you really try to get them compiled along (even if it requires installing like 10 libraries -- BLAS libraries are the biggest pain here), or is there some other recommended way to handle that?
If the binary is independant of the other part of your build process, you definitively should check-in it. But as you cannot include every version of the binary (I mean for every platform and compile flags the user might use) the build from source seems mandatory. I have done something similar. I have checked-in the source code archives of the libraries/binaries I needed. Then I wrote makefile/scripts to build them according to the targeted platform/flags in a specific location (no standard OS location) and make my main build process to point to the right location. I have done that to be able to handle the correct versions and options of the libraries/binaries I needed. It's quite a hard work to make things works for different platforms but it's worth the time ! Oh, and of course it's easier if you use crossplatform build tools :)
1,102,507
1,102,559
What does a "true;" or "10;" statement mean in C++ and how can it be used?
In C++ one can write any of the following statements: 10; true; someConstant; //if this is really an integer constant or something like int result = obtainResult(); result; // looks totally useless The latter can be used to suppress a compiler warning "A variable is initialized but not referenced" (C4189 in VC++) if a macro that is expanded into an empty string in some configuration is later used with the result variable. Like this: int result = obtainResult(); result; assert( result > 0 ); // assert is often expanded into an empty string in Release versions of code What's the meaning of such statements? How can they be used except for compiler warning suppression?
These statements (called expression-statements in the C++ grammar) are valid because they are expressions. Expressions are all constructs that calculate some kind of value, such as 3 + 5 someVariable someFunctionCall( 2 ) someVar += 62 val > 53 I think, to keep the grammar simple, they decided to not differentiate between those expressions that actually have a side effect (such as the function call or the assignment) and those that don't.
1,102,853
1,103,171
Handling different datatypes in a single structure
I need to send some information on a VxWorks message queue. The information to be sent is decided at runtime and may be of different data types. I am using a structure for this - struct structData { char m_chType; // variable to indicate the data type - long, float or string long m_lData; // variable to hold long value float m_fData; // variable to hold float value string m_strData; // variable to hold string value }; I am currently sending an array of structData over the message queue. structData arrStruct[MAX_SIZE]; The problem here is that only one variable in the structure is useful at a time, the other two are useless. The message queue is therefore unneccessarily overloaded. I can't use unions because the datatype and the value are required. I tried using templates, but it doesn't solve the problem.I can only send an array of structures of one datatype at a time. template <typename T> struct structData { char m_chType; T m_Data; } structData<int> arrStruct[MAX_SIZE]; Is there a standard way to hold such information?
There are many ways to handle different datatypes. Besides the union solution you can use a generic struct like : typedef struct { char m_type; void* m_data; } structData; This way you know the type and you can cast the void* pointer into the right type. This is like the union solution a more C than C++ way of doing things. The C++ way would be something using inheritance. You define a base "Data" class an use inheritance to specialize the data. You can use RTTI to check for type if needed. But as you stated, you need to send your data over a VxWork queue. I'm no specialist but if those queues are OS realtime queue, all the previous solutions are not good ones. Your problem is that your data have variable length (in particular string) and you need to send them through a queue that probably ask for something like a fixed length datastruct and the actual length of this datastruct. In my experience, the right way to handle this is to serialize the data into something like a buffer class/struct. This way you can optimize the size (you only serialize what you need) and you can send your buffer through your queue. To serialize you can use something like 1 byte for type then data. To handle variable length data, you can use 1 to n bytes to encode data length, so you can deserialize the data. For a string : 1 byte to code the type (0x01 = string, ...) 2 bytes to code the string length (if you need less than 65536 bytes) n data bytes So the string "Hello" will be serialized as : 0x00 0x00 0x07 0x65 0x48 0x6c 0x6c You need a buffer class and a serializer/deserializer class. Then you do something like : serialize data send serialized data into queue and on the other side receive data deserialize data I hope it helps and that I have not misunderstood your problem. The serialization part is overkill if the VxWorks queues are not what I think ...
1,102,918
1,386,020
Windows not drawing above OpenGL windows
I have an application with an OpenGL window as a child window of the main window. When I display a dialog box above the OpenGL window, it doesn't get drawn. It's like it's not getting WM_PAINT messages. If I can guess the title bar position of the dialog box, I can drag it and it's still responsive. I realise this might be a vague question, but I was wondering if anyone else has seen this sort of behaviour before and knew of a solution? I wondered if the Pixel Format Descriptor would make a difference - I had PFD_DRAW_TO_WINDOW, but changing to PDF_DRAW_TO_BITMAP didn't make any difference. I'm not sure what else I should be looking at?
Bugger. Should have given all the details. I was running Windows in a virtual machine on Mac OS X using Parallels. I upgrade from Parallels 3 to 4 and now everything is working fine. I suspect a Parallels video driver issue. Thanks to all those who answered with suggestions.
1,103,047
1,105,009
Capturing syscall stdout without writing to file in C/C++
I want to read the std output of a system call into a C/C++ string. Can I do this without using a temp file? Perl //without file io $output = `echo hello`; C++ //with file io system ("echo hello > tmp"); std::fstream file ("tmp"); std::string s; file >> s;
Using C's popen (probably the simplest solution, even if it doesn't use C++'s iostream): FILE *p = popen("echo hello", "r"); std::string s; for (size_t count; (count = fread(buf, 1, sizeof(buf), p));) s += string(buf, buf + count); pclose(p); Assuming your iostream has the non-standard xfstream::xfstream(int fd) constructor: FILE *p = popen("echo hello", "r"); std::ifstream p2(fileno(p)); std::string s; p2 >> s; p2.close(); pclose(p); Using Boost.Iostreams, you don't have to depend upon non-standard extensions to iostream: boost::iostreams::file_descriptor_source p2(fileno(p)); Unfortunately, Windows is horrible and _popen only works for console applications; for a graphical app: SECURITY_ATTRIBUTES sec; sec.nLength = sizeof(sec); sec.bInheritHandle = TRUE; sec.lpSecurityDescriptor = NULL; HANDLE *h[2]; CreatePipe(&h[0], &h[1], &sec, 0); SetHandleInformation(h[0], HANDLE_FLAG_INHERIT, 0) STARTUPINFO si; memset((void *)&si, 0, sizeof(si)); si.hStdInput = INVALID_HANDLE_VALUE; si.hStdOutput = h[1]; si.hStdError = INVALUD_HANDLE_VALUE; si.dwFlags |= STARTF_USESTDHANDLES; CreateProcess(NULL, "cmd /c \"echo hello\"", NULL, NULL, TRUE, 0, NULL, NULL, &si, NULL); boost::iostreams::file_descriptor_source p(h[0]); (completely untested)
1,103,313
1,103,342
Is anybody using the named boolean operators?
Or are we all sticking to our taught "&&, ||, !" way? Any thoughts in why we should use one or the other? I'm just wondering because several answers state thate code should be as natural as possible, but I haven't seen a lot of code with "and, or, not" while this is more natural.
Those were not supported in the old days. And even now you need to give a special switch to some compilers to enable these keywords. That's probably because old code base may have had some functions || variables named "and" "or" "not".
1,103,385
1,103,832
is it safe to recv passing in 0 to detect a socket error?
For a TCP blocking socket, is it safe to call: if(SOCKET_ERROR != recv(s, NULL, 0, 0)) //... to detect errors? I thought it was safe, then I had a situation on a computer that it was hanging on this statement. (was with an ssl socket if that matters). I also tried passing in the MSG_PEEK flag with a buffer specified but I also had a hang there. What is the alternative?
In addition to other answers - here's a handy little function to get the pending socket error: /* Retrives pending socket error. */ int get_socket_error( int sockfd ) { int error; socklen_t len( sizeof( error )); if ( getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ) < 0 ) error = errno; return error; }
1,103,863
1,151,491
Painting on top of video in a Qt Widget
I am developing a Qt application that can play the videos and shows some scrolling bar along the way. The window size MUST Not exceed the limit of 720px in height and 1280 in width. I use MPlayer as a slave process and pass it the winId() of the QWidget and it renders the video in it. Now I want another widget on top of this video widget to show some results all the time but placing a label widget on top of the widget that contains video does not serve the purpose as it gets painted over and over by the video. Any workaround? Suggestions about it?
When using MPlayer in this manner, I believe your best option would be to create a second window. There's a couple ways you could go from here, the fancier way which might not work on some versions/configurations of Xorg is to have the second window the same size as the first, and place it directly on top of the other (with a mechanism to move the other window when either is moved), and make the window transparent except for your controls (transparency being the problem with some versions of X, check labs.trolltech.com for some examples of this). The alternative method, which I believe is what VLC uses when in fullscreen mode, is to have the second window just be a small little thing with the controls, and position it on top of the first window with an offset and no border... making it so when the first window is moved, the second window's position is updated.
1,103,933
1,103,988
Prompt with editable default in c++?
Is is possible (without external library such as boost) to prompt for input from the user, like using cin, but with a default choice that is editable by the user (without a GUI)? For example, the program will say: Give your input: default and the user can press enter to use "default" or press 1 then enter to get "default1", etc. EDIT for clarification: What I current have in my program is providing the default in the prompt (as in one of the answer below). But I'm writing for very special cases where having a editable default is extremely time saving (and 90% of the time, all the user needs is adding a suffix to the default). I can prompt for the suffix only, but then I lost flexibility to edit the default in the other 10% of the cases.
You may want to use GNU readline.
1,104,035
1,104,048
"Generic" iterator in c++
I have: void add_all_msgs(std::deque<Message>::iterator &iter); How can I make that function "generic", so it can take any kind of inputiterators ? I don't really care if it's iterating a deque,a vector or something else, as long as the iterator is iterating Message's. - is this at all straight forward possible in c++ ?
template<class InputIterator> void add_all_msgs(InputIterator iter); Usage: std::deque<Message> deq; add_all_msgs(deq.begin());
1,104,235
1,105,960
Is there a simpler Windows C++ Subversion API or an example .vcproj for minimal_client.c?
Following on the tails of my previous (answered) question... SharpSvn makes calling the Subversion client API simple: SvnClient client = new SvnClient(); client.Authentication.DefaultCredentials = new NetworkCredential(username, password); client.CheckOut(new Uri("http://xxx.yyy.zzz.aaa/svn/repository"), workingCopyDir); On the other hand, calling the client API from C/C++, as shown in minimal_client.c requires coding "closer to the metal", as it were, on Subversion. Are there Windows libraries for C++ in Visual Studio 2003 that present a simpler interface than what minimal_client uses? If there are not, is there a VS2003 C++ project (a .vcproj file) that demonstrates getting minimal_client to run? I'm able to compile minimal_client.c and link it using the following libraries: libsvn_client-1.lib libsvn_delta-1.lib libsvn_diff-1.lib libsvn_fs-1.lib libsvn_fs_base-1.lib libsvn_fs_fs-1.lib libsvn_ra-1.lib libsvn_ra_local-1.lib libsvn_ra_svn-1.lib libsvn_repos-1.lib libsvn_subr-1.lib libsvn_wc-1.lib libapr-1.lib libaprutil-1.lib xml.lib libneon.lib but when I run my application (in the debugger or start the release build without debugging), it runs for about 20 seconds without hitting the first line of main() and then throws this exception: An unhandled exception of type 'System.TypeLoadException' occurred in Unknown Module. Additional information: Could not load type apr_pool_t from assembly minimal_client, Version=1.0.3477.16033, Culture=neutral, PublicKeyToken=null. I've tried various combination of libsvn_.lib and svn_.lib to no avail. Any thoughts on what I'm doing wrong? EDIT: I started fresh with a "Win32 Console Project" (still in VS2003) and I am now able to debug the first few lines of my app. But now, on this line: if (svn_cmdline_init ("minimal_client", stderr) != EXIT_SUCCESS) I get a different exception (in the debugger or start the release build without debugging): Unhandled exception at 0x7c91b21a in Win32ConsoleProject_minimal_client.exe: 0xC0000005: Access violation writing location 0x00000010. EDIT: This thread explains that this error is a CRT mismatch between svn and stderr in my app. If I don't want to build Svn so they match (I don't want to), I can pass NULL instead of stderr (provided I'm willing to do without messages that would go to stderr) When I did this, my app ran all the way through correctly.
It seems that C++ wrappers are not overflowing the 'net. However, you may want to try SVNCPP, which can be yoinked from RapidSVN. See http://rapidsvn.tigris.org/ for details (note: I've not tried it).
1,104,605
1,104,635
Need help with STL sort algorithm
I'm having some troubles with using the std::sort algorithm here. I was reading that you can just overload the less than operator to sort classes, but I have been getting all sorts of errors. I have also tried using a functor as you can see in the example I made below. I was hoping somebody could see what I'm doing wrong here. #include <iostream> #include <vector> #include <algorithm> #include <stdlib.h> #include <time.h> class Thing { public: Thing(int val) { this->_val = val; } bool operator<(Thing& rhs) { std::cout << "this works!"; return this->val() < rhs.val(); } int val() { return this->_val; } protected: int _val; }; struct Sort { bool operator()(Thing& start, Thing& end) { return start.val() < end.val(); } }; int main (int argc, char * const argv[]) { std::srand(std::time(NULL)); std::vector<Thing> things; for(int i = 0; i < 100; i++) { Thing myThing(std::rand()); things.push_back(myThing); } if(things[1] < things[2]) { //This works } //std::sort(things.begin(), things.end()); //This doesn't //std::sort(things.begin(), things.end(), Sort()); //Neither does this for(int i = 0; i < 100; i++) { std::cout << things.at(i).val() << std::endl; } return 0; }
I believe you need to change bool operator()(Thing& start, Thing& end) { into bool operator()(const Thing& start, const Thing& end) { and int val() { into int val() const { IOW, your code needs to be const-correct and not claim it may modify things it in fact doesn't (nor needs to).
1,104,816
1,105,151
Using templated "super"
Related question: Using "super" in C++ I examined the source code for OpenSteer and found the following code for defining properties of vehicles. The requirement is Super have too be inherited from an interface class AbstractVehicle. template <class Super> class SteerLibraryMixin : public Super { ... } template <class Super> class AnnotationMixin: public Super { ... } template <class Super> class LocalSpaceMixin: public Super { ... } With these I could define a SimpleVehicle with all properties: // SimpleVehicle_1 adds concrete LocalSpace methods to AbstractVehicle typedef LocalSpaceMixin<AbstractVehicle> SimpleVehicle_1; // SimpleVehicle_2 adds concrete annotation methods to SimpleVehicle_1 typedef AnnotationMixin<SimpleVehicle_1> SimpleVehicle_2; // SimpleVehicle_3 adds concrete steering methods to SimpleVehicle_2 typedef SteerLibraryMixin<SimpleVehicle_2> SimpleVehicle_3; // SimpleVehicle adds concrete vehicle methods to SimpleVehicle_3 class SimpleVehicle : public SimpleVehicle_3 { ... } Or just with one of the properties: class SimpleVehicle : public LocalSpaceMixin<AbstractVehicle> { ... } This was pretty smart, here I could choose what properties my vehicles should have but when I tried to compile it it didn't work! Compiler errors: SteerLibrary.hpp||In member function Vec2D SteerLibrary<Super>::SteerForWander(float)':| SteerLibrary.hpp|41|error: there are no arguments toGetMaxSpeed' that depend on a template parameter, so a declaration of GetMaxSpeed' must be available| SteerLibrary.hpp|41|error: (if you use-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)| SteerLibrary.hpp|42|error: there are no arguments to GetVel' that depend on a template parameter, so a declaration ofGetVel' must be available| Here I'm trying to access my AbstractVehicle member function 'GetMaxSpeed' and 'GetVel'. With '-fpermissive' it compiles and work but it issues a warning for every member function and with good reason - one could pretty easily inherit from a non AbstractVehicle with none of these functions! Now for my question: Is this a better way to handle this? I tried with the typedef method like the link above but it didn't work at all.
I think that doing: this->GetMaxSpeed() will solve your problem. Also You could do: SimpleVehicle::GetMaxSpeed() both of these explicitly say where the function is coming from.
1,105,058
1,105,074
Can I create an object from a derived class by constructing the base object with a parameter?
In other words, given a base class shape and a derived class rectangle: class shape { public: enum shapeType {LINE, RECTANGLE}; shape(shapeType type); shape(const shape &shp); } class rectangle : public shape { public: rectangle(); rectangle(const rectangle &rec); } I'd like to know if I could create an instance of rectangle by calling: shape *pRectangle = new shape(RECTANGLE); and how could I implement the copy constructor, in order to get a new rectangle by calling: shape *pNewRectangle = new shape(pRectangle);
Short Answer: No Long Answer: You need a factory object/method. You can add a static factory method to the base class the creates the appropriate object type. class Shape { static Shape* createShape(shapeType type) { switch (type) { case RECTANGLE:return new rectangle(); ... } } }; Personal preference: I would go with a completely different class to be the factory rather than using a static method on the base class. The reason for this is that every time you create a new Shape class the above style forces you to re-build the Shape class each time. So I would separator out the factory into a ShapeFactory class.
1,105,349
1,106,120
C++ OpenGL Window and Context creation framework / library
I'm searching for an multi platform OpenGL framework that abstracts the creation of windows and gl contexts in C++. I'd like to have an OO representation of Window, Context & co where i can instantiate a Window, create a Context and maybe later set the window to fullscreen. I'm thinking about implementing this myself for xgl, wgl and agl. But before So here comes the Question: Which libraries / frameworks should i check out first, before inventing the wheel again? Edit: So far named libraries: glut Qt SDL gtkglext wxwdigets SFML
SMFL is another, similar to SDL, but takes a more object oriented approach.
1,105,398
1,109,834
Multiple Rendertargets in DX9
I've set m_lpD3DDevice->SetRenderTarget(0,Buffer1); m_lpD3DDevice->SetRenderTarget(1,Buffer2); m_lpD3DDevice->SetRenderTarget(2,Buffer2); and if I render the pixelshader only affects the first render target. It's output structure is struct PS_OUTPUT { float4 Color0 : COLOR0; float4 Color1 : COLOR1; float4 Color2 : COLOR2; }; what do I need to do to affect the other two render targets too?
I finally have the answer now. All I had to do was to set ColorWriteEnable = red | green | blue; in the effect file. Everything else was correct. But I don't know why this made it work.
1,105,642
1,106,130
Adding SSL support to existing TCP & UDP code?
Here's my question. Right now I have a Linux server application (written using C++ - gcc) that communicates with a Windows C++ client application (Visual Studio 9, Qt 4.5.) What is the very easiest way to add SSL support to both sides in order to secure the communication, without completely gutting the existing protocol? It's a VOIP application that uses a combination of UDP and TCP to initially set up the connection and do port tunneling stuff, and then uses UDP for the streaming data. I've had lots of problems in the past with creating the security certificates from scratch that were necessary to get this stuff working. Existing working example code would be ideal. Thank you!
SSL is very complex, so you're going to want to use a library. There are several options, such as Keyczar, Botan, cryptlib, etc. Each and every one of those libraries (or the libraries suggested by others, such as Boost.Asio or OpenSSL) will have sample code for this. Answering your second question (how to integrate a library into existing code without causing too much pain): it's going to depend on your current code. If you already have simple functions that call the Winsock or socket methods to send/receive ints, strings, etc. then you just need to rewrite the guts of those functions. And, of course, change the code that sets up the socket to begin with. On the other hand, if you're calling the Winsock/socket functions directly then you'll probably want to write functions that have similar semantics but send the data encrypted, and replace your Winsock calls with those functions. However, you may want to consider switching to something like Google Protocol Buffers or Apache Thrift (a.k.a. Facebook Thrift). Google's Protocol Buffers documentation says, "Prior to protocol buffers, there was a format for requests and responses that used hand marshalling/unmarshalling of requests and responses, and that supported a number of versions of the protocol. This resulted in some very ugly code. ..." You're currently in the hand marshalling/unmarshalling phase. It can work, and in fact a project I work on does use this method. But it is a lot nicer to leave that to a library; especially a library that has already given some thought to updating the software in the future. If you go this route you'll set up your network connections with an SSL library, and then you'll push your Thrift/Protocol Buffer data over those connections. That's it. It does involve extensive refactoring, but you'll end up with less code to maintain. When we introduced Protocol Buffers into the codebase of that project I mentioned, we were able to get rid of about 300 lines of marshalling/demarshalling code.
1,105,839
1,105,862
MFC: GetWindowRect usage
I'm trying to determine the window position of an application. I know SetWindowPos() would set the window position at a certain position with a specific sizing. I would like to retrieve this information, but I have noticed some negative values in there. When I save these values into the registry and then load them on the next instance, I can't replicate the sizing and placement information accurately. Is this even the most accurate function to be used in the first place? Thanks.
You should be calling the GetWindowPlacement method to get the WINDOWPLACEMENT structure which has not only the window position, but the state of the window (minimized, maximized, etc, etc). In turn, you should store this information in the registry in addition to the position values and set the state of the window when reading the values back from the registry.
1,106,065
1,107,044
XPath support in Xerces-C
I am supporting a legacy C++ application which uses Xerces-C for XML parsing. I've been spoiled by .Net and am used to using XPath to select nodes from a DOM tree. Is there any way to get access some limited XPath functionality in Xerces-C? I'm looking for something like selectNodes("/for/bar/baz"). I could do this manually, but XPath is so nice by comparison.
See the xerces faq. http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9 Does Xerces-C++ support XPath? No.Xerces-C++ 2.8.0 and Xerces-C++ 3.0.1 only have partial XPath implementation for the purposes of handling Schema identity constraints. For full XPath support, you can refer Apache Xalan C++ or other Open Source Projects like Pathan. It's fairly easy to do what you want using xalan however.
1,106,082
1,122,851
Open source project for c++ developer?
I am a vc++ developer (but like Qt) interested in learning from open source project by contributing and reading the code. I use windows as primary development platform. Which project will be right for me to start? Is chromium a good choice?
Is chromium a good choice? I believe so, yes! The source code is IMO very well written, it's a really active project with a lot of work to do and is also interesting in many different ways. Obviously a browser is in itself just a combination of specific libraries, and thus Chromium gives you a nice entry to learn more about them and hopefully contribute evidently. But most importantly it has a big community, is sponsored by a big corporation and has many talented software engineers on its core team. Want to learn how to integrate the V8 javascript engine? Want to learn about rendering/drawing on screen via Skia? Want to learn how to integrate Webkit? Want to learn more about the HTTP protocol / network stack? Want to learn how to sandbox applications? Want to learn about multi-process architecture and IPC? There are so many things to do, so you could even contribute things you know while learning stuff you don't. I'd like to add; The choice of an open source project to join should be based on: Your level of expertize What you'd like to learn Quality of the code Maturity of the project Code complexity (not to be confused with readability) I only speak for myself here, but as much as I love learning more from too complex projects (file systems, RDBM etc) I find those projects to be less rewarding because of the overwhelming complexity. Try not to learn everything at once, take smaller steps and finish what you start rather than taking larger steps and give up. Just my 2c - YMMV In case you'd want to try Chromium out, here are links for the design documents: Getting around the source code explains in great detail how the projects tree structure is built. The Engineering design docs explain the architecture, most under the hood and future work The user experience design docs provide insight to everything that touches the user, that is behavior and look. Tech Talk Videos that are very helpful for understanding some key engineering issues and decisions, even if you don't intend to join the chromium project. The links above are all taken from the Chromium developer documentation, where even more details can be found. Anyway, good luck finding a project that fits your needs!
1,106,149
1,106,167
What is a "translation unit" in C++?
I am reading at the time the "Effective C++" written by Scott Meyers and came across the term "translation unit". Could somebody please give me an explanation of: What exactly it is? When should I consider using it while programming with C++? Is it related to C++ only, or it can be used with other programming languages as well? I might already use it without knowing the term...
From here: (wayback machine link) According to standard C++ (wayback machine link) : A translation unit is the basic unit of compilation in C++. It consists of the contents of a single source file, plus the contents of any header files directly or indirectly included by it, minus those lines that were ignored using conditional preprocessing statements. A single translation unit can be compiled into an object file, library, or executable program. The notion of a translation unit is most often mentioned in the contexts of the One Definition Rule, and templates.
1,106,483
1,106,572
Modify a Binary file(an after effect project file) in c# or c++
I need to change some text values inside an after effect project file that I assume it's a binary file. You cannot edit this file with a text editor, if you do next time you open it you will encounter the error message about corrupted project file. So i need to for example change "TextArea1" to "Some new text" so as you see the length of the new text is not the same as the original one. should i use BinaryReader or something? how can i find the original String in Byte[] Array i get from this command... As I'm a newbie in this field please tell me what should I do in this matter.
Have you got visual studio? If so, do: File->Open and select the file. On the open button, press the drop down arrow. Choose "Open With..." Select: Binary Editor. At least you can see what's in the file. This is at least a good starting point. It will show you the byte values, and any character value for the byte on the right-hand side. As for how to edit the text, it all depends on what the format of the data is. I know you say it's binary, but that isn't a format, saying something is binary just means you don't actually know what the format is. It might be that before a string (text) value, the previous byte gives the length of the text, so you could insert some more text and then increase this value. It might be that the length is stored in two or more bytes (because a byte can only hold values up to 256, and they might use two bytes for the format if they expect they might want text longer than 256). The format might after a piece of text have a byte that has the value 0 to mark the end of the text. Also, text may often be stored with one character in 1 byte, or 1 character in 2 bytes, or for some characters (mandarin etc), the number of bytes per characters can vary. Good luck! The best advice is to try and track down someone who knows what the files format is. Tell us more about the file, what type is it? Has it got an extension.
1,106,519
1,106,602
Overwriting function in another dll without edits to primary dll
This one game I do scripting for uses a primary dll in which our scripts we write (creatively named "scripts.dll" This scripts.dll, server-side, loads other plugins (.dlls as well). Question: I need to override an existing function in scripts.dll in, for example, pluginA.dll to where the one in scripts.dll doesn't get called. I had the idea of maybe grabbing the address of the one in scripts.dll and overwriting it with (memcpy()?) the address of my new function. Oh and the functions are named the same.
First I would try to adjust the caller to get this specific function pointer from pluginA.dll, and not from scripts.dll, through GetProcAddress. If that is not feasible, I would overwrite the start of the old function with a jump instruction to the new function. The jump instruction on x86 is "E9 XX XX XX XX"; notice that the target address is relative to the PC following the jump. If you don't have x86, the machine code will look different, of course.
1,106,659
1,145,554
Handle HTMLElementEvents2 when DWebBrowserEvents2 has been handled using ATL's macros
I'm creating a Browser Helper Object using VS2008, C++. My class has been derived from IDispEventImpl among many others class ATL_NO_VTABLE CHelloWorldBHO : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CHelloWorldBHO, &CLSID_HelloWorldBHO>, public IObjectWithSiteImpl<CHelloWorldBHO>, public IDispatchImpl<IHelloWorldBHO, &IID_IHelloWorldBHO, &LIBID_HelloWorldLib, /*wMajor =*/ 1, /*wMinor =*/ 0>, public IDispEventImpl<1, CHelloWorldBHO, &DIID_DWebBrowserEvents2, &LIBID_SHDocVw, 1, 1> { . . . BEGIN_SINK_MAP(CHelloWorldBHO) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_DOCUMENTCOMPLETE, OnDocumentComplete) SINK_ENTRY_EX(1, DIID_DWebBrowserEvents2, DISPID_BEFORENAVIGATE2, BeforeNavigate2)//Handle BeforeNavigate2 END_SINK_MAP() . . . } As apparent from the code above, my DWebBrowserEvents2 are handled using the ATL's macros. Now I want to handle HTMLElementEvents2 (to detect clicks, scrollbars, etc.) For that, I QueryInterface() the IHTMLDocument2 object for IHTMLElement, QueryInterface() that for IConnectionPointContainer and call IConnectionPointContainer::FindConnectionPoint(DIID_HTMLElementEvents2). (See msdn's article on handling HTMLElementEvents2). The problem is, when I overwrite IDispatch::Invoke in my class, the DWebBrowserEvents2 handles (created using ATL macros) fail. Is there a way to handle HTMLElementEvents2 without overwriting Invoke, or implement invoke in such a way that it only handles HTMLElementEvents2? Thanks, Any help will be appreciated.
There is no real need to override Invoke or get IConnectionPointContainer. Since this is an ATL project, Implementing another IDispEventImpl: public IDispEventImpl<2, CHelloWorldBHO, &DIID_HTMLTextContainerEvents2, &LIBID_MSHTML, 4, 0> does the trick. Then, sink the entry as: SINK_ENTRY_EX(2, DIID_HTMLTextContainerEvents2, DISPID_ONSCROLL, OnScroll) In OnDocumentComplete, call IWebBrowser2::get_Document, IHTMLDocument2::get_body, and then call DispEventAdvise to start receiving events. Note that I've used DIID_HTMLTextContainerEvents2 instead of DIID_HTMLElementEvents. That's because the body object does not support HTMLElementEvents2, and for my purpose (to handle scrolling) this works just fine!
1,106,820
1,106,838
Get Keyboard input c++ outside of terminal
I am trying to write a c++ program that responds to keyboard input. I want to run this as a daemon so I can't use cin, I would also like to output each character as it is pressed to a picoLCD screen that I have set up. What is the best way to do this?
If the application is running in the background as a daemon, you can use the common Windows approach of a "keyboard hook". This is performed much differently on Linux though and there are various methods you may want to look into. It is discussed a bit in this SO question: system wide keyboard hook on X under linux
1,106,930
1,107,432
Cygwin GDB gives error 193 when trying to start program
When I attempt to debug a simple program with gdb on cygwin I get the following: C:\Users\Benoit St-Pierre\workspace_cpp\cs454>gdb a.exe GNU gdb 6.8.0.20080328-cvs (cygwin-special) Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-pc-cygwin"... (gdb) start Breakpoint 1 at 0x401a51: file server.cc, line 207. Starting program: /cygdrive/c/Users/Benoit St-Pierre/workspace_cpp/cs454/a.exe Error creating process /cygdrive/c/Users/Benoit St-Pierre/workspace_cpp/cs454/a.exe, (error 193). Where the error 193 is a ERROR_BAD_EXE_FORMAT. The compiled application itself runs great and clients connect and interact with the application. I'm using cygwin 1.7 since I'm using the new getaddrinfo methods for setting up sockets. The application was compiled using gcc 3.4.4 with the following command: g++ -g3 server.cc Anyone have a clue what I might be doing wrong?
The problem is that you have space character in your path name. Move the file to a different directory and gdb will be able to start the process.
1,107,149
1,107,235
Is it possible to get the value type from an arbitrary iterator (C++)?
I have a class template <typename Iterator, typename Value> class Foo { public: Foo(const Iterator& it) { ... } ... private: map<Value, int> m_; } }; Is there any way to get rid of Value in the template? The Iterator may or may not be an STL iterator, but it's guaranteed that *it type is Value. I know about iterator_traits<T>::value_type for STL iterators, but wonder if there's any way to get Value type automatically for an arbitrary Iterator type? One trick I'm thinking about - say, we have a helper class template <typename Iterator, typename Value> class Bar { public: Bar(const Iterator& dummy_iterator, const Value& dummmy_value) {} ... }; Then if we instantiate Bar as Bar(it, *it), the type of Value will be known inside Bar. But I can't find a good way to combine Bar with Foo.
Any iterator should provide iterator_traits<Iterator>::value_type. If it does not, then it is not an iterator. ISO C++ 2003 24.3.1[lib.iterator.traits] "Iterator traits": To implement algorithms only in terms of iterators, it is often necessary to determine the value and difference types that correspond to a particular iterator type. Accordingly, it is required that if Iterator is the type of an iterator, the types iterator_traits<Iterator>::difference_type iterator_traits<Iterator>::value_type iterator_traits<Iterator>::iterator_category be defined as the iterator’s difference type, value type and iterator category, respectively. Aside from that, there's no general way to obtain a type of an arbitrary C++ expression. C++0x will rectify it by providing decltype.
1,107,596
1,107,639
Trying to return multiple values
I'm having some trouble returning multiple values in this program that calculates min, max, mean, median. The first thing I did was pass reference arguments, and it worked - but I read that creating a struct or class is the preferred method to returning multiple values. So I tried and I haven't been able to get good results. Here is what I've got so far. #include "std_lib_facilities.h" struct maxv{ int min_value; int max_value; double mean; int median; }; maxv calculate(vector<int>& max) { sort(max.begin(), max.end()); min_value = max[0]; int m = 0; m = (max.size()-1); max_value = max[m]; for(int i = 0; i < max.size(); ++i) mean += max[i]; mean = (mean/(max.size())); int med = 0; if((max.size())%2 == 0) median = 0; else { med = (max.size())/2; median = max[med]; } } int main() { vector<int>numbers; cout << "Input numbers. Press enter, 0, enter to finish.\n"; int number; while(number != 0){ cin >> number; numbers.push_back(number);} vector<int>::iterator i = (numbers.end()-1); numbers.erase(i); maxv result = calculate(numbers); cout << "MIN: " << result.min_value << endl; cout << "MAX: " << result.max_value << endl; cout << "MEAN: " << result.mean << endl; cout << "MEDIAN: " << result.median << endl; keep_window_open(); } Obviously the variables in the calculate function are undeclared. I'm simply not sure how to implement this in the correct way to return the correct values. So far from the things I've tried, I've gotten VERY construed values. Any help would be appreciated - thanks. P.S. I've looked at other threads regarding this topic and I'm still kind of confused since there aren't really any differences between the arguments that need to be passed to calculate() and the variables in the maxv struct.
There are three ways to do it. 1) Return a maxv instance from the calculate function maxv calculate(vector<int>& max) { maxv rc; //return code ... some calculations ... ... initialize the instance which we are about to return ... rc.min_value = something; rc.max_value = something else; ... return it ... return rc; } 2) Pass-in a maxv instance by reference void calculate(vector<int>& max, maxv& rc) { ... some calculations ... ... initialize the instance which we were passed as a parameter ... rc.min_value = something; rc.max_value = something else; } 3) Say that calculate is a method of the maxv struct (or even better, the constructor) struct maxv { int min_value; int max_value; double mean; int median; //constructor maxv(vector<int>& max) { ... some calculations ... ... initialize self (this instance) ... this->min_value = something; this->max_value = something else; } };
1,107,672
1,107,687
How to gain Access to member variables of a class using void pointer but Not Object
I am trying to access member variables of a class without using object. please let me know how to go about. class TestMem { int a; int b; public: TestMem(){} void TestMem1() { a = 10; b = 20; } }; void (TestMem::*pMem)(); int main(int argc, char* argv[]) { TestMem o1; pMem = &(TestMem::TestMem1); void *p = (void*)&pMem; // How to access a & b member variables using variable p getch(); return 0; }
The "right" way to do this is by using the offsetof() macro from <stddef.h>. Unfortunately offsetof() has some fairly draconian restrictions in C++: Because of the extended functionality of structs in C++, in this language, the use of offsetof is restricted to "POD [plain old data] types", which for classes, more or less corresponds to the C concept of struct (although non-derived classes with only public non-virtual member functions and with no constructor and/or destructor would also qualify as POD). So if you make a and b public and get rid of TestMem's constructor, you can write something like this to access a: C++ style: #include <cstddef> int vala = *reinterpret_cast<int *>(reinterpret_cast<char *>(&o1) + offsetof(TestMem, a)); C style: #include <stddef.h> int vala = *(int *) ((char *) &o1 + offsetof(TestMem, a)); Notice that you need to use &o1 here, not p, which is a function pointer. The address of TestMem::TestMem1 won't have any relation to the locations of a and b. Class methods don't reside in memory anywhere near class member variables. The "wrong" way is to just guess at where a and b are in memory. Most likely they are at offsets 0 and 4 from the start of o1, respectively. So this code would work most of the time: int vala = *(int *) ((char *) &o1 + 0); int valb = *(int *) ((char *) &o1 + 4); There are a lot of assumptions here. This assumes that ints are 4 bytes and that there's no padding between a and b. On the other hand it doesn't have any of the restrictions from above: a and b don't need to be public, you can have a constructor, whatever.
1,107,705
1,107,717
system("pause"); - Why is it wrong?
Here's a question that I don't quite understand: The command, system("pause"); is taught to new programmers as a way to pause a program and wait for a keyboard input to continue. However, it seems to be frowned on by many veteran programmers as something that should not be done in varying degrees. Some people say it is fine to use. Some say it is only to be used when you are locked in your room and no one is watching. Some say that they will personally come to your house and kill you if you use it. I, myself am a new programmer with no formal programming training. I use it because I was taught to use it. What I don't understand is that if it is not something to be used, then why was I taught to use it? Or, on the flip side, is it really not that bad after all? What are your thoughts on this subject?
It's frowned upon because it's a platform-specific hack that has nothing to do with actually learning programming, but instead to get around a feature of the IDE/OS - the console window launched from Visual Studio closes when the program has finished execution, and so the new user doesn't get to see the output of his new program. Bodging in System("pause") runs the Windows command-line "pause" command and waits for that to terminate before it continues execution of the program - the console window stays open so you can read the output. A better idea would be to put a breakpoint at the end and debug it, but that again has problems.
1,107,784
1,107,837
I'm trying to return a SDL Mix_Music data type, but I'm having problems
I know I could just make all the Mix_Musics public, and not worry about the problem, but I'd still like to understand how to do it. //header.h class Music { private: Mix_Music * BGMusic, * fall, * reset, * teleport, * win, * singleCubeWin; public: Music(); bool loadMusic(); void clean_up(); Mix_Music * getSound( Mix_Music * m ) { return m; } }; //program.cpp Music Sound; int main( int argc, char* args[] ) { ... Mix_PlayMusic( Sound.getSound( "BGMusic" ), -1 ); ... }
From your code above I'm not absolutely certain what you are trying to do. The function 'getSound' takes a Mix_Music object as the parameter and returns the same object. Now from some deduction I assume that you are trying to request the BGMusic object via a string. There a few ways to do this, via IDs for each of Mix_Music objects, request by ID.: ... // Somewhere above: enum MixMusicID { BGMUSIC, FALL, RESET, TELEPORT, WIN, SINGLECUBEWIN }; ... // In the class: Mix_Music * getMusic ( MixMusicID id ) { switch (id) { case BGMUSIC: return BGMusic; ... default: return NULL; } } ... // In main: Mix_PlayMusic( Sound.getSound( BGMUSIC ), -1 ); You could do it similarly with string identifiers for each object. What it really comes down to is there is no built in relationship between a variable's name and a string identifier. So its up to you to implement this relationship either via an enum (above) or string identifiers. Hope this helped, again not sure exactly what the question was.
1,107,846
1,107,900
Display c++ code in php
I am trying to display the contents of a .cpp file in php. I am loading it using fread when I print it out it comes out formatted incorrectly. How can I keep the format without escaping each character?
<?php echo "<pre><code>"; $filename = "./test.cpp"; $handle = fopen($filename, "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096); // assuming max line len is 4096. echo htmlspecialchars($buffer); } fclose($handle); } echo "</code></pre>"; ?> We need htmlspecialchars function to print it out correctly.
1,107,862
1,107,895
HTTP client example on win32
I wanted to develop one HTTP example on win32 platform, which is asynchronous. I am new to win32 programming, what are the api and library win32 platform provides for HTTP send and receive request? I am using Windows XP with VS 2005. If any example is available please provide a link to it.
You can use WinHTTP library. Here is an sample on Asynchronous completion.
1,107,940
1,108,181
size_t can not be found by g++-4.1 or others on Ubuntu 8.1
This has happened before to me, but I can't remember how I fixed it. I can't compile some programs here on a new Ubuntu install... Something is awry with my headers. I have tried g++-4.1 and 4.3 to no avail. g++ -g -frepo -DIZ_LINUX -I/usr/include/linux -I/usr/include -I/include -c qlisttest.cpp /usr/include/libio.h:332: error: ‘size_t’ does not name a type /usr/include/libio.h:336: error: ‘size_t’ was not declared in this scope /usr/include/libio.h:364: error: ‘size_t’ has not been declared /usr/include/libio.h:373: error: ‘size_t’ has not been declared /usr/include/libio.h:493: error: ‘size_t’ does not name a type /usr/include/stdio.h:294: error: ‘size_t’ has not been declared ... the file... #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> ... @ubuntu:~/work/zpk/src$ cat /usr/include/linux/types.h | grep size_t typedef __kernel_size_t size_t; typedef __kernel_ssize_t ssize_t; types.h is definitely in the path, and is getting picked up. I verified by changing the file name and get an error its missing... Does anyone have any ideas...? I would really appreciate the help...
Start by removing -I/usr/include/linux and -I/usr/include. Adding system directories to include paths manually either has no effect, or breaks things. Also, remove -frepo for extra safety.
1,107,948
1,108,097
Test whether a class is polymorphic
We have a sub-project 'commonUtils' that has many generic code-snippets used across the parent project. One such interesting stuff i saw was :- /********************************************************************* If T is polymorphic, the compiler is required to evaluate the typeid stuff at runtime, and answer will be true. If T is non-polymorphic, the compiler is required to evaluate the typeid stuff at compile time, whence answer will remain false *********************************************************************/ template <class T> bool isPolymorphic() { bool answer=false; typeid(answer=true,T()); return answer; } I believed the comment and thought that it is quite an interesting template though it is not used across the project. I tried using it like this just for curiosity ... class PolyBase { public: virtual ~PolyBase(){} }; class NPolyBase { public: ~NPolyBase(){} }; if (isPolymorphic<PolyBase>()) std::cout<<"PolyBase = Polymorphic\n"; if (isPolymorphic<NPolyBase>()) std::cout<<"NPolyBase = Also Polymorphic\n"; But none of those ever returns true. MSVC 2005 gives no warnings but Comeau warns typeid expression has no effect. Section 5.2.8 in the C++ standard does not say anything like what the comment says i.e. typeid is is evaluated at compile time for non-polymorphic types and at runtime for polymorphic types. 1) So i guess the comment is misleading/plain-wrong or since the author of this code is quite a senior C++ programmer, am i missing something? 2) OTOH, I am wondering if we can test whether a class is polymorphic(has at least one virtual function) using some technique? 3) When would one want to know if a class is polymorphic? Wild guess; to get the start-address of a class by using dynamic_cast<void*>(T) (as dynamic_cast works only on polymorphic classes). Awaiting your opinions. Thanks in advance,
I cannot imagine any possible way how that typeid could be used to check that type is polymorphic. It cannot even be used to assert that it is, since typeid will work on any type. Boost has an implementation here. As for why it might be necessary -- one case I know is the Boost.Serialization library. If you are saving non-polymorphic type, then you can just save it. If saving polymorphic one, you have to gets its dynamic type using typeid, and then invoke serialization method for that type (looking it up in some table). Update: it appears I am actually wrong. Consider this variant: template <class T> bool isPolymorphic() { bool answer=false; T *t = new T(); typeid(answer=true,*t); delete t; return answer; } This actually does work as name suggests, exactly per comment in your original code snippet. The expression inside typeid is not evaluated if it "does not designate an lvalue of polymorphic class type" (std 3.2/2). So, in the case above, if T is not polymorphic, the typeid expression is not evaluated. If T is polymorphic, then *t is indeed lvalue of polymorphic type, so entire expression has to be evaluated. Now, your original example is still wrong :-). It used T(), not *t. And T() create rvalue (std 3.10/6). So, it still yields an expression that is not "lvalue of polymorphic class". That's fairly interesting trick. On the other hand, its practical value is somewhat limited -- because while boost::is_polymorphic gives you a compile-time constant, this one gives you a run-time value, so you cannot instantiate different code for polymorphic and non-polymorphic types.
1,107,990
1,108,006
Scope, arrays, and the heap
So, I have this array. It needs to be accessed outside the scope of this function. I have been slapping a pointer to it into a pair which gets put into a deque. But once I'm outside the scope, the local stack is gone, the array is invalid, and I've just got a useless pointer, right? So I've trying to put this array onto the scope-transcending heap, where it will remain until I delete it at a later time. But I'm having issues getting this working. Right now g++ is coughing up errors about invalid conversion from 'int' to 'int*'. void randomFunction(int x, int y, int width, int height) { int **blah[4] = {x, y, width, height}; std::pair <foobar*, int* > tempPair (foobar1, blah); randomDeque.push_front(tempPair); } I've also tried initializing it like this: int *blah[4] = new int[4]; ...and it says that the array must be initialized with a brace-enclosed initializer. I'm really not used to working with pointers. What am I doing wrong?
The whole concept looks strange to me. If you declare array on the stack, it will not exist outside the scope of your function. If you allocate it using 'new' - make sure you 'delete' it sometime, otherwise it's memory leak! The correct code with 'new' is: int *blah = new int[4]; ... // don't forget to: delete [] blah;
1,108,029
1,108,037
How i am able to use string without #include<string>?
It is given in the STL reference that string class is in string header,then without including the header how the following program is running without an error?? #include<iostream> using namespace std; int main() { string s; cin>>s; cout<<"string entered is : "<<s; } I am using a g++ complier on ubuntu machine.
Perhaps because iostream itself includes string in that compiler's implementation of the libraries. But this is not the case in other library implementations, e.g. Microsoft's VC++ doesn't allow this. You shouldn't rely on that kind of implicit inclusion, as it varies from compiler to compiler, and even from version to version (I'm currently trying to build some old std:: c++ code in Visual Studio 2010 and there's been at least one extra include I've had to put in.)
1,108,105
1,108,118
Condition order in while loop
First of all, before I begin, I am using VC++ 2008 professional, running an Intel core2 on windows OS. I also know that this code will NEVER be executed on anything other than a core2/corei7 running Windows. I have a while loop with 2 conditions that looks something like this: note: this is a much simplified version. while((a != b) && (array[a] < c)) If the first condition (a != b) generates a false, will the second condition even be evaluated? or will the loop just terminate right there? I did a few tests and it seems that it is indeed true. However, here is the catch. When and if first condition evaluates false, the second condition WILL generate an access violation if it is evaluated. However, from what i can see, once the first condition is evaluated as false, the program doesn't bother to evaluate the second condition and quits the loop, thus saving me. The problem is that I can't quite get rid of the access violation problem without making my very nice and neat code suddenly blow up on me. However, due to the little "bug" (i know it's a compiler optimization, not a bug), I seem to be able to get away from it. I also know this is probably not good programming practice to do, but to be honest, in my situation, if it works, I'm already ahead of the game. My question is, will this "bug" or programming malpractice come back and bite me some day? Even when considering that I tested the hell out of this section and WILL ONLY EVER USE IT THIS ONE TIME?
The second condition will not be evaluated unless the first one has been evaluated to true. You can count on this. Millions lines of code work because this is how C and C++ do short-curcuit logical expressions evaluation. You can use it and count on it. If the first expression evaluates to false the second will not even start evaluating.
1,108,203
1,109,021
I18n C++ hello world with plurals
Complete C++ i18n gettext() “hello world” example has C++ code that works for a simple fixed string. I am now looking for an example program that works with plurals. This example code displays six lines. Only one is correct in English. It does not handle the plurals correctly. cat >helloplurals.cxx <<EOF // hellopurals.cxx #include <libintl.h> #include <locale.h> #include <iostream> #include <stdio.h> int main (){ setlocale(LC_ALL, ""); bindtextdomain("helloplurals", "."); textdomain( "helloplurals"); for (int ii=0; ii<5; ii++) printf (gettext("Hello world with %d moon.\n"), ii); } EOF g++ -o helloplurals helloplurals.cxx ./helloplurals GNU gettext() for plural forms describes various ways that languages handle plurals for example: Korean - no pluals English - two forms, singular used for one only French - two forms, singular used for zero and one Polish - three forms, special case for one and some numbers ending in 2, 3, or 4 My expectation is that the code will be able to work (given message catalogs) specifically for all of the above cases and several more variations not listed here. The correct output when it is executed with English would be: Hello world with 0 moons. Hello world with 1 moon. Hello world with 2 moons. Hello world with 3 moons. Hello world with 4 moons.
I'm not sure what you want. If it is slight modification of your example that give your wanted output, just replace the printf line by printf(ngettext("Hello world with %d moon\n", "Hello world with %d moons\n", ii), ii); but as it is a trivial modification of unwind's answer and the gettext documentation has the very similar example, printf (ngettext ("%d file removed", "%d files removed", n), n); I wonder if it is really what you wanted. If you want to use gettext with a more C++ syntax, you'll have to look for libraries like Boost::Format.
1,108,273
1,108,297
Is there a better way to pass command line arguments to my programs in VC++?
I'm writing a program in C++ and it takes some command line arguments. The only way I know to pass command line arguments in VSC++ is to open up the properties and navigate to the command line argument field and enter them in, then run it. That's not exactly streamlined if I want to pass in different arguments each time I run it. The other option is to just open up a command prompt in the directory where the executable is placed and to run it from the command line there, but then if I want to use the debugger I have to attach it and that's a pain too. Is there a better way to do this?
If its just for quick testing or whatever, you could just create local variables in your main method instead of passing arguments in. Makes it a lot quicker/easier to change them.
1,108,360
1,108,525
delete a NULL pointer does not call overloaded delete when destructor is written
class Widget { public: Widget() { cout<<"~Widget()"<<endl; } ~Widget() { cout<<"~Widget()"<<endl; } void* operator new(size_t sz) throw(bad_alloc) { cout<<"operator new"<<endl; throw bad_alloc(); } void operator delete(void *v) { cout<<"operator delete"<<endl; } }; int main() { Widget* w = 0; try { w = new Widget(); } catch(bad_alloc) { cout<<"Out of Memory"<<endl; } delete w; getch(); return 1; } In this code, delete w does not call the overloaded delete operator when the destructor is there. If the destructor is omitted, the overloaded delete is called. Why is this so? Output when ~Widget() is written operator new Out of Memory Output when ~Widget() is not written operator new Out of Memory operator delete
I remember something similar on operator delete a while ago in comp.lang.c++.moderated. I cannot find it now, but the answer stated something like this .. Unfortunately, the language specification is not sufficiently clear on whether the control should go into the overloaded 'operator delete' when the delete-expression is invoked on the null-pointer of corresponding type, even though the standard does say that delete-expression on null-pointer is a no-op. And James Kanze specifically said: It's still the responisiblity of operator delete (or delete[]) to check; the standard doesn't guarantee that it won't be given a null pointer; the standard requires that it be a no-op if given a null pointer. Or that the implementation is allowed to call it. According to the latest draft, "The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect." I'm not quite sure what the implications of that "is one supplied in the standard library" are meant to be---taken literally, since his function is not one provided by the standard library, the sentence wouldn't seem to apply. But somehow, that doesn't make sense I remember this becoz i had a similar prob sometime back and had preserved the answer in a .txt file. UPDATE-1: Oh i found it here. Also read this link defect report. So, the answer is Unspecified. Chapter 5.3.5/7.
1,108,537
1,108,557
How to import a tlb and a namespace in c++ at runtime when some condition meets?
Generally we import a tlb file at the starting of the program like #include < stdio.h > #import " sql.tlb " But i need to import a tlb file when certain condition meets in the middle of the program how can i do this. to load dll there is LoadLibrary() but to load tlb can i use LoadLibrary(). Since tlb is generated by using .dll?
You can load a type library at runtime using LoadTypeLib. ITypeLib *ptlib; LoadTypeLib("sql.tlb", &ptlib); What you do then with ptlib is kind of up in the air as you don't really say what you are trying to do with it. ptlib is an object supporting the ITypeLib interface. It has methods which you can call to enumerate and iterate the types in the type library. Normally you use it in combination with the other interfaces like ITypeInfo and so on. I found a fuller tutorial style document here. Also, this link here has some more detail, also it shows the header file and link library you need to use. Header oaidl.h, oaidl.idl Library oleaut32.lib, uuid.lib Windows Embedded CE Windows CE 2.0 and later Windows Mobile Windows Mobile Version 5.0 and later
1,108,682
1,108,738
type traits specialization
template<typename T> class vec3 { public: typename T type_t; T x; T y; T z; }; template<typename T> struct numeric_type_traits_basic_c { typedef T type_t; typedef T scalar_t; }; template<typename T> struct numeric_type_traits_vec3_c { typedef T type_t; typedef typename T::type_t scalar_t; }; typedef numeric_type_traits_basic_c<int> int_type_traits; typedef numeric_type_traits_vec3_c< vec3<int> > vec3_int_type_traits; This is type traits for scalar and vector, the only difference is that the scalar type, for a vector, is the type of its element. Works fine. But I'd really like to be able to use the same name for those two classes. template<typename T> struct numeric_type_traits_c { typedef T type_t; typedef ????? scalar_t; }; I know this is possible to do so if the class is explicitly specialized for each type I need: int, float, vec3, vec3... That's a lot of duplication... How can I keep the simplicity of the first bit of code but have the same class name at the same time?
This is the syntax for partial class template specialisation: template<typename T> struct numeric_type_traits // basic template { typedef T type_t; typedef T scalar_t; }; template<typename T> struct numeric_type_traits< vec3<T> > // partial specialisation for vec3's { typedef vec3<T> type_t; typedef T scalar_t; }; And so on, e.g.: template <typename T, typename T_Alloc> struct numeric_type_traits< std::vector<T,T_Alloc> > // part. spec. for std::vector { typedef std::vector<T,T_Alloc> type_t; // deal with custom allocators, too typedef T scalar_t; };
1,108,709
1,109,070
Solve boost.thread compilation error with Metrowerks compiler
I'm trying to use boost.thread with metrowerks codewarrior 5.5.3; in the header thread.hpp, I get the error that he's redefining thread::thread_data: class BOOST_THREAD_DECL thread { private: ... template<typename F> struct thread_data: detail::thread_data_base { F f; thread_data(F f_): f(f_) {} thread_data(detail::thread_move_t<F> f_): f(f_) {} void run() { f(); } }; ... }; template<typename F> struct thread::thread_data<boost::reference_wrapper<F> >: detail::thread_data_base { F& f; thread_data(boost::reference_wrapper<F> f_): f(f_) {} void run() { f(); } }; I see that, in effect, thread::thread_data seems to be declared twice. What C++ feature is used there? How can I overcome that compiler deficiency?
The second instance is a partial specialization of the template class, this is valid C++ and should not result in a redefinition error. I've had problems with such features in a metrowerks compilers in the past too though, more specifically, when using template template parameters with default values, the compiler would never compile it. My workaround was rather easy, don't provide a default value... (1) If I were you I'd try adding a full specialization for your specific type, and hope the compiler uses some different compile path for those and gets you past this.... (this is just a wild guess, I don't have/use a metrowerks compiler these days) typedef boost::function< void () > MyThreadFunction; // or whatever you need template <> struct thread::thread_data<boost::reference_wrapper< MyThreadFunction > >: detail::thread_data_base { .... }; (1) To be honest, this was many years ago, I don't think any compiler compiled templates fully back then.
1,109,446
1,109,457
C++: generate gaussian distribution
I would like to know if in C++ standard libraries there is any gaussian distribution number generator, or if you have any code snippet to pass. Thanks in advance.
The standard library does not. Boost.Random does, however. I'd use that if I were you.
1,109,522
1,109,527
How to (fast) fill a CListCtrl in C++ (MFC)?
in my application I have a few CListCtrl tables. I fill/refresh them with data from an array with a for-loop. Inside the loop I have to make some adjustments on how I display the values so data binding in any way is not possible at all. The real problem is the time it takes to fill the table since it is redrawn row by row. If I turn the control invisible while it is filled and make it visible again when the loop is done the whole method is a lot faster! Now I am looking for a way to stop the control from repainting until it is completely filled. Or any other way to speed things up.
Look into the method SetRedraw. Call SetRedraw(FALSE) before starting to fill the control, SetRedraw(TRUE) when finished. I would also recommend using RAII for this: class CFreezeRedraw { public: CFreezeRedraw(CWnd & wnd) : m_Wnd(wnd) { m_Wnd.SetRedraw(FALSE); } ~CFreezeRedraw() { m_Wnd.SetRedraw(TRUE); } private: CWnd & m_Wnd; }; Then use like: CFreezeRedraw freezeRedraw(myListCtrl); //... populate control ... You can create an artificial block around the code where you populate the list control if you want freezeRedraw to go out of scope before the end of the function.
1,109,564
1,109,590
Intercept windows open file
I'm trying to make a small program that could intercept the open process of a file. The purpose is when an user double-click on a file in a given folder, windows would inform to the software, then it process that petition and return windows the data of the file. Maybe there would be another solution like monitoring Open messages and force Windows to wait while the program prepare the contents of the file. One application of this concept, could be to manage desencryption of a file in a transparent way to the user. In this context, the encrypted file would be on the disk and when the user open it ( with double-click on it or with some application such as notepad ), the background process would intercept that open event, desencrypt the file and give the contents of that file to the asking application. It's a little bit strange concept, it could be like "Man In The Middle" network concept, but with files instead of network packets. Thanks for reading.
The best way to do it to cover all cases of opening from any program would be via a file system filter driver. This may be too complex for your needs though.
1,109,602
1,110,474
Using Protocol Buffers to send icons/small images
I have a simple question about std::string and google's protocol buffers library. I have defined a message like so: message Source { required string Name = 1; required uint32 Id = 2; optional string ImplementationDLL = 3; optional bytes Icon = 4; } I want to use the Icon field to send an image, it most probably will be a png image. After feeding this to the protobuf compiler i got something like this to access/manipulate the Icon field. inline bool has_icon() const; inline void clear_icon(); static const int kIconFieldNumber = 4; inline const ::std::string& icon() const; inline void set_icon(const ::std::string& value); inline void set_icon(const char* value); inline void set_icon(const void* value, size_t size); inline ::std::string* mutable_icon(); the std::string* mutable_icon() function is giving me a headache. It is returning a std::string but i believe strings can not hold binary data ! or can they ? i can use set_icon(const void*, size_t) function to put binary data, but then how do i get it on the other side ? i think std::string might be able to hold binary data, but how ????
the answer to this question: How do you construct a std::string with an embedded null?
1,109,833
1,110,131
Accessing Function Variable After calling it while Being in main()
I want to access variable v1 & v2 in Func() while being in main() int main(void) { Func(); int k = ? //How to access variable 'v1' which is in Func() int j = ? //How to access variable 'v2' which is in Func() } void Func() { int v1 = 10; int v2 = 20; } I have heard that we can access from Stack. But how to do. Thank you.
You're in C/C++ land. There are little you cannot do. If this your own code, you shouldn't even try to do that. Like others suggested: pass a output parameter by reference (or by pointer in C) or return the values in a struct. However, since you asked the question, I assume you are attempting to look into something you only have binary access to. If it is just an one time thing, using a debugger will be easier. Anyway, to answer your original question, try the following code. You have to compile it in for x86 CPU, with optimization and any stack debug flag turned off. void f() { int i = 12345; int j = 54321; } int main() { int* pa = 0; int buf[16] = {0}; f(); // get the stack pointer __asm { mov dword ptr [pa],ESP } // copy the stack, try not to do anything that "use" the stack // before here for (int i = 0; i < 16; ++i, --pa) { buf[i] = *pa; } // print out the stack, assuming what you want to see // are aligned at sizeof(int) for (int i = 0; i < 16; ++i) { std::cout << i << ":" << buf[i] << std::endl; } return 0; }
1,109,995
1,110,101
Do getters and setters impact performance in C++/D/Java?
This is a rather old topic: Are setters and getters good or evil? My question here is: do compilers in C++ / D / Java inline the getters and setter? To which extent do the getters/setters impact performance (function call, stack frame) compared to a direct field access. Besides all the other reasons for using them, I would like to know whether they are supposed to affect the performance besides being a good OOP practice.
It depends. There is no universal answer that is always going to be true. In Java, the JIT compiler will probably inline it sooner or later. As far as I know, the JVM JIT compiler only optimizes heavily used code, so you could see the function call overhead initially, until the getter/setter has been called sufficiently often. In C++, it will almost certainly be inlined (assuming optimizations are enabled). However, there is one case where it probably won't be: // foo.h class Foo { private: int bar_; public: int bar(); // getter }; // foo.cpp #include "foo.h" int Foo::bar(){ return bar_; } If the definition of the function is not visible to users of the class (which will include foo.h, but won't see foo.cpp), then the compiler may not be able to inline the function call. MSVC should be able to inline it if link-time code generation is enabled as an optimization. I don't know how GCC handles the issue. By extension, this also means that if the getter is defined in a different .dll/.so, the call can not be inlined. In any case, I don't think trivial get/setters are necessarily "good OOP practice", or that there are "all the other reasons for using them". A lot of people consider trivial get/setters to 1) be a sign of bad design, and 2) be a waste of typing. Personally, it's not something I get worked up about either way. To me, for something to qualify as "good OOP practice", it has to have some quantifiable positive effects. Trivial get/setters have some marginal advantages, and some just as insignificant disadvantages. As such, I don't think they're a good or bad practice. They're just something you can do if you really want to.
1,110,125
1,110,172
Cost of passing an optional parameter to a method rather than computing it
I have a memory block that is divided into a series of location that can be retrieved and returned by client code. The method that returns locations back looks like this: void ReturnLocation(void *address) { int location = AddressToLocation(address); // I need the location here // some code DoSmthA(location); } void DoSmthA(int location) { // I need the address, but also the location void *address = LocationToAddress(location); // do something with the address DoSmthB(location); } void DoSmthB(int location) { // Again, I need the address, but also the location void *address = LocationToAddress(location); // do something with the address DoSmthC(location); // It may go on this way... } // ------------------------------------------------------ void* LocationToAddress(int location) { return (void *)((char *)this + HEADER_SIZE + (location * LocationSize)); } int AddressToLocation(void *address) { return (int)(((__int64)address - HEADER_SIZE - (__int64)this) / LocationSize); } My question is: should I pass only the location to the helper methods, or it is faster to pass each time the address too (and not compute it again and again): void DoSmthA(int location, void *address) { } or even better to use a struct like this: struct LocationInfo { int Location; void *Address; }; void DoSmthA(LocationInfo locInfo) { } This methods may be called million of times and I'm not sure if the operations to compute the address from the location (two additions and one multiplication) are faster or slower than passing a second parameter containing the address. Thanks in advance!
Profile it. Do what is actually faster in your case, on your compiler and with your code base. Not what was faster in my unrelated test, on my unrelated compiler. Passing an argument to a function is a pretty cheap operation. A stack push/pop, basically. Computing the location might be very fast, if the division can be optimized away (depends on the value of LocationSize, and whether it is known at compile-time). So try both, see which is faster in the real world. CPU's are complex beasts, and performance is not trivial.
1,110,418
1,110,485
Do typedefs of templates preserve static initialization order?
Within the same compilation unit, the C++ standard says that static initialization order is well defined -- it's the order of the declarations of the static objects. But using the Sun Studio 12 compiler I'm encountering unintuitive behavior. I've define a templated class helper<T> which contains a static member _data of type T and a static member function that uses _data called foo. In my .cpp file I have this above main(): struct A { /* some definition */ }; typedef helper<int> s0; typedef helper<A> s1; Notice that the typedef for helper<int> comes before the typedef for helper<A>. Thus according to the standard I would expect that helper<int>::_data will be constructed before helper<A>::_data (remember _data is a static member). On GCC this is the case, on Sun it is not. This is problematic because A's constructor uses helper<int>::_data. I only have one compilation unit, with no earlier potential instantiation of helper<A>, so I thought the order should be well defined. Is this a Sun compiler bug, or does the typedef not constitute a definition/instantiation technically? What I mean is, is the Sun compiler's behavior allowed by the standard? I have the following main(): int main() { //Swapping the order of these has no effect on Sun s0::foo(); s1::foo(); } There are no other uses of s0 or s1.
Within the same compilation unit, the C++ standard says that static initialization order is well defined -- it's the order of the declarations of the static objects. In your shown code you have no declaration of a static data member. You have a declaration of a typedef-name. These have nothing to do with that, and don't influence any order. You probably think along this way: If i make that typedef declaration, it will instantiate helper<int>, and thus instantiate its static data member declaration first. The problem is, that line does not cause an instantiation of helper<int>. For that to happen, you would need an explicit instantiation or manage to make it instantiate it implicitly (creating an object of helper<int> for example, or using it as a nested name specifier as in helper<int>::... and explicitly referencing the static member - otherwise, creation of it is omitted). But there is a much deeper problem. The order is not the declaration of the static data-members. The order is their definition. Consider the following struct C { C() { printf("hey\n"); } }; struct A { static C a; static C b; }; C A::b; C A::a; In this code, b is created before a, even though a is declared before b. The following code prints 2 1: struct C { C(int n) { printf("%d\n", n); } }; template<int N> struct A { static C c; }; template<int N> C A<N>::c(N); // explicit instantiation of declaration and definition template struct A<2>; template struct A<1>; int main() { } But the following code prints nothing, unless you comment in the line in main. struct C { C(int n) { printf("%d\n", n); } }; template<int N> struct A { static C c; }; template<int N> C A<N>::c(N); // implicit instantiation of declarations A<2> a2; A<1> a1; int main() { // A<1>::c; A<2>::c; } I'm not actually sure what the correct output for this second snippet is. Reading the Standard, i can't determine an order. It says at 14.6.4.1 "Point of Instantiation": For a function template specialization, a member function template specialization, or a specialization for a member function or static data member of a class template, if the specialization is implicitly instantiated because it is referenced from within another template specialization [...]. Otherwise, the point of instantiation for such a specialization immediately follows the namespace scope declaration or definition that refers to the specialization. The point of instantiation of their definitions both appear immediately after the definition of main. Which definition is instantiated before the other definition seems to be left unspecified. If anyone knows the answer and khow other compilers behave (GCC prints 1 2 but with the order of the expressions in main swapped, prints 2 1), please let me know in the comment. For details, see this answer about static object's lifetime.
1,110,458
1,110,549
WinForms interthread modification
Whenever I want to modify a winform from another thread, I need to use ->Invoke(delegate, params) so that the modification occurs in the winform's own thread. For every function that needs to modify the gui, I need another delegate function. Is there some scheme which allows me to limit the number of delegate functions needed? I have a controller class which handles the whole gui in one spot, I've thought about reusing delegates but that smells badly. I think that my question can apply to all languages where winform can run
If you're using C# 3, you can use lambda, and in C# 2, use anonymous delegates. These simplify the syntax when there's no need to reuse the behavior. One thing I always do is to do the synchronization in the form code, not in the controller. The controller shouldn't be bothered with these sort of "plumbing" problems that are more specific to the technology than to the controller logic. public void ResetFields() { // use "delegate" instead of "() =>" if .Net version < 3.5 InvokeOnFormThread(() => { firstInput.Text = Defaults.FirstInput; secondInput.Text = Defaults.SecondInput; thirdChoice.SelectedIndex = Defaults.ThirdChoice; }); } // change Action to MethodInvoker for .Net versions less than 3.5 private void InvokeOnFormThread(Action behavior) { if (IsHandleCreated && InvokeRequired) { Invoke(behavior); } else { behavior(); } } As a practice, make all public methods in your form call "InvokeOnFormThread." Alternately, you could use AOP to intercept public method calls on your form and call "InvokeOnFormThread," but the above has worked well enough (if you're consistent and remember to always do it on public methods on the form or UserControls).
1,110,658
1,110,692
Trying to keep age/name pairs matched after sorting
I'm writing a program where the user inputs names and then ages. The program then sorts the list alphabetically and outputs the pairs. However, I'm not sure how to keep the ages matched up with the names after sorting them alphabetically. All I've got so far is... Edit: Changed the code to this - #include "std_lib_facilities.h" struct People{ string name; int age; }; int main() { vector<People>nameage; cout << "Enter name then age until done. Press enter, 0, enter to continue.:\n"; People name; People age; while(name != "0"){ cin >> name; nameage.push_back(name); cin >> age; nameage.push_back(age);} vector<People>::iterator i = (nameage.end()-1); nameage.erase(i); } I get compiler errors for the != operator and the cin operators. Not sure what to do.
Rather than two vectors (one for names, and one for ages), have a vector of a new type that contains both: struct Person { string name; double age; }; vector<Person> people; edit for comments: Keep in mind what you're now pushing onto the vector. You must push something of type Person. You can do this in a couple of ways: Push back a default constructed person and then set the name and age fields: people.push_back(Person()); people.back().name = name; people.back().age = age; Give Person a constructor that takes a name and an age, and push a Person with some values: struct Person { Person(const string& name_, double age_) : name(name_), age(age_) {} string name; double age; }; people.push_back(Person(name, age)); Create a Person, give it some values, and push that into the vector: Person person; person.name = name; person.age = age; people.push_back(person); Or more simply: Person person = { name, age }; people.push_back(person); (thanks avakar)
1,110,682
1,111,975
Extending PHP with C++?
I have a performance intensive routine that is written in PHP that I'd like to port to C++ for a performance increase. Is there any way to write a plugin or extension or something using C++ and interface with it from PHP? WITHOUT manually editing the actual PHP source?
I've written a PHP plugin in C++ with the help of SWIG. It's doable, but it may take a while to get used to the SWIG-compilation cycle. You can start with the SWIG docs for PHP. Update As @therefromhere has mentioned, I greatly recommend that you get the book Extending and Embedding PHP. There is almost no documentation to be found online (at least there wasn't in late 2008, early 2009 when I did my PHP plugin). I had to rely on the book for everything. Although sometimes Google Code Search is helpful for finding sample code.
1,110,779
1,110,906
How C++ can import a DLL made in C#?
I have a DLL made in C#, this DLL contains some clases like Creator. I need to load this DLL and use Creator class in C++ unmanaged, so Is there some way to create that instance or must I load just the functions exposed? I need something like this: CreatorInstance->Init(); Is this posible?
John Fisher's approach using C++/CLI is by far the easiest means of handling this, but it is not the only means. The other three options are: 1) Use COM interop to wrap the .NET class via COM 2) You can host the CLR in your native, unmanaged application, and call into it. For details, see this article. 3) You can host the Mono runtime, and use it to call your managed code. For details on this, see this page. Option 2 and 3 are very similar, but IMO, 3 is easier than 2.
1,110,802
1,110,828
C++ Storing large data in std::list<> ..should I use reference counting?
How do people normally manage copying a list of large objects around? Here's my situation: Currently I have this: typedef std::vector<float> Image; and I'm storing it in a std::list<Image> lst; The Image.size() is quite large (each is ~3-5 MB). I'm passing (copying) the list around. Is it a correct understanding on my part that std::vector will copy each element by value? If so, the performance might be a bit awful due to excessive copying? What can I do to minimize copying? Should I instead store std::list<ImageRef> lst; where typedef boost::shared_ptr<Image> ImageRef; ? What's the elegant way of handling this kind of issue?
Objects larger than built-in types are most often way cheaper to pass around by reference then by value. So if your object is about 3 Meg big, and you need to pass it around, please don't copy it! All STL types use value semantics: they copy their content. Note that content may exist of pointers. In that case the pointers are copied, not what they refer to. It may even be a good idea to pass your image-list around by reference. Saves a lot of smart-pointer copying, so it saves a lot of reference-count management, and may save a lot of locks/unlocks.