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
3,251,305
3,251,650
How do I use SSE(1,2,3,4) optimizations?
I'm wondering if simply compiling my msvc project with sse/sse2 will have any effect. I do for example vector normalization and dot product but I do these wth math, not any specific function. Is there like sse_dot() and sse_normalize() that I should be using to actualyy take advantage, or will the compiler know? Thanks
As I understand it, using the sse2 compiler option will result in the compiler using the scalar not vector sse2 instructions in place of normal fpu code. I don't think it will do any vectorisation. The sse2 scalar stuff is quicker than fpu for sure. To use the vector unit you need to use either intrinsics directly ( xmmintrin.h ) or use 3rd party libs that do. If you're just doing simple vector/matrix stuff for rendering, the Bullet SDK has an sse optimised vector math lib that's not bad. IIRC the DirectX/XNAmath lib is sse optimised too. If neither of those take your fancy, Google should turn up a number of alternatives.
3,251,307
3,251,368
What's the best workflow to keep cpp files and header files in sync?
I'm trying to learn C++ for Qt development, and I'm a little scared of header files. What I'd like to know is, what's the best workflow for keeping *.cpp and *.h files synched? For example, is the norm to write the class file and then copy the relevant info over to the header? Sorry if this doesn't make any sense...I'm just looking for an efficient workflow for this. Thanks! Justin
For example, is the norm to write the class file and then copy the relevant info over to the header? While there is no single standard approach, its usually a good idea to: first think about the public interface put that in the header implement in the source file accordingly update the header if needed Jumping straight into the implementation can make for a painful refactoring later on.
3,251,336
3,251,366
Memory allocation of identical structs
So I was teaching my friend about pointers. While doing so, I noticed that the address of two identical structs are exactly back-to-back. struct Foo { int a; }; struct Bar { int b; }; Which allowed me to do this: Foo foo; foo.a = 100; Bar bar; bar.b = 100; Foo *pFoo = &foo; Bar *pBar = &bar; (pFoo+1)->a = 200; This overrides the value in bar.b and sets it to 200. Now, I'm not questioning the merits of doing such a thing- it will probably never see the light of day in a real program. I was just wondering, does the OS always allocate identical structs back-to-back? Provided there is enough memory space free in the given area.
No, not necessarily. It is possible that some architectures/compilers will align structures on boundaries such that there are different spacings between structs in an array and structs on the call stack. You're allocating on the call stack and treating them as a contiguous array, that's an unreliable assumption.
3,251,465
3,251,503
Correct implementation of Boyer Moore algorithm
I tried to use several implementations, but all of them had bugs. Search at SO gave me http://www-igm.univ-mlv.fr/~lecroq/string/node14.html - looks nice, but this implementation gave me wrong results - sometimes it doesn't found a string. I spent couple hours to find the bug. Following line looks fine: j += MAX(bmGs[i], bmBc[y[i + j]] - m + 1 + i); but y is char * and char is signed! It means that y[i + j] could be negative (what happens in one of my tests). My question is: Where to find correct implementation of Boyer Moore algorithm?
char isn't definitively signed or unsigned - it's unspecified, and left up to the implementation to define. If the algorithm depends on char being unsigned, then it should explicitly cast the input pointers to unsigned char (which is how the C standard library string handling functions are defined to work - all comparisons are done treating the characters in the string as unsigned char).
3,251,506
3,251,531
Compiling into executable file
I am currently writing a programming language in C/C++ as an exercise (but mostly for fun). At the moment it compiles into a list of commands that are then executed (kind of like a low-level API). Its working fantastically, however, I think it would be more exciting if instead of having a interpreter executable, having the language actually compile into a .exe file. I don't know if it is possible or how challenging this might be. I could not find any resources to help me with this. - Thanks in advance.
You could consider writing a frontend for LLVM (tutorial) or GCC (article from linux journal) - if thats still fun for you is a different question.
3,251,667
3,252,184
Find out which functions were inlined
When compiling C++ with GCC 4.4 or MSVC is it possible to get the compiler to emit messages when a function is inlined?
With g++, I don't think you can make g++ report that, but you can examine the resulting binary with any tool that shows symbols, nm for example: #include <iostream> struct T { void print() const; }; void T::print() const { std::cout << " test\n" ; } int main() { T t; t.print(); } ~ $ g++ -O3 -Wall -Wextra -pedantic -o test test.cc ~ $ nm test | grep print 0000000000400800 t _GLOBAL__I__ZNK1T5printEv 0000000000400830 T _ZNK1T5printEv vs #include <iostream> struct T { void print() const { std::cout << " test\n" ; } }; int main() { T t; t.print(); } ~ $ g++ -O3 -Wall -Wextra -pedantic -o test test.cc ~ $ nm test | grep print (no output from nm in the second case) EDIT: Also, profilers may be of use. gprof shows, on these two examples: 0.00 0.00 0.00 1 0.00 0.00 global constructors keyed to _ZNK1T5printEv 0.00 0.00 0.00 1 0.00 0.00 T::print() const vs. just 0.00 0.00 0.00 1 0.00 0.00 global constructors keyed to main
3,251,790
3,251,888
Getting "execute" permission for an area of memory
I am using C++, and would like to get the permission to execute on an area of memory. Is there a way I can do this? Right now when I just try to execute it, I get an access violation error.
On Windows the function is VirtualProtect, you'll want to pass in PAGE_EXECUTE_READWRITE to get execute permission. By default Windows does not allow memory. It's called Data Execute Prevention (DEP).
3,251,930
3,251,955
*(c++) operator order
What precedence rules apply in parsing this expression: *(c++); // c is a pointer. Thank you. well, I tried the following x = *c; c++; x = (*c++); x = *(c++); They appear to be equivalent
the ++ operator has not so much to do with precedence, but tells to increment only after evaluation. So *c will be "returned" and then c will be incremented. Please don't confuse precedence with order of execution!
3,251,983
3,256,743
What is the syntax for an array type?
Is it type[]? For example, could I have T<int[]>; for some template T.
There are two syntaxes to denote array types. The first is the type-id syntax and is used everywhere where the language expects a compile time type, which looks like: T[constant-expression] T[] This specifies an array type that, in the first form, has a number of elements given by an integer constant expression (means it has to be known at compile time). In the second form, it specifies an array type with an unknown number of elements. Similar to class types that you declare without a body, such an array type is said to be incomplete, and you cannot create arrays of that type // not valid: what size would it have? int a[]; You can, however, specify that type. For example you may typedef it typedef int unknown_int_array[]; In the same manner, you may specify it as a template type argument, so the answer to your question is yes you can pass such a type specifier to a template. Notice that i talk about specifiers here, because the form you use here is not the type itself. The second way is using the new-type-id syntax which allows denoting runtime types by having non-constant bounds T[expression] This allows passing variables as element count, and also allows passing a zero. In such a case, a zero element array is created. That syntax is only usable with the new operator for supporting dynamic arrays.
3,252,238
3,252,277
Light weight container around const char* & length without copying the data
I have a underlying API that passes a const char* and a length: foo(const char* data, const uint32_t len); I'd like to wrap this data/length in a light weight container that can be iterated and has the ability to be randomly accessed but not make a copy (e.g. like a vector). What is the best way to achieve this? The const char* data is not necessarily a 'string'; it may contain NULL's throughout. I am using STL and Boost. I've seen boost::as_array<> and as_literal<> -- is one of these appropriate here?
It would be easy to make such a class. Something like this: template <class T> class array_ref { public: // makes it work with iterator traits.. typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef T* iterator; typedef T& reference; typedef const T* const_pointer; typedef const T* const_iterator; typedef const T& const_reference; public: array_ref(T *p, size_t n) : data_(p), len_(n) {} // iteration iterator begin() { return data_; } iterator end() { return data_ + len_; } const_iterator begin() const { return data_; } const_iterator end() const { return data_ + len_; } // access reference operator[](size_t n) { return data_[n]; } reference at(size_t n) { return data_[n]; } const_reference operator[](size_t n) const { return data_[n]; } const_reference at(size_t n) const { return data_[n]; } // capacity size_t size() const { return len_; } bool empty() const { return size() == 0; } // raw access T* data() const { return data_; } // etc... private: T* data_; size_t len_; }; This looks like a bunch of code, most of it isn't strictly necessary. However, since it is a template the compiler will only generate code for the methods used. And the actual class itself only uses space for the pointer and the length members. But in the end, this really isn't much of a gain. Since pointers themselves are nice pointers, I'd probably just use raw pointers here.
3,252,248
3,252,603
Calling member functions from DLL (AI library for games)
My problem is this: I am trying to implement a C++ library which can call functions in the base EXE. I am trying to have a minimum amount of code on the EXE side to get the functionality to work. At the moment I have DLL-side entities which are created by DLL function calls. These entities hold a container of "actions" which is just a map of strings (action names) and pointers to the EXE-side functions. Each of these functions return void and take as an argument a container of boost::any. The EXE then just has to call an update function in the DLL every tick and the DLL does the thinking and calls whichever "action" is appropriate. This is working fine for normal functions. How can I get this to work for member functions also? (Where the DLL has no idea what kind of object the function resides in.) Please let me know if my question is too vague and I will try to clarify. Thanks!
What you want is boost::bind and boost::function. The dll side map would have boost::functions instead of function pointers. The client would pass a bound object using boost::bind which could be anything you want. DLL Side: typedef boost::function<void ()> CallbackFunctionType; CallbackFunctionType gCallback; void SetCallback(CallbackFunctionType& callback) { gCallback = callback; } void Update { if (condition == true) { gCallback(); } } And on the Client side: class CallbackClass { void CallbackMember(); }; CallbackClass x; dllInterface->SetCallback(bind(&CallbackClass::CallbackMember, &x)); dllInterface->Update(); Hope this is what you were looking for. bind member
3,252,410
3,252,443
Trouble with 'extern' Keyword
I have a set of global variables and a method in a cpp file. int a; int b; int c; void DoStuff() { } in the header file I have declared them explicitly with the extern keyword. My problem is when I include the header file in another C++ file, I can't use the external variables and the method. It's giving a linker error saying error LNK2001: unresolved external symbol for the methods and variables. What have I done wrong here?? PS: DoStuff() method populates the variables. All the header files and cpp files are in the same project folder. Thank You!
Try this Define those variables inside your header instead of just declaring them. extern int x; is just a declaration(not a definition) Simple example a.cpp int a,b,c; //definition void doStuff(){ } b.cpp extern int a,b,c; //extern keyword is mandatory void doStuff(); //extern keyword is optional because functions by default have external linkage int main() { doStuff(); }
3,252,762
3,252,841
Porting C++ code to Silverlight
I have C++ application which has UI developed using MFC, does some networking using sockets (using boost libraries) and some image processing. I want to move this application into Silvelight framework (I can use 4.0 if required) so that it can be used over the internet easily. Here I want to move all parts (UI + networking etc) in to C# but keep the image processing code in unmanaged C++ only. I don't know .NET framework yet, but whatever I have read so far suggests that it is not possible to call the unmanaged code from a silvelight web application. Is my understanding correct? Can something be done to achieve what I am trying to do? Also, if somebody has some suggestions on how to go about porting the code?
Silverlight 4 supports COM when running in trusted mode. So, tecnically you could have Silverlight call your c++ library using COM. The main problem I see is on deployment and I don't think it's a good idea. Also, remember that Silverlight can run on Macs but COM is Windows only. What you could do is to have the image processing happening on the server, but then you can run into scalability issues. Transfering large amounts of data between client and server can become an issue. UI response should probably be closely evaluated too. Regarding porting the code, well, you are most certain looking at a complete rewrite.
3,252,909
3,252,933
Is C++ name mangling (decoration) deterministic?
I hope to LoadLibrary on an unmanaged C++ DLL with managed code, and then call GetProcAddress on extern functions which have been mangled. My question is are the mangled names you get from a C++ compiler deterministic? That is: Will the name always by converted to the same mangled name, if the original's signature hasn't changed?
It isn't specified by the standard, and has certainly changed between versions of the same compiler in my experience, though it has to be deterministic over some fixed set of circumstances, because otherwise there would be no way to link two separately compiled modules. If you're using GetProcAddress, it would be far cleaner to export the functions as extern "C" so their names are not mangled.
3,253,046
3,253,065
Implementing the clrscr() function to understand its working
I am trying to make the copies of the builtin functions and adding a x to their name so i can understand each functions working.While writing a function for clrscr() i am confused about how it works.Does it use 2 nested loops and print (" ") i.e space all over the screen or it prints("\n") over the screen?Or what? I tried this: #include<stdio.h> #include<conio.h> void main(void) { printf("press any key to make clrscr() work"); getch(); for(int i=0;i<50;i++) { printf("\n"); } // to make the screen come to 1,1 gotoxy(1,1); getch(); }
clrscr() implementation may depend on the environment your console application runs. Usually it sends the ClearScreen control character (0x0C) to the console driver, that actually clears the screen. The driver knows about character space to clear as well as all attributes (blink, underline,...) to reset. If you dont want the driver to handle 0x0C, you can mimic this with 50 times calling printf("\n"). but calling 50x80 calling poutchar(' ') is not similar to calling clrsrc(), since the cursor will be advanced by one what may put it in the next line after scrolling the screen content. Further you should regard, that the behaviour of the screen depends on the implementation. When the cursor position is in the right column and you output one character the cursor position may stay at the right edge or it may cause a new line. Whe you cursor position is in the lower right corner the next character may cause a new line including scrolling the screen content by one line. The best way would be to imaging what clrscr() would do and let it make it's job.
3,253,107
3,255,534
How to rotate monochrome images in GDI+
I am trying to rotate a monochrome Bitmap in GDI+ using RotateFlip method. When i try to rotate it by 90/270 I get a wrong image or the application crashes. But when I try to rotate it by 180 degrees it works fine. Hence I am now rotating all monochrome bitmaps twice through 180 and then rotating it again by the angle required. Is this a known bug in GDI+? Any other good workarounds would be appreciated.
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Matrix m = new Matrix(); Bitmap bmp = new Bitmap("myfile"); m.Rotate(30); e.Graphics.Transform = m; e.Graphics.DrawImageUnscaled(bmp);
3,253,246
3,253,462
What is good way to maintain versions in a C++ project?
We have a C++ project, which has hundreds of SVN revisions every month. Sometimes we need to increment a minor digit in a version number, changing it from, say, 1.6 to 1.7. We do it once per month approximately. What is a correct approach to do it? We want to save/maintain information about changes made in every new version, and we want to have some sort of release notes. Please, give us some suggestions or links. Thanks! ps. Sorry if the question is too vague. pps. I see that I need to clarify the question a bit. I'm not interested about how should I name versions. I'm interested how technically I should maintain version numbers in C++ code.
For the 'release note' tracking, I suggest using some external tool to track tasks. You can assign functionalities and in many cases associate issue numbers with specific subversion commits. I have used ClearQuest and Jira for this in the past but there are opensource/free tools out there you can try. If you decide to follow this path, make sure that each commit is tagged with the issue number, and that all issues are tagged with specific software version numbers ('resolve in'). Open an issue for each found bug. For each new release make a branch, merge the commits that are tagged with issues to be resolved in that release, and test --sometimes you can have conflicts with changes that are not meant for this release but rather a later one--. After the branch has been merged, build and tested, make a release tag from it. Generating the release documentation is then quite simple: all the information is present in your issue tracker associated to the current release number. I have also seen in the past the work performed the other way around: open a branch for development, perform separate changes in the branches and merge them back to the trunk, with each merge containing a descriptive text of the whole change --new functionality or bug being fixed. Create release tags from the trunk directly when needed. Getting the changes from two releases is just reading the logs from the changes to trunk from the one release to the next. Both solutions share the same type of problems: merging is trivial in theory, but not so in practice. In the first case, when pulling code from trunk to the release branch you will have to handle merge problems when intermediate commits are not to be pulled. When developing in branches and merging back to trunk, before each merge to trunk you will have to merge first trunk changes into your branch. Build, test and then merge back to trunk. Most subversion books will recommend the second path, but in some circumstances the first one (which is the one I am currently using makes sense). In our case we have a whole set of automated tests that run for over 20 hours, having all code written directly to the trunk means that you only need the automated tests to run there. If we were branching for each change, either we would leave the branches untested until we merged back --bad idea-- or else we would have to throw a lot more hardware in for testing and slow down development quite a bit.
3,253,349
3,253,371
code from hackers delight
/* Converts the unsigned integer k to binary character form with a blank after every fourth digit. Result is in string s of length 39. Caution: If you want to save the string, you must move it. This is intended for use with printf, and you can have only one reference to this in each printf statement. */ char * binary(unsigned k) { int i, j; static char s[40] = "0000 0000 0000 0000 0000 0000 0000 0000"; j = 38; for (i = 31; i >= 0; i--) { if (k & 1) s[j] = '1'; else s[j] = '0'; j = j - 1; k = k >> 1; if ((i & 3) == 0) j = j - 1; } return s; } i have tested it in c++ #include <iostream> using namespace std; char *binary(unsigned k){ int i, j; static char s[40]="0000 0000 0000 0000 0000 0000 0000 0000"; j=38; for (i=31;i>=0;i--){ if (k & 1) s[j]='1'; else s[j]='0'; j=j-1; k=k>>1; if ((i & 3)==0) j=j-1; } return s; } int main(){ unsigned k; cin>>k; *binary(k); return 0; } but what value does k have ? for example i have entered 127 but it return 0 why?
You're throwing away the return value of the function binary : *binary(k); binary returns a char * which is (as the documentation says) "intended for use with printf", but you aren't doing anything with this string. Your program 'returns' 0 because that's what you're explicitly returning with your last line of code! Try changing *binary(k); to cout << binary(k); and you should at least see some output.
3,253,590
3,253,662
What is the meaning of this code
I found following code in one of the frameworks we are using, if (nValue + 0.01 > nLimit) nValue = nValue - 0.01; if (((nValue+1) / (int)(nValue+1)) == 1) sprintf(szValue, "%0.0f", nValue); else sprintf(szValue, "%0.2f", nValue); what is the meaning of this code
I'd suspect that the first part is a mistaken attempt to ensure nValue does not exceed nLimit. It possibly should be if (nValue + 0.01 > nLimit) nValue = nLimit - 0.01; In other words, if nValue is closer than 0.01 to the limit make it 0.01 less than the limit To explain how the second part works, it involves dividing a floating point number by the integer part of the number. If the number is an integer then the result will be 1 e.g. 23.00 / 23 = 1 - It's an integer 23.05 / 23 = 1.002 - It's not an integer Adding 1 to each side is (as ufukgun noticed) to prevent devide by zero, but the devision is redundant as you could simply compare the float with the int if (nValue == (int)nValue)
3,253,866
3,254,015
What's the clue to make stringstream write binary?
What I'm trying to do is, make the class message serialize and deserialize it's self. Not into or from a file, but into or from a binary sequence as a string or cstring. Message.h: class Message { private: int message_id; int sender_id; std::string sender_data; Message (); public: Message (int id, std::string data); virtual ~Message (); virtual const char* Serialize (); virtual void Deserialize (const char* buf); virtual void Print (); }; Message.cpp: const char* Message::Serialize () { char buf[1024]; // This will work somehow. I get the object and then glibc // detects double free or corruption, because i write into buf // and not into a file. // std::ofstream out_stream(buf, std::ios::binary); // out_stream.write((char *)this, sizeof(*this)); // out_stream.close(); // Why this won't work? I didn't get it. std::stringstream out_stream(buf, std::ios::binary); out_stream.write((char *)this, sizeof(*this)); std::string str(buf); std::cout << str << std::endl << buf << std::endl; return str.c_str(); } void Message::Deserialize (const char* buf) { std::ifstream in_stream(buf, std::ios::binary); in_stream.read((char*)this, sizeof(*this)); in_stream.close(); } Main: #include "Message.h" int main (int argc, int argv[]) { Message msg1(12345, "some data"); Message msg2(12346, "some other data"); msg1.Print(); msg2.Print(); msg2.Deserialize(msg1.Serialize()); msg1.Print(); msg2.Print(); return 0; } Output: Msg: 0 Client: 12345 Data: some data Msg: 1 Client: 12346 Data: some other data Msg: 0 Client: 12345 Data: some data Msg: 1 Client: 12346 Data: some other data Any suggestions? Greetings Mesha
Generally you serialize an object by serializing all it's data-members. Hence this will not work as expected: out_stream.write((char *)this, sizeof(*this)); This does not serialize data dynamically allocated data. If you have a lot of serialization/deserialization to do, take a look at Boost.Serialization. Even if you do not want to use it, reading the docs can give you some good understanding on how this is done. If guess correctly, your code is intended to check if the serialization works as intended. This would be better achieved by passing the stream you want to serialize to as a parameter to the serialization-method: std::string Message::Serialize(ostream & sink); Also, you should use str::string for strings, not const char *.
3,254,020
3,266,131
BDM elf file vs normal elf file
Whats the advantage that the BDM ELF file has over the normal ELF file in terms of memory used? I know the following things about both: BDM ELF file could be used for debugging through any debugger tools like Trace32 by plugging in JTAG. The normal ELF file also can be used for debugging purpose, provided we have the corresponding FLS file (Flash file) that has to be flashed into the ROM area of the ECM. BDM ELF files are loaded into the RAM area of the ECM (Electronic Control Module) whereas the normal ELF files and their corresponding FLS are loaded into the ROM are of the ECM. The ELF files (either BDM or the normal one) are not loaded entire into the memory of ECM (I understood this from the size of the ECM memory that we use for loading the ELF which is in terms of KB's compared to the huge size of the ELF which is in terms of MB's), some part of the ELF file (symbols like types, variabled and functions etc) are kept with the Trace32 memory. The above were my major understandings of using the ELF's, I know that you people will help me in correcting myself in case I have interpreted anything wrongly. My expectation is to understand how is BDM ELF file content distributed among the Trace32 debugger and the ECM memory, how is either of the ELF formats advantageous than one another as both are used for debugging purpose only. Please note that when it come to releasing the application/software to the customer, we release in terms of the FLS format which the customer flash into their ECM. Please let me know if you need anymore information to proceed with answering my question.
OK, I'll try again: How is BDM ELF file content distributed among the Trace32 debugger and the ECM memory? The ELF file can hold debugging symbol information (relating memory locations and registers to functions and variables), which the trace32 uses to help you debug. This symbol information is held in trace32 and it is used to decode the BDM output from the chip (register values, mostly) and provide useful information beyond bare assembly. How is either of the ELF formats advantageous than one another as both are used for debugging purpose only? This depends on your debugging tool and your development tool chain. As I said in my other answer, ELF is just a standard format. Weather it is used for line programming depends on what your development tool does at link time. Since you don't tell me what your tool chain is, I can really only speculate. If your device has a flat memory model and integrated ROM (most 32-bit devices with smaller amounts of storage), then only a single file is necessary to program the device. Since RAM and internal flash are addressed the same, the address just needs to match the desired destination. If, on the other hand, you have two places where ROM is stored (which I suspect is the case in your product) and they aren't addressed the same, then two files might be necessary. This would be the case if there were an ECU which interfaced with and external flash ROM chip (or SD card or the like). In this case, a separate image would be required to write to the off-chip storage since the addresses would likely overlap (an ELF assumes a unique address for a piece of data). So in your case, two ELF files are needed: one specifies the debugging setup to be loaded into RAM to start the device in debug, the other specifies the symbol information for the OS and other data programmed into the external flash chip. The FLS files probably specify information that the programmer uses to address the external flash not present in the ELF, but this depends on architecture (I'm not familiar with how Nokia designs their hardware). This may help for general ELF info: http://blog.ksplice.com/tag/elf/
3,254,148
3,254,269
Strange words appearing during compilation of Application
I am having a service written in C++ and i use VC++ 6.0. When i build this service i get a strange message as shown (The letter 'T'coming during compilation). Though it does not cause any problem, i would like to know why this message occurs. Compiling... SerString.cpp SerSwitcher.cpp Smtp.cpp SysConfigBlob.cpp T T TransLateReportNames.cpp
Perhaps this explains it? Try to look for #warning T or #pragma message ("T") inside your code / headers.
3,254,427
3,255,762
Are tuples of tuples allowed?
I'm currently working on a class with a lot of templates and being able to build tuples of tuples would make it a lot easier But I tried this simple code in MSVC++ 2010: #include <tuple> void main() { auto x = std::make_tuple(std::make_tuple(5, true)); } And I get a compilation error. The same problem happens if I don't use std::make_tuple but directly std::tuple's constructor. Is it a bug of MSVC or are tuples of tuples not allowed by the standard?
More data points: If we use std::tr1::tuple and explicitly state the type instead of using auto, then Visual C++ 2008 compiles the code without error. Trying to compile that same code with Visual C++ 2010 results in the error you are seeing. If we use boost::tuple an explicitly state the type instead of using auto, then Visual C++ 2008 and Visual C++ 2010 both compile the code without error. It looks like it is probably an implementation bug.
3,254,491
3,256,318
C++ Undefined Type Error
Dear all, i have two classes which are computer and floppy disk. When i put #include "FloppyDisk.h" #include "Computer.h" in main, then compiler generates error of computer undeclared When i #include "Computer.h" #include "FloppyDisk.h" in main, then compiler generates error of floppy disk undeclared. What is the problem? I have check there is no cyclic dependency between the header file. These are the implementation file for reference. #include "EquipmentAttributes.h" #include "EquipmentVisitor.h" #include "Computer.h" #include "BoostHeader.h" #include <algorithm> // ============================================= computer::computer() : cont() { } // ============================================= void computer::add(equipment* equip) { cont.push_back(equip); } // ============================================= void computer::remove(equipment* equip) { vecIte myIte; myIte = std::find(cont.begin(), cont.end(), equip); cont.erase(myIte); } // ============================================= void computer::accept(equipmentVisitor* visitor) { BOOST_FOREACH(equipment* anEquip, cont) { anEquip->accept(visitor); } visitor->visitComputer(this); } // ============================================= computer::equipVec computer::getCont() const { return cont; } #include "FloppyDisk.h" #include "EquipmentAttributes.h" #include "EquipmentVisitor.h" // ============================================= floppyDisk::floppyDisk(const int userPrice, const std::string& userName) : state(new equipmentState(userPrice, userName) ) { } // ============================================= void floppyDisk::accept(equipmentVisitor* visitor) { visitor->visitFloppyDisk(this); } // ============================================= floppyDisk::equipPtr floppyDisk::getState() const { return state; } Please help. Thanks.
Are you using the same header include guard in each file, e.g.: #ifndef MY_INCLUDE_GUARD #define MY_INCLUDE_GUARD // blah blah #endif The MY_INCLUDE_GUARD needs to be a unique name in each header.
3,254,521
3,254,640
In how many ways we can take input values in C++?
How to take input values in C++, in how many ways we can take input values.? Please describe in brief with small examples
For console application you have two standard ways: Argument values. User input.
3,254,570
3,254,603
Appending pointers to QList
I need to insert pointers of classes (inherited from QObject) into a QList. I know that the following syntax can be used: .h QList<MyObject*> list; .cpp list.append(new MyObject("first", 1)); list.append(new MyObject("second", 2)); ... and then free memory: if(!list.isEmpty()) { qDeleteAll(list); list.clear(); } This should be valid and does not cause any memory leaks (as far as I know). However, I need to initialize objects before adding them to the collection. Can the following piece of code cause some errors like memory leaks or dangling pointers (I'll use the same way to delete pointers as above)? MyObject *obj; for(i = 0; i < 5; i++) { obj = new MyObject(); if(!obj.Init(i, map.values(i))) { // handle error } else { list.append(obj); } } Thanks.
if you take care of "obj" (the allocated but not initialized instance) in the "// handle error" case, your code is ok.
3,254,652
3,720,560
Several ways of placing an image in a QTextEdit
I think this is a very simple question, but when I copy an image I can't paste it in a QTextEdit? Paste is inactive! Also I would like to know how to drag-and-drop a picture. BTW I use the following code in order to insert a picture into a QTextEdit: QTextEdit *textEditor = new QTextEdit(0); QTextDocumentFragment fragment; fragment = QTextDocumentFragment::fromHtml("<img src='C:\\aaa.jpg'>"); textEditor->textCursor().insertFragment(fragment); textEditor->setVisible(true); Is it recommended? How do you do this operation?
The second way is this: void TextEdit::insertImage() { QString file = QFileDialog::getOpenFileName(this, tr("Select an image"), ".", tr("Bitmap Files (*.bmp)\n" "JPEG (*.jpg *jpeg)\n" "GIF (*.gif)\n" "PNG (*.png)\n")); QUrl Uri ( QString ( "file://%1" ).arg ( file ) ); QImage image = QImageReader ( file ).read(); QTextDocument * textDocument = m_textEdit->document(); textDocument->addResource( QTextDocument::ImageResource, Uri, QVariant ( image ) ); QTextCursor cursor = m_textEdit->textCursor(); QTextImageFormat imageFormat; imageFormat.setWidth( image.width() ); imageFormat.setHeight( image.height() ); imageFormat.setName( Uri.toString() ); cursor.insertImage(imageFormat); } The third way is to inherit QTextEdit and reimplement canInsertFromMimeData and insertFromMimeData functions as follows. By the way this method allows to use drag-and-drop or copy-paste mechanisms. class TextEdit : public QTextEdit { public: bool canInsertFromMimeData(const QMimeData* source) const { return source->hasImage() || source->hasUrls() || QTextEdit::canInsertFromMimeData(source); } void insertFromMimeData(const QMimeData* source) { if (source->hasImage()) { static int i = 1; QUrl url(QString("dropped_image_%1").arg(i++)); dropImage(url, qvariant_cast<QImage>(source->imageData())); } else if (source->hasUrls()) { foreach (QUrl url, source->urls()) { QFileInfo info(url.toLocalFile()); if (QImageReader::supportedImageFormats().contains(info.suffix().toLower().toLatin1())) dropImage(url, QImage(info.filePath())); else dropTextFile(url); } } else { QTextEdit::insertFromMimeData(source); } } private: void dropImage(const QUrl& url, const QImage& image) { if (!image.isNull()) { document()->addResource(QTextDocument::ImageResource, url, image); textCursor().insertImage(url.toString()); } } void dropTextFile(const QUrl& url) { QFile file(url.toLocalFile()); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) textCursor().insertText(file.readAll()); } }; Just wanted to share what I have found during long investigation :).
3,254,664
3,573,467
Windows Mobile 6.5 Change the camera focus
I have a project to scan some QR-code or bar-code with camera on windows mobile. (phone x01t) Programing in C++ and using DirectShow. Tired to change focus with IAMCameraControl interface, but return the error like "...request is not supported". Are there any way else? Thanks
Most (if not all) Windows Mobile phones I've used so far used custom camera drivers, which means OEMs decide which functionalities to implement/support. IAMCameraControl is most likely not one of them. However, you might want to look for OEM-specific SDKs. For instance, Samsung provides custom APIs enabling to change such parameters as camera focus or ISO. Maybe such APIs exist for your device.
3,254,669
4,438,846
How to implement QTextDocument serialization
This question I have asked before and just got answer that there is an open bug for this. But this is a really required feature and, I guess, each Qt programmer who programmes a more or less serious application, it is quite probable that there is used a QTextEdit and the data is inserted in QTextEdit is serialized and deserialized. Thus I consider this issue very importand and it can be useful for many Qt developers. So I have decided to discuss with good programmers how to implement operator<<(QDataStream, QTextDocument). Otherwise we should wait when Qt guys will be kind to do that by themselves :). So say in a QTextEdit I have some pictures and text. In different fragments the text has different format. How to get the content of this kind of QTextEdit and how to serialize, in order to show then as it was? EDIT: I know that I can get the formated text and images by using documnet() method, which returns QTextDocument. I also know that QTextDocument has no operator<<(QDataStream, QTextDocument) and there is a request for writting this operator but it is still open. So please help me to write this method. I guess I should inherit the QTextDocument class, then to add a new member (a container) that stores all the names of resources that are present in the QTextEdit. Then I should serialize all resources by iterating on them by using the container I have defined. Is it a good solution? If yes, then could you please help me to implement? If no then please provide me with a better idea.
See here: How to serialize and deserialize rich text in QTextEdit?
3,254,788
3,254,949
How Visitor Pattern avoid downcasting
can anyone show example code before and after to avoid down casting for visitor pattern code ? Thanks.
A bare, minimalistic example. Before class Base {}; class Derived1 : public Base {}; class Derived2 : public Base {}; // Some arbitrary function that handles Base. void Handle(Base& obj) { if (...type is Derived1...) { Derived1& d1 = static_cast<Derived1&>(base); std::printf("Handling Derived1\n"); } else if (...type is Derived2...) { Derived2& d2 = static_cast<Derived2&>(base); std::printf("Handling Derived2\n"); } } This means Base must have some type tag field, or you will be using dynamic_cast to check for each type. After // Class definitions class Visitor; class Base { public: // This is for dispatching on Base's concrete type. virtual void Accept(Visitor& v) = 0; }; class Derived1 : public Base { public: // Any derived class that wants to participate in double dispatch // with visitor needs to override this function. virtual void Accept(Visitor& v); }; class Derived2 : public Base { public: virtual void Accept(Visitor& v); }; class Visitor { public: // These are for dispatching on visitor's type. virtual void Visit(Derived1& d1) = 0; virtual void Visit(Derived2& d2) = 0; }; // Implementation. void Derived1::Accept(Visitor& v) { v.Visit(*this); // Calls Derived1 overload on visitor } void Derived2::Accept(Visitor& v) { v.Visit(*this); // Calls Derived2 overload on visitor } That was the framework. Now you implement actual visitor to handle the object polymorphically. // Implementing custom visitor class Printer : public Visitor { virtual void Visit(Derived1& d1) { std::printf("Handling Derived1\n"); } virtual void Visit(Derived2& d2) { std::printf("Handling Derived2\n"); } }; // Some arbitrary function that handles Base. void Handle(Base& obj) { Printer p; obj.Accept(p); } Accept() is a virtual function that dispatches on the type of obj (first dispatch) It then calls appropriate overload of Visit(), because inside Accept() you already know the type of your object. Visit(), in turn, is a virtual function that dispatches on the type of visitor (second dispatch). Because you have double dispatch (one on object, another on visitor), you don't do any casting. The downside is that any time you add a class to your hierarchy, you have to go and update your visitor class to add an appropriate function to handle the new subclass.
3,254,834
3,255,355
How can I find a rare bug that seems to only occur in release builds?
I have a fairly large solution that occasionally crashes. Sadly, these crashes appear to only occur in release build. When I attach the debugger upon crashing, I get the message: "No symbols are loaded for any call stack frame. The source code cannot be displayed" This makes it quite hard to find the cause of the crashes. I am using the default release build settings of visual studio 2008, in which 'debug information format' is set to 'Program Database (/Zi)'. Do you have any tips that might help me find the bug? For example, could I change some settings in my projects so that the crashes might still occur but get more meaningful information in the debugger? Update: The problem was a very rarely occurring logic error that in itself should not cause a crash, but apparently caused a crash elsewhere. Solving the logic error solved the crashing behavior. To anyone that came here looking for a resolution of a similar problem: best of luck, you're in for a rough ride. What eventually helped me locate the problem was adding a lot of bounds checks in the code (that I could enable/disable with preprocessor directives) and compiling for linux and running with gdb/valgrind.
Sounds to me like that stack frame was blown. Trivial to do with a buffer overflow, just copy a large string in a small char[] for example. That wipes out the return address. The code just keeps running until the return, then bombs when it pops a bad address off the stack. Or worse, if the address happens to be valid. The debugger cannot display anything meaningful since it cannot walk the stack to show you how the code got to the crash location. The actual crash location doesn't tell you anything. Tuff as nails to debug. You have to get it reproducible and you need either stepping or tracing to find the last known-good function. The one that produces the crash after stepping out of it is the one with the bug. You can actually see the statement that does the damage, the debugger call stack suddenly goes catatonic. If you can't get a consistent repro then a thorough code review is all that's left. You can justify the time by calling it a "security review". Good luck with it.
3,254,937
3,254,969
Creating objects of class through its name stored in a string?
Can I create an object of a class at runtime, by extracting the class name stored in a string? eg: I want to create and object of class QButton like QString strClassName = "QButton"; QButton *pBtn = new strClassName(); I want to read an xml file of all the controls and instantiate them at runtime using this way.
Maybe you are looking for the functionality provided by QUiLoader?
3,255,074
3,255,133
How to process jpg images with c/c++ most easily?
I want to iterate over each pixel color in a jpg format image, which library should I refer to to do this so that the code can be as short as possible?
I can think of either ImageMagick or CImg. Here is a CImg tutorial for you. They abstract away a lot of the decompression details and just give you a grid to work with. If you go with CImg, you only need to use the data call. You can probably do something like: CImg<unsigned char> src("image.jpg"); int width = src.width(); int height = src.height(); unsigned char* ptr = src.data(10,10); // get pointer to pixel @ 10,10 unsigned char pixel = *ptr;
3,255,094
3,255,201
Minimum DirectX 9.0c version and how to check for it
Our Windows C++ Ogre-based game is nearing completion. Before we publicly release it, we have to solve this matter : Ogre crashes on many test-computers if they are not updated to the latest Dx9.0c version. All these computers already had 9.0c installed, but that must have been an older OS-pre-installed sub-version, hence the crash..? The 1st questions is : how can I ensure that a user has the correct 9.0c version so that the game doesn't crash on the user's face, but instead show a message like "Go get the latest 9.0c version from there...."? The 2nd question is : is there a standard, automated method to update the user's computer to the latest 9.0c version during the game's installation? That would be the best solution. Many many thanks in advance, Bill
The 1st questions is : how can I ensure that a user has the correct 9.0c version so that the game doesn't crash on the user's face, but instead show a message like "Go get the latest 9.0c version from there...."? The best idea is to update/install DirectX silently from Game Installer. Along with other required system components like PhysX, vcredist, etc. Silently, without asking "do you want to install DirectX" (user may not know if he needs DirectX, and if it is already installed, nothing will happen). See DirectX Installation for Game Developers. Also, I'd recommend to see "Instalation and Maintenance of Games" This is because (I believe that) when you're making games, you should assume that computer user is total idiot. I.e. if you give instructions, expect that user will screw up, damage the system and blame you for it. Compared to that silent DirectX install is almost fool-proof. Also, it is much more convenient - user won't have to hunt for DirectX download, and will be able to play immediately after installation. The 2nd question is : is there a standard, automated method to update the user's computer to the latest 9.0c version during the game's installation? That would be the best solution. AFAIK, DXSDK includes DirectX redistributable, and AFAIK you're supposed to include those redistributables with your product.
3,255,096
3,255,136
Why syntax error occurs when a void function is checked in IF statement
What will be the output if I write In C++ if(5) will be executed without any problem but not in C# same way will it be able to run. if(func()){} //in C# it doesn't runs Why how does C# treats void and how in Turbo C++ void func() { return; } if(null==null){}//runs in C# EDIT if(printf("Hi"){} //will run and enter into if statement if(printf(""){}//will enter into else condition if found. This Question is not meant for those who are not aware of Turbo Compiler
In C and C++ there is an implicit conversion of int , pointers and most other types to bool. The designers of C# elected not to have that, for clarity. So with int i = 1; int* P = null; if (i && p) { } // OK in C++ if (i != 0 && p != null) { } // OK in C++ and C#
3,255,339
3,255,378
C++ basic template question
I'm slightly confused with template specialization. I have classes Vector2, Vector3 which have operator+= in it (which are defined the following way). Vector2& operator+=(const Vector2& v) { x() += v.x(), y() += v.y(); return *this; } Now I want to add the generic addition behaviour and say something like: template <typename V> const V operator+(const V& v1, const V& v2) { return V(v1) += v2; } This compiles fine and works for both Vector2 and Vector3. But let's say I want to have a slightly more efficient "+" operation for my Vector2 and I want it to act the following way (using the template specialization): template<> const Vector2 operator+(const Vector2& v1, const Vector2& v2) { return Vector2(v1.x() + v2.x(), v1.y() + v2.y()); } This looks fine to me, but unfortunately placing these two chunks of code right after each other makes the code fail the compilation (linker says error LNK2005: "Vector2 const operator+<Vector2>(Vector2 const &,Vector2 const &)" (??$?HVVector2@core@lf@@@core@lf@@YA?BVVector2@01@ABV201@0@Z) already defined in ...) What is my error and where did I go wrong? Thank you.
If the specialisation is in a header file, then you need to declare it inline to allow it to be included in more than one compilation unit. Note that you don't actually need a template specialisation here; a simple overload will do the same thing.
3,255,663
3,256,477
How to Set text color in OpenGl
I am new to openGL and wanted to set the text color tried the glColor3f function but it changes the drawing color as i only want to change the text color what should i do?
You could push the current colour onto the attribute stack, change the colour, draw the text, and then pop the stack to restore the original colour: glPushAttrib(GL_CURRENT_BIT); glColor3f(...); // Draw your text glPopAttrib(); // This sets the colour back to its original value
3,255,671
3,255,686
How can I make an object construct itself at a particular location in memory?
Possible Duplicate: Create new C++ object at specific memory address? I am writing what is essentially an object pool allocator, which will allocate a single class. I am allocating just enough memory to fit the objects that I need, and I am passing out pointers to spaces inside. Now my question is this: Once I have gotten a pointer within my pool, how do I construct an object there?
You use placement new. Like so: new( pointer ) MyClass();
3,255,899
3,255,955
Why are there WSA pendants for socket(), connect(), send() and so on, but not for closesocket()?
I'm going to try to explain what I mean using a few examples: socket() -> WSASocket() connect() -> WSAConnect() send() -> WSASend() sendto() -> WSASendTo() recv() -> WSARecv() recvfrom() -> WSARecvFrom() ... closesocket() -> WSA???() This is nothing that matters much, but is still something that gives me a splitting headache.
closesocket is only available on Windows, I'm not sure why they didn't follow the WSA convention there though. If it really bothers you though you can make your own wrapper that calls closesocket. As mentioned in WSASocket a call to closesocket should be made.
3,255,962
3,256,251
Translating const strings in structure initializers
I'm working with a large code base which uses const strings in structure initializers. I'm trying to translate these strings via GNU gettext with a minimal amount of time. Is there some sort of conversion operator I can add to default_value which will allow Case #1 to work? #include <cstring> template<int N> struct fixed_string { char text[N]; }; // Case #1 struct data1 { char string[50]; }; // Case #2 struct data2 { const char* string; }; // Case #3 struct data3 { fixed_string<50> string; }; // A conversion helper struct default_value { const char* text; default_value(const char* t): text(t) {} operator const char*() const { return text; } template<int M> operator fixed_string<M>() const { fixed_string<M> ret; std::strncpy(ret.text, text, M); ret.text[M - 1] = 0; return ret; } }; // The translation function const char* translate(const char* text) {return "TheTranslation";} int main() { data1 d1 = {default_value(translate("Hello"))}; // Broken data2 d2 = {default_value(translate("Hello"))}; // Works data3 d3 = {default_value(translate("Hello"))}; // Works }
What about direct conversion to data1? .. operator data1() const { data1 ret; std::strncpy(ret.string, text, sizeof(ret.string)); ret.string[sizeof(ret.string)] = 0; return ret; } .. and then: .. data1 d1 = default_value(translate("Hello")); // should work now... ..
3,255,971
3,255,988
method declared in struct in C++ (STL)
I'm trying to understand the syntax used in STL for a class. Our teacher pointed us to this website (http://www.sgi.com/tech/stl/Map.html) where I copied the code below: struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; int main() { map<const char*, int, ltstr> months; months["january"] = 31; months["february"] = 28; months["march"] = 31; months["april"] = 30; months["may"] = 31; months["june"] = 30; months["july"] = 31; months["august"] = 31; months["september"] = 30; months["october"] = 31; months["november"] = 30; months["december"] = 31; cout << "june -> " << months["june"] << endl; map<const char*, int, ltstr>::iterator cur = months.find("june"); map<const char*, int, ltstr>::iterator prev = cur; map<const char*, int, ltstr>::iterator next = cur; ++next; --prev; cout << "Previous (in alphabetical order) is " << (*prev).first << endl; cout << "Next (in alphabetical order) is " << (*next).first << endl; } I did not know you could declare methods in structs. How does that work? I'm assuming that with it, when you declare the map named months, using the luster in the Compare field of a map alphabetizes the map. But still unsure about how it works with the struct syntax. Thanks.
In C++, a struct is really just a class whose default access specifier is public and which inherits publicly by default. In other words, struct ltstr { // ... }; is equivalent to class ltstr { public: // ... }; If you want to, you can make parts of your struct protected or private, too. The reason that struct is still in C++, even though it's redundant, is backwards compatibility.
3,256,039
3,256,121
Cross-platform svn management (Makefiles & Visual Studio)
I'm working on a little game called freegemas, it's an open source version of the classic Bejeweled written in C++ and using gosu as the graphic API. I've been developing it under Ubuntu Linux as usual, but the other day I wanted to give it a try and I compiled it on Windows using Visual Studio 2005 (which I had never used before). The program worked flawlessly. To compile it on Windows I manually copied all the source and header files to a new project on MSVC, but I would like to adapt the SVN so I don't have to recreate the project every time I want to compile it. Therefore, the question would be: What's the best way of organizing the svn so I can have, on the one hand, a Makefile to compile the project in Linux, and, on the other side, the MSVC project's files? Right now I've got a simple folder called trunk with all header, source and resource files on it. I've never used Visual Studio before, so I don't know which files are the most important either. Maybe some of those files are auto-generated and do not need to be svn-versioned. Thanks in advance.
You could just keep the project files in a seperate directory "winbuild" or similar. Still, to maintain them would require manual interaction (ie adding every new file manually). The only files you would need to upload to svn are the *.vcproj (for MSVC 2005/2008) and *.vcxproj (MSVC 2010). Alternatively, you could opt for a cross-platform solution like CMake, which could generate makefiles and Visual Studio project files from a common CMakeLists.txt, which is the only "project file" that would have to be maintained (instead of your makefile). Especially for a simple (?) project like yours (some headers+sources). There would be no need to include any makefiles or vcproj files at all, just the CMakelists.txt file would suffice. There are others like CMake (SCons, boost.jam, jam, premake, etc.) It should be feasable, but requires some testing and trial-and-error.
3,256,045
3,256,223
How to exclude certain #include directives from C++ stream?
I have this C++ file (let's call it main.cpp): #include <string> #include "main.y.c" void f(const std::string& s) { yy_switch_to_buffer(yy_scan_string(s.c_str())); yyparse(); } The file depends on main.y.c, which has to be generated beforehand by means of bison util. In other words, I can't compile main.c file if I forget to run bison main.y before it. And it's perfectly OK, this is how I want it. Now I'm trying to build .d file from Makefile, using this command: $ c++ -MM main.c > main.d main.cpp:2:10: error: main.y.c: No such file or directory I fail here, since main.y.c is not ready yet. I think that I should somehow quote my #include directive in the main.c file to make it invisible for c++ -MM process.
You can indicate in your makefile that main.c depends on main.y.c so that it'll run the bison process before it tries to compile main.c. As an alternative (which I think is probably not what you want to do) is that you can have your makefile pass a macro to the compiler to indicate whether or not main.y.c exists and use an #if directive to include (or not) main.y.c. #if EXISTS_MAIN_Y_C #include "main.y.c" #endif
3,256,192
3,256,246
Complex initialization of const fields
Consider a class like this one: class MyReferenceClass { public: MyReferenceClass(); const double ImportantConstant1; const double ImportantConstant2; const double ImportantConstant3; private: void ComputeImportantConstants(double *out_const1, double *out_const2, double *out_const3); } There is a routine (ComputeImportantConstants) that computes three constants at runtime. Suppose the computation is fairly complex, and inherently produces all three values at once. Moreover, the results depend on build configuration, so hardcoding the results isn't an option. Is there a sensible way to store these computed values in the corresponding const double fields of the class? If not, can you suggest a more natural way to declare such a class in C++? In C# I would use a static class with a static constructor here, but that isn't an option in C++. I have also considered making ImportantConstant1..3 either non-const fields or function calls, but both seem inferior. The only way to initialize const fields that I found is to use initializer lists, but it doesn't seem possible to pass the results of a multi-output computation in such a list.
Why can't you do: MyReferenceClass ComputeImportantConstants(){ //stuff to compute return MyReferenceClass( const1, const2, const3 ); } MyReferenceClass{ public: MyReferenceClass(double _1, double _2, double _3) : m_Const1(_1), m_Const2(_2), m_Const3(_3){} double getImportantConst1() const { return m_Const1; } double getImportantConst2() const { return m_Const2; } double getImportantConst3() const { return m_Const3; } private: const double m_Const1, m_Const2, m_Const3; }; Like that and have the calculate function turn into a factory function?
3,256,198
3,256,243
Does usleep create thread cancellation point?
According to the Linux manpages, only the following functions are thread cancellation points: pthread_join, pthread_cond_wait, pthread_cond_timedwait, pthread_testcancel, sem_wait, sigwait. In my test program, thread exits on usleep. Thread function: void* ThreadFunction(void* arg) { int n = 0; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); for(;;) { ostringstream s; s << "Thread iteration " << n++; PrintLine(s.str().c_str()); usleep(500000); PrintLine("Check whether thread canceled..."); pthread_testcancel(); PrintLine("Thread is not canceled - continue"); } pthread_exit(NULL); } When main function executes pthread_cancel, I expect that last line printed by ThreadFunction is "Check whether thread canceled...". However, it always prints "Thread iteration ..." before exit. This means, usleep is cancellation point. I think that it is correct - any sleep function must be cancellable. But this is not written in documentation. If usleep line is commented, last thread output line is "Check whether thread canceled...", as I expect.
The complete list of cancellation points and optional cancellation points is available in the POSIX spec: http://opengroup.org/onlinepubs/007908775/xsh/threads.html usleep() is a mandatory cancellation point
3,256,428
3,256,474
Can I use a preprocessor variable in #include directive?
This is what I'm trying to do: $ c++ -D GENERATED=build/generated-content main.cpp My main.cpp file: #include "GENERATED/header.h" void f() { /* something */ } Currently this code fails to compile. How should I fix it? And whether it's possible at all?
It seems you want to use different headers depending on some "compilation profile". Instead of the -Dsolution, I would rather suggest using the -I directive to specify the include directories. Given you have the following file tree: / debug/ header.h release/ header.h main.cpp: #include "header.h" /* some instructions, not relevant here */ And in your Makefile (or whatever tool you use), just specify the proper include directory to use, depending on whatever reason you want: g++ -I debug main.cpp // Debug mode g++ -I release main.cpp // Release mode Important foot note: I don't know if you intended to use this as a debug/release switch. However, doing so would be weird: the interface (the included .h files) shouldn't change between release and debug. If you ever need this, the usual way is to enable/disable some parts of the code using defines, mostly in .c (and .cpp) files.
3,256,641
3,256,683
GCC equivalent to VC's floating point model switch?
Does GCC have an equivalent compiler switch to VC's floating point model switch (/fp)? In particular, my application benefits from compiling with /fp:fast and precision is not a big deal, how should I compile it with GCC?
Try -ffast-math. On gcc 4.4.1, this turns on: -fno-math-errno - Don't set errno for single instruction math functions. -funsafe-math-optimizations - Assume arguments and result of math operations are valid, and potentially violate standards -ffinite-math-only - Assume arguments and results are finite. -fno-rounding-math - Enable optimizations that assume default rounding. This is the default, but it could be overridden by something else. -fno-signaling-nans - Enable optimizations that can change number of math exceptions.; also default -fcx-limited-range - Assume range reduction is not needed for complex number division: __FAST_MATH__ macro. You could also enable these individually.
3,256,740
3,256,759
Variadic C++ function doesn't work when fetching arguments of type float
I have a variadic template function: template<typename T, typename ArgType> vector<T> createVector(const int count, ...) { vector<T> values; va_list vl; va_start(vl, count); for (int i=0; i < count; ++i) { T value = static_cast<T>(va_arg(vl, ArgType)); values.push_back(value); } va_end(vl); return values; } This works for some (to me, strange) configurations of T and ArgType, but not the way I expect: // v1 = [0.0, 1.875, 0.0] vector<float> v1 = createVector<float, float>(3, 1.0f, 2.0f, 3.0f); // v2 = [0.0, 1.875, 0.0] vector<float> v2 = createVector<float, float>(3, 1.0, 2.0, 3.0); // v3 = [1.0, 2.0, 3.0] vector<float> v3 = createVector<float, double>(3, 1.0, 2.0, 3.0); // v4 = [1.0, 2.0, 3.0] vector<float> v4 = createVector<float, double>(3, 1.0f, 2.0f, 3.0f); // v5 = [1.0, 2.0, 3.0] vector<double> v5 = createVector<double, double>(3, 1.0, 2.0f, 3.0); Why does this work when ArgType is double (even when passing floats), but not when it's float?
Floating point values are passed as doubles when passed to variadic functions, just as integers small than int are passed as int.
3,256,910
3,256,930
assign elements in vector declared with new. C++
I am trying to use a large 2D vector which I want to allocate with new (because it is large). if I say: vector< vector<int> > bob; bob = vector< vector<int> >(16, vector<int>(1<<12,0)); bob[5][5] = 777; it works. But if I say: std::vector< std::vector<int> > *mary; mary = new vector< vector<int> >(16, vector<int>(1<<12, 0)); mary[5][5] = 777; it doesn't work and I get the error: Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) c:\Users\jsparger\Documents\My Dropbox\ARI\VME_0.01\VME_0.01\V965.cpp 11 VME_0.01 Obviously I am new to C++. Could someone explain what syntax I need to use to perform this operation. mary is a pointer, so I can see why this wouldn't work, but *mary[5][5] = whatever is not allowed either because of "new", right? Thanks for the help. This vector is what I will be using for now because it seems easy enough for my small c++ brain to understand, but feel free to let me know if a large vector like this is a bad idea, etc. Thanks a bunch. Edit: I am mistaken about the "not allowed because of new". I don't know where I misread that, because it obviously works, and wouldn't make too much sense for it not to. Thanks.
If mary is a pointer then you have to dereference it before applying the subscript operator: (*mary)[5][5] = 777; The parentheses are required because the subscript has higher precedence than the dereference.
3,256,998
3,257,018
C++ void type - how?
typedef void(Object Sender) TNotifyEvent; This is what I'm trying to do from Delphi to C++, but it fails to compile with 'type int unexpected'. The result should be something I can use like that: void abcd(Object Sender){ //some code } void main{ TNotifyEvent ne = abcd; } How do I make such type(of type void)? I'm not very familiar with C++.
If what you want is to define the type of a function that takes an Object as parameter and returns nothing, the syntax would be: typedef void TNotifyEvent( Object Sender ); EDIT, as answer to the comment. Yes, you can define the type of a function, and that type can later be used in different contexts with different meanings: TNotifyEvent func; // function declaration (weird as it might look) // same as: void func( Object Sender ); TNotifyEvent *fp = func; // function pointer declaration -- initialized with &func void func( Object Sender ) // cannot use the type when defining the function {} void foo( TNotifyEvent f ); // compiler translates to TNotifyEvent * f // just as 'int a[5]' is converted to 'int *a' // in function parameter lists.
3,257,062
3,257,142
How to use Eigen, the C++ template library for linear algebra?
I have an image processing algorithm which makes of matrices, I have my own matrix operation codes (Multiplication, Inverse...) with me. But the processor I use is ARM Cortex-A8 processor, which has NEON co-processor for vectorization, as matrix operations are ideal cases for SIMD operations, I asked the compiler (-mfpu=neon -mfloat-abi=softfp) to generate NEON instructions for my code, but the compiler fails to do so and then I also attempted to write my own NEON intrinsics code for the Matrix operations, but I found it very hard to do so. So, I thought of making use of Eigen library which promises vectorization of matrix operations. So I promptly downloaded the Eigen C++ library and tried using it as given in their tutorials but, unfortunately I get compilation errors when I run their example programs. Anyone out there who has experience using Eigen, any examples will be really helpful? Kindly help me how to go about it. Help! Thanks I have the Eigen folder at: /home/ubuntu/Documents/eigen I set this path in my Eclipse's C++ project's additional directories. Then I run the following program (Example)- #include <Eigen/Core> // import most common Eigen types USING_PART_OF_NAMESPACE_EIGEN int main(int, char *[]) { Matrix3f m3; m3 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix4f m4 = Matrix4f::Identity(); Vector4i v4(1, 2, 3, 4); std::cout << "m3\n" << m3 << "\nm4:\n" << m4 << "\nv4:\n" << v4 << std::endl; } Errors I get - Build of configuration Debug for project Test_Eigen **** make all Building file: ../main.cpp Invoking: Sourcery G++ C++ Compiler arm-none-linux-gnueabi-g++ -I/home/ubuntu/Documents/eigen -O0 -g3 -Wall -c -fmessage-length=0 -fcommon -MMD -MP -MF"main.d" -MT"main.d" -mcpu=cortex-a8 -marm -o"main.o" "../main.cpp" ../main.cpp:6: error: expected constructor, destructor, or type conversion before 'int' make: *** [main.o] Error 1
The USING_PART_OF_NAMESPACE_EIGEN macro was removed in Eigen 3. Instead, simply use using namespace Eigen; Apparently, the tutorial is outdated.
3,257,116
3,295,486
JNI method returns old data
I've spent whole day on this problem and still have no idea how to solve it. Here is the simplified code JAVA class javaclass{ private volatile boolean isTerminated; public void javamethod() { log.logInfo("java :"+isTerminated()); } public int isTerminated() { return (isTerminated) ? 1 : 0; } public doJob() { executeNative(); } private native int executeNative() throws Exception; } C++ bool cmethod() { cerr &lt&lt "JNI " &lt&lt wrapper::isTerminated() &lt&lt "\n"; if(wrapper::isTerminated) return false; jni->CallVoidMethod(self, apiJavamethod, xPoint); return true; //apiJavamethod is jMethodId of javamethod } int wrapper::isTerminated() { return jni->CallIntMethod(self, apiIsTerminated); } JNIEXPORT jint JNICALL NAMESPACE_javaclass_executeNative(JNIEnv* env, jobject self) { for(int i=0;i &lt _ITERATIONS;++i) { if(!cmethod()) break; } } C++ cmethod is executed in some loop, which stops when C++ catches isTerminated(). In output i see: .... .... in log: java 0 java 1 java 1 java 1 in console: JNI 0 JNI 0 JNI 0 JNI 1 So, JNI is somehow behind the real state of variable. It produces an important bug in application ((( Maybe it's some problem with java itself? (v.1.5, i forced to used it) Any help is greatly appreciated.
I would suggest doing all the synchronization in one language or the other. It's looking like "volatile" isn't being respected across the boundary for some reason. Something like: public doJob() { while(!isTerminated) executeNative(); }
3,257,146
3,257,552
Class method with number of arguments specified by integer template parameter
Was not exactly sure how to phrase this question or what to search on so if this is the same as another question please close and redirect to the appropriate question. Suppose template<typename Type, int Size> class vector { Type data[Size]; } Is it possible to replace a constructor which takes Size number of arguments in template specializations like this template<typename Type> class vector3<Type,3> { Type data[3]; public: vector3( Type, Type, Type ); } with something in the non-specialized template class? Like a "varargs constructor" that produces a constructor with Size number of arguments of type Type? A solution involving C++0x features is fine.
In C++0x you have template typedef finally available! Disclaimer: nothing has been compiled... From Wikipedia's article: template< typename second> using TypedefName = SomeType<OtherType, second, 5>; which in your case would yield template <class Type> using vector3 = vector<Type, 3>; I can't tell you how much I craved for this ;) However it doesn't solve the parameters issue. As mentioned, you could try and use variadic templates here, however I am unsure as to their application in this case. The normal use is with recursive methods and you would need to throw a static_assert in the midst. Edited to take the comments into account. template <class Type, size_t Size> class vector { public: template <class... Args> vector(Args... args): data({args...}) { // Necessary only if you wish to ensure that the exact number of args // is passed, otherwise there could be less than requested BOOST_MPL_ASSERT_RELATION(sizeof...(Args), ==, Size); } private: T data[Size]; }; Another possibility that is already available is to combine Preprocessor generation with boost::enable_if. template <class Type, size_t Size> class vector { public: vector(Type a0, typename boost::enable_if_c< Size == 1 >::type* = 0); vector(Type a0, Type a1, typename boost::enable_if_c< Size == 2 >::type* = 0); // ... }; Using Boost.Preprocessor for the generation makes this easier. BOOST_PP_REPEAT(MAX_COUNT, CONSTRUCTOR_MACRO, ~); // where MAX_COUNT is defined to the maximum size you wish // and CONSTRUCTOR_MACRO actually generates the constructor #define CONSTRUCTOR_MACRO(z, n, data) \ vector( \ BOOST_PP_ENUM_PARAMS(n, Type a), \ typename boost::enable_if_c< Size == n >::type* = 0 \ ); The implementation of the constructor is left as an exercise for the reader. It's another call to BOOST_PP_REPEAT. As you can see, it soon gets ugly, so you'll be better off if you can use the variadic template version.
3,257,393
3,257,590
Is it legal/well-defined C++ to call a non-static method that doesn't access members through a null pointer?
I came across the following code recently: class Foo { public: void bar(); // .. other stuff }; void Foo::bar() { if(!this) { // .. do some stuff without accessing any data members return; } // .. do normal actions using data members } The code compiles because in C++ methods are just functions that are implicitly passed a pointer for 'this' and 'this' can be checked to be NULL just like any other pointer. Obviously this code is confusing and bad practice even though it doesn't crash; it would be pretty confusing to step through the code in the debugger, see a NULL pointer is about to have a method called on it and then not see the expected crash. My question is: does it violate the C++ standard to call SomeFooPtr->bar() where SomeFooPtr == NULL? It occurs to me that it may not because the user defined operator-> returns a pointer, which means that even if that pointer is NULL it definitely hasn't been dereferenced (dereferencing a NULL pointer I'm sure is regarded by the standard as illegal or undefined). On the other hand the semantics of raw pointers don't necessarily have to match the semantics of user defined pointers -- perhaps operator-> on them is considered a dereference even though the compiler won't generate one.
This will probably work on most systems, but it is Undefined Behaviour. Quoth the Standard: 5.2.5.3 If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2 [...] And: 5.2.5.1 A postfix expression followed by a dot . or an arrow ->, optionally followed by the keyword template (14.8.1), and then followed by an id-expression, is a postfix expression. The postfix expression before the dot or arrow is evaluated;58) [...] 58) This evaluation happens even if the result is unnecessary to determine the value of the entire postfix expression, for example if the id-expression denotes a static member. Evaluation of *x where x is a null pointer results in Undefined Behaviour, so yours is clearly a case of UB, before the function is even entered.
3,257,430
3,257,666
Do you get Debug Assertions under C++ when no CRT is installed?
When you have a Debug version of a C++ program running on an OS that has no VS or CRT installed, will you still get Debug Assertion error boxes? The ones that say "Debug Assert Failed!". Or will you only get them when the machine has certain components, such as CRT or Visual Studio installed?
If you can get it to run, yes. Compiling with /MDd (the default) requires distributing the debug version of the dynamic CRT. It is not a redistributable component, shipping it anyway is a license violation. You could get around it by compiling with /MTd. Of course, your user will have no idea what "Debug assertion failed" means and won't understand why Ignore doesn't work. Best avoided.
3,257,453
3,257,502
c++ ternary operator
So I ran into something interesting that I didn't realize about the ternary operator (at least in Visual C++ 98-2010). As pointed out in http://msdn.microsoft.com/en-us/library/e4213hs1(VS.71).aspx if both the expression and conditional-expression are l-values the result is an l-value. Of course normally in c/c++ you'd write something like: int value = (x == 1) ? 1 : 0; and never even care about the r-value/l-value involvment, and in this case neither 1 nor 0 are convertible to l-values. However, take something like: int value = (x == 1) ? y : z; both y and z are l-values and they, or more precisely, one of them is the actual result of the ternary operator (not its stored value) which isn't necessarily obvious (at least I had never thought about it at any length). But, what that leads to is the ability to write the following (x == 1 ? y : z) = 99; Which assigns 99 to y if x == 1 or 99 to z if x != 1 I've never seen that described anywhere and in all the discussions I've read about the use (or, usually, whether to use) the ternary operator. Of course it only works if both the expression and conditional-expression are l-values something like (x == 1 ? 0 : z) = 99; fails to compile because 0 is an r-value as happily pointed out by the compiler. And this only works if you include the parenthesis x == 1 ? y : z = 99; is something entirely different which assigns 99 to z only if (x != 1) and the beautiful part is that both sides are still l-values so there is the serious rat-hole of what things like (x == 1 ? y : z = 99) = 100 do (it assigns 100 to y or z depending on the truth of x == 1, stomping on the z = 99 assignment if x==1 is false) So, this leads me to my questions: A) Is this part of the actual c++ standard (which seems like it would be) and not just a Microsoft thing -- I've looked but have failed, so far, to find this info. B) If this is widely realized and I've been living under a rock? I've never seen it used in any code that I can recall, and never seen it mentioned when the ternary operator is discussed. C) Do I need to get out more often?
A) Yes, this is part of the standard. B) It's not widely realized, though it may be here on SO. There's a reason it was voted the #1 hidden feature of C++: Hidden Features of C++?. C) No comment. :) Personally, I recommend steering clear of using this feature. It is a lot less intuitive than using if/else statements, and clearly not everyone knows about it. Going against my own warning, I actually tried using this once on a personal project, and I got burned by missing the parentheses and wasting 30 minutes trying to find the error.
3,257,465
3,257,515
Invalid use of List Iterator in c++
int num = 0; list::iterator it; for(it = binary.const_iterator; it !=binary.end(); ++it) { if(*it == '1') { abc.push_back(copyoflist.at(num)); } num++; } Here binary is defined as list binary; copyoflist is a char type vector. I am getting this error: invalid use of 'std::list >::const_iterator' on the line for(it = binary.const_iterator; it !=binary.end(); ++it) Am not able to figure out what is going wrong. Can someone help me out ?
const_iterator is a type, not a property. You would use it like this: list<char>::const_iterator it; for(it = binary.begin(); it != binary.end(); ++it)
3,257,584
3,257,671
O* p = new O[5]; What does p point to?
To the first O of the array?
Exactly. *p and p[0] are the same. Here are some neat features you want to know: "Pointer notation" generally refers to using the 'dereference' (or 'indirection') operator "Array notation" generally refers to using the brackets and offset value You can represent an address in memory using either interchangeably: *p is equivalent to p[0] *(p+1) is equivalent to p[1], and more awesomely also equivalent to 1[p] NOTE: As noted in another response, the general form is that *(p+i) is equivalent to p[i] Also, please don't use i[p]
3,257,610
3,257,816
How can I catch my custom exception with Boost.Test?
When I'm testing my C++ class with Boost.Test and my custom exceptions are thrown (they are instances of my class), this is the message I see in log: unknown location:0: fatal error in "testMethod": unknown type It's very un-informative and I don't know how to teach Boost.Test to convert my exception to string and display it properly. My Exception class has operator string(), but it doesn't help. Any ideas? Thanks!
I believe it would work if your custom exception class inherited from std::exception.
3,257,687
3,257,759
Correct way to initialize array of boost::scoped_ptr?
I have a class with an array of scoped pointers to objects which do NOT have a default constructor. The only way I've found to "initialise" them is using swap() like this: class Bar { Bar(char * message) {}; } class Foo { boost::scoped_ptr<Bar> arr[2]; Foo() { arr[0].swap(boost::scoped_ptr<Bar>( new Bar("ABC") )); arr[1].swap(boost::scoped_ptr<Bar>( new Bar("DEF") )); }; } This feels a little verbose and clunky. Have I missed a smarter way of doing it?
arr[0].reset(new Bar("ABC")); arr[1].reset(new Bar("DEF"));
3,257,707
3,257,870
Why is programming with objects not considered procedural?
Even though OOP uses objects and data encapsulation, the code still writes out like a procedure. So what makes OOP loose the procedural label? Is it just because it is considered "high-level"? Thank You.
It's not that Object-orient Programming is "non-Procedural"; it's just that the code we call "Procedural" is not Object-oriented (and not Functional and probably not a couple others) It's not so much an either-or case, but a slow gradiate: Spaghetti code -> Structured Code -> Object-oriented code -> Component code. (UPDATE: Removed "Procedural" from the chart above, since it refers to all of the right 3/4rds of it)
3,257,837
3,257,908
c++ search text n boolean mode
basically have two questions. 1. Is there a c++ library that would do full text boolean search just like in mysql. E.g., Let's say I have: string text = "this is my phrase keywords test with boolean query."; string booleanQuery = "\"my phrase\" boolean -test -\"keywords test\" OR "; booleanQuery += "\"boolean search\" -mysql -sql -java -php"b //where quotes ("") contain phrases, (-) is NOT keyword and OR is logical OR. If answer to first is no, then; 2. Is it possible to search a phrase in text. e.g., string text =//same as previous string keyword = "\"my phrase\""; //here what's the best way to search for my phrase in the text?
TR1 has a regex class (derived from Boost::regex). It's not quite like you've used above, but reasonably close. Boost::phoenix and Boost::Spirit also provide similar capabilities, but for a first attempt the Boost/TR1 regex class is probably a better choice.
3,257,890
3,257,953
How to fix the syntax in this code rife with templates?
The following code template<typename T, typename U> class Alpha { public: template<typename V> void foo() {} }; template<typename T, typename U> class Beta { public: Alpha<T, U> alpha; void arf(); }; template<typename T, typename U> void Beta<T, U>::arf() { alpha.foo<int>(); } int main() { Beta<int, float> beta; beta.arf(); return 0; } Fails to compile due to: ../src/main.cpp: In member function ‘void Beta::arf()’: ../src/main.cpp:16: error: expected primary-expression before ‘int’ ../src/main.cpp:16: error: expected ‘;’ before ‘int’ How the heck do I fix this? I've tried everything I can think of.
alpha::foo is a dependent name, use alpha.template foo<int>(). Dependent names are assumed to not be types unless prefixed by typename not be templates unless directly prefixed by template
3,257,896
3,260,163
C++ for_each calling a vector of callback functions and passing each one an argument
I'm fairly green when it comes to c++0x, lambda, and such so I hope you guys can help me out with this little problem. I want to store a bunch of callbacks in a vector and then use for_each to call them when the time is right. I want the callback functions to be able to accept arguments. Here's my code right now. The trouble is in void B::do_another_callbacks(std::string &) #include <boost/bind.hpp> #include <boost/function.hpp> #include <vector> #include <iostream> #include <algorithm> class A { public: void print(std::string &s) { std::cout << s.c_str() << std::endl; } }; typedef boost::function<void(std::string&)> another_callback; typedef boost::function<void()> callback; typedef std::vector<callback> callback_vector; typedef std::vector<another_callback> another_callback_vector; class B { public: void add_callback(callback cb) { m_cb.push_back(cb); } void add_another_callback(another_callback acb) { m_acb.push_back(acb); } void do_callbacks() { for_each(m_cb.begin(), m_cb.end(), this); } void do_another_callbacks(std::string &s) { std::tr1::function<void(another_callback , std::string &)> my_func = [] (another_callback acb, std::string &s) { acb(s); } for_each(m_acb.begin(), m_acb.end(), my_func(_1, s)); } void operator() (callback cb) { cb(); } private: callback_vector m_cb; another_callback_vector m_acb; }; void main() { A a; B b; std::string s("message"); std::string q("question"); b.add_callback(boost::bind(&A::print, &a, s)); b.add_callback(boost::bind(&A::print, &a, q)); b.add_another_callback(boost::bind(&A::print, &a, _1)); b.do_callbacks(); b.do_another_callbacks(s); b.do_another_callbacks(q); } I thought I might be able to do something like this... void do_another_callbacks(std::string &s) { for_each(m_acb.begin(), m_acb.end(), [&s](another_callback acb) { acb(s); }); } But that doesn't compile in MSVC2010
The problem with the long example is that my_func(_1,s) is evaluated right there and then. You need to use std::bind (or boost::bind) to invoke the function on each element in the range. The alternative code that you posted does indeed work, but the whole example fails to compile because of the code in do_callbacks: void do_callbacks() { for_each(m_cb.begin(), m_cb.end(), this); } this is of type B*, which is not callable. If you define a result_type typedef to match the return type of operator() then you could use std::ref(*this) instead. The following code compiles and runs under MSVC10: #include <functional> #include <vector> #include <iostream> #include <algorithm> class A { public: void print(std::string &s) { std::cout << s.c_str() << std::endl; } }; typedef std::function<void(std::string&)> another_callback; typedef std::function<void()> callback; typedef std::vector<callback> callback_vector; typedef std::vector<another_callback> another_callback_vector; class B { public: void add_callback(callback cb) { m_cb.push_back(cb); } void add_another_callback(another_callback acb) { m_acb.push_back(acb); } void do_callbacks() { std::for_each(m_cb.begin(), m_cb.end(), std::ref(*this)); } void do_another_callbacks(std::string &s) { std::for_each(m_acb.begin(), m_acb.end(), [&s](another_callback acb) { acb(s); }); } typedef void result_type; void operator() (callback cb) { cb(); } private: callback_vector m_cb; another_callback_vector m_acb; }; int main() { A a; B b; std::string s("message"); std::string q("question"); b.add_callback(std::bind(&A::print, &a, s)); b.add_callback(std::bind(&A::print, &a, q)); b.add_another_callback(std::bind(&A::print, &a, std::placeholders::_1)); b.do_callbacks(); b.do_another_callbacks(s); b.do_another_callbacks(q); }
3,257,965
3,258,174
which size of struct member alignment in VC bring performance benefit?
does struct member alignment in VC bring performance benefit? if it is what is the best performance implication by using this and which size is best for current cpu architecture (x86_64, SSE2+, ..)
Perf takes a nose-dive on x86 and x64 cores when a member straddles a cache line boundary. The common compiler default is 8 byte packing which ensures you're okay on long long, double and 64-bit pointer members. SSE2 instructions require an alignment of 16, the code will bomb if it is off. You cannot get that out of a packing pragma, the heap allocator for example will only provide an 8-byte alignment guarantee. Find out what your compiler and CRT support. Something like __declspec(align(16)) and a custom allocator like _aligned_malloc(). Or over-allocate the memory and tweak the pointer yourself.
3,258,058
3,258,158
Aren't template class member functions compiled at instantiation?
I found a strange issue when porting my code from Visual Studio to gcc. The following code compiles fine in Visual Studio, but results in an error in gcc. namespace Baz { template <class T> class Foo { public: void Bar() { Baz::Print(); } }; void Print() { std::cout << "Hello, world!" << std::endl; } } int main() { Baz::Foo<int> foo; foo.Bar(); return 0; } My understanding is that this should compile OK, as the class shouldn't be compiled until the template is instantiated (which is after Print() is defined). However, gcc reports the following: t.cpp: In member function 'void Baz::Foo::Bar()': Line 8: error: 'Print' is not a member of 'Baz' Who's right? And if gcc is right, why?
gcc is right. It is because Baz is a namespace and namespaces are parsed top to bottom, so the declaration of Baz::Print is not visible from inside Foo (since it is beneath it). When the template is instantiated, only names visible from the template definition are considered, not counting Koenig lookup (which wouldn't change anything in your case). If Baz were a struct or class, your code would work, since these are parsed in two phases (first declarations, then bodies), so anything declared in a struct or class is visible inside eg. member functions, regardles of their order in the source file. You can make it work by declaring Baz::Print before Foo. Quoting the standard: 14.6.3 Non-dependent names Non-dependent names used in a template definition are found using the usual name lookup and bound at the point they are used. 14.6.4 Dependent name resolution In resolving dependent names, names from the following sources are considered: Declarations that are visible at the point of definition of the template. Declarations from namespaces associated with the types of the function arguments both from the instantiation context (14.6.4.1) and from the definition context. (end quotation) When Print is nondependent (as it is now), it wouldn't be found since it is looked up before its declaration (in the template definition context). If it were dependent, it wouldn't be the first case (same as when nondependent), and Baz is not associated with int (the template parameter) in any way, so it wouldn't be searched according to the second case either.
3,258,230
3,276,677
Passing a typename and string to parameterized test using google test
Is there a way of passing both a type and a string to a parametrized test using google's test. I would like to do: template <typename T> class RawTypesTest : public ::testing::TestWithParam<const char * type> { protected: virtual void SetUp() { message = type; } }; TEST_P(RawTypesTest, Foo) { ASSERT_STREQ(message, type); ParamType * data = ..; ... } Thanks in advance
Value parameterized tests won't work for passing type information; you can only do that with typed or type parameterized tests. In both cases you'll have to package your type and string information into special structures. Here is how it can be done with type-parameterized tests: template <typename T> class RawTypesTest : public testing::Test { public: virtual void SetUp() { this->message_ = TypeParam::kStringValue; } protected: const char* const message_; }; TYPED_TEST_CASE_P(RawTypesTest); TYPED_TEST_P(RawTypesTest, DoesFoo) { ASSERT_STREQ(message, TypeParam::kStringValue); TypeParam::Type* data = ...; } TYPED_TEST_P(RawTypesTest, DoesBar) { ... } REGISTER_TYPED_TEST_CASE_P(FooTest, DoesFoo, DoesBar); And now you have to define the parameter structures and instantiate the tests for them: struct TypeAndString1 { typedef Type1 Type; static const char* kStringValue = "my string 1"; }; const char* TypeAndString1::kStringValue; struct TypeAndString2 { typedef Type1 Type; static const char* kStringValue = "my string 2"; }; const char* TypeAndString2::kStringValue; typedef testing::Types<TypeAndString1, TypeAndString2> MyTypes; INSTANTIATE_TYPED_TEST_CASE_P(OneAndTwo, RawTypeTest, MyTypes); You can use a macro to simplify definition of your parameter types: #define MY_PARAM_TYPE(name, type, string) \ struct name { \ typedef type Type; \ static const char kStringValue = string; \ }; \ const char* name::kStringValue Then definitions of parameter structs become much shorter: MY_PARAM_TYPE(TypeAndString1, Type1, "my string 1"); MY_PARAM_TYPE(TypeAndString2, Type2, "my string 2"); This is quite complicated but there is no easy way to do this. My best advice is to try re-factor your tests to avoid requiring both type and value information. But if you must, here is the way.
3,258,248
3,258,466
Is it possible to construct an "infinite" string?
Is there any real sequence of characters that always compares greater than any other string? My first thought was that a string constructed like so: std::basic_string<T>(std::string::max_size(), std::numeric_limits<T>::max()) Would do the trick, provided that the fact that it would almost definitely fail to work isn't such a big issue. So I presume this kind of hackery could only be accomplished in Unicode, if it can be accomplished at all. I've never heard of anything that would indicate that it really is possible, but neither have I heard tell that it isn't, and I'm curious. Any thoughts on how to achieve this without a possibly_infinite<basic_string<T>>?
I assume that you compare strings using their character value. I.e. one character acts like a digit, a longer string is greater than shorter string, etc. s there any real sequence of characters that always compares greater than any other string? No, because: Let's assume there is a string s that is always greater than any other string. If you make a copy of s, the copy will be equal to s. Equal means "not greater". Therefore there can be a string that is not greater than s. If you make a copy of s and append one character at the end, it will be greater than original s. Therefore there can be a string that is greater than s. Which means, it is not possible to make s. I.e. A string s that is always greater than any other string cannot exist. A copy of s (copy == other string) will be equal to s, and "equal" means "not greater". A string s that is always greater or equal to any other string, can exist if a maximum string size has a reasonable limit. Without a size limit, it will be possible to take a copy of s, append one character at the end, and get a string that is greater than s. In my opinion, the proper solution would be to introduce some kind of special string object that represents infinitely "large" string, and write a comparison operator for that object and standard string. Also, in this case you may need custom string class. It is possible to make string that is always less or equal to any other string. Zero length string will be exactly that - always smaller than anything else, and equal to other zero-length strings. Or you could write counter-intuitive comparison routine where shorter string is greater than longer string, but in this case next code maintainer will hate you, so it is not a good idea. Not sure why would you ever need something like that, though.
3,258,269
3,258,538
SomeClass* initialEl = new SomeClass[5];
Should SomeClass* initialEl = new SomeClass[5]; necessarily compile, assuming SomeClass does not have a non-publicly declared default constructor? Consider: /* * SomeClass.h * */ #ifndef SOMECLASS_H_ #define SOMECLASS_H_ class SomeClass { public: SomeClass(int){} ~SomeClass(){} }; #endif /* SOMECLASS_H_ */ /* * main.cpp * */ #include "SomeClass.h" int main() { SomeClass* initialEl = new SomeClass[5]; delete[] initialEl; return 0; }
No, it won't compile without a default constructor. There is no compiler-generated default constructor in this case, because you have defined another constructor. "The compiler will try to generate one if needed and if the user hasn't declared other constructors." -- The C++ Programming Language, Stroustrup If you really want to use new SomeClass[5], you'll have to provide a default constructor as well.
3,258,312
3,258,622
SetWindowsHookEx for Mac OS X?
Windows hooks allows you to poke inside other processes and sometimes alter their behaviors. Is there such thing for Mac OS X? Thanks!
SetWindowsHookEx is more like the old InputManager hack, in the sense that you change the code of an app from inside a shared library / a plugin loaded to it. See SIMBL for a ready-made code injector to another process. For Objective-C classes, you then need to use method swizzling. I haven't tried replacing C functions / C++ classes myself, but surely it can be done using mach_override. See also this blog post. But usually if you want to modify a GUI app, tapping into Objective-C classes would be sufficient.
3,258,448
3,258,513
Show Delphi And C++ Source Code
How can I see the source code of an executable compiled by Delphi or C++? Please help me. After Edit: I have a program. When I start this program, it shows a dialog and asks for a password. This password is saved in source code. I want to take this password quickly and easily.
You can't. An enormous amount of information is thrown away when the compiler reduces human readable text source code down to machine executable code. Local variables don't need names in machine code, for example, they're just register bits in the instruction opcode. This is why debugging a compiled executable to step through the original source files line by line can only be done if you have the compiler debug symbols to go with the executable. There are utilities that attempt to reverse engineer machine code into source code, but the result is less readable to humans than the original machine code, in my opinion. Machine generated function names, machine generated local variables and arguments, and many times the utility has to guess as to the exact data types of arguments and local vars. (is this arg a signed int or an unsigned int? Hard to tell when it's just a stack slot or machine register) Compiling to an intermediate representation, as is done in Java and .NET, provides for much more reversibility because the types and symbol names of much of the original code are retained. Reflector, for example, can emit C# source code that is very close to the original human written source code.
3,258,789
3,258,894
C++ vectors question
Does anyone know how to speed up boost::numeric::ublas::vector? I am using typedef ublas::vector<float, ublas::bounded_array<float, 3> > MYVECTOR3 and compare it's speed to D3DXVECTOR3 on plain operations. The test look the following way: #include <d3dx9.h> #pragma comment(lib, "d3dx9.lib") static const size_t kRuns = static_cast<size_t>(10e6); TEST(Performance, CStyleVectors) { D3DXVECTOR3 a(1.0f, 2.0f, 3.0f); D3DXVECTOR3 b(2.0f, 3.0f, 1.0f); D3DXVECTOR3 c(6.0f, 4.0f, 5.0f); for (size_t i = 0; i < kRuns; ++i) { c = c + (a + b) * 0.5f; } } #include <boost/numeric/ublas/vector.hpp> TEST(Performance, CppStyleVectors) { typedef boost::numeric::ublas::vector<float, boost::numeric::ublas::bounded_array<float, 3> > MYVECTOR3; MYVECTOR3 a(3), b(3), c(3); a[0] = 1.0f, a[1] = 2.0f, a[2] = 3.0f; b[0] = 2.0f, b[1] = 3.0f, b[2] = 1.0f; c[0] = 6.0f, c[1] = 4.0f, c[2] = 5.0f; for (size_t i = 0; i < kRuns; ++i) { noalias(c) = c + (a + b) * 0.5f; } } And the results are the following: [----------] 2 tests from Performance [ RUN ] Performance.CStyleVectors [ OK ] Performance.CStyleVectors (484 ms) [ RUN ] Performance.CppStyleVectors [ OK ] Performance.CppStyleVectors (9406 ms) [----------] 2 tests from Performance (9890 ms total) As you can see, plain C-style vector is about 20 times faster than one from boost::numeric::ublas even when using custom stack-based allocator. Does somebody have any idea on how I could speed it up? Maybe by writing a custom wrapper or something like that? Thank you
Boost uBLAS (and BLAS in general) provides support for vector and matrix algebra, where number of dimensions is determined in runtime. It is suitable for solving certain numerical problem (like simulation with FEM or similar method, optimization problems, approximation). For these problems it's relatively fast but cannot compete in performance with specialized 3d vector class library on its turf. Use some other library. If D3DXVECTOR3 is not enough, checkout e.g. CGAL.
3,258,831
3,258,859
Behavior of STL remove() function - only rearrange container elements?
I've read here on StackOveflow and other sources that the behavior of the remove function is simply re-ordering the original container so that the elements that are TO BE REMOVED are moved to the end of the container and ARE NOT deleted. They remain part of the container and the remove() function simply returns an iterator that delimits the end of the range of elements to keep. So if you never actually trim off the portion of the container that has the values that have been 'removed', they should still be present. But when I run the code below there are no trailing spaces after the alphanumeric characters that were not 'removed'. int main() { std::string test "this is a test string with a bunch of spaces to remove"; remove(test.begin(), test.end(), ' '); std::cout << test << std::endl; return 0; } What is going on here? Seeing as I never call test.erase() shouldn't I have a bunch of trailing spaces on my string? Is it guaranteed that the 'removed' items will still be present after calling remove()? PS-I'm not looking for suggestions on how to best remove spaces from a string, the above is simply an illustrative example of the remove() behavior that is confusing me.
What's left at the end of your container after a call to remove is not necessarily the elements that were removed. It's just junk. Most likely it's "whatever was in those positions before the call to remove", but you can't rely on that either. Much like an uninitialized variable, it could be anything. For example, the string: "Hi I am Bob!\0" after a call to remove to get rid of spaces probably looks like this "HiIamBob!\0b!\0" You won't see that on a cout, though, because it will stop printing once it hits the '\0'.
3,258,861
3,258,937
Iterate forward and then reverse over STL container
I have an STL container and I need to perform an action on each element in the container. But if the action fails on any element, I want to reverse the action on any elements that have already been changed. For example, if I had an STL vector with pointers to a number bankAccount classes and wanted to increase each one by $50. But if any of the bank accounts fail to increase by 50, I want to cancel the increase entirely and decrease by $50 any of the accounts that have already been increased. std::vector<bankAccount*> bankAccounts; std::vector<bankAccount*>::iterator iter; for (iter = bankAccounts.begin(); iter != bankAccounts.end(); ++iter) { try { iter->increaseBalance(50); } catch (...) { // One of the bankAccounts failed to increase by 50, now I need to go // back and decrease by 50 all of the bankAccounts that have already // been increased. } } Is there any elegant way to do this? Maybe with STL algorithms or using reverse iterators?
Here's what I would do: Move the try/catch outside the loop Create a duplicate of the bankAccounts container Iterate over the duplicate container, calling increaseBalance on each item If the loop sucessfully completed, swap() the original and the duplicate container The code would look something like this: std::vector<bankAccount> bankAccounts; ... std::vector<bankAccount> tmp(bankAccounts); try { for (iter = tmp.begin(); iter != tmp.end(); ++iter) { iter->increaseBalance(50); } bankAccounts.swap(tmp); } catch (...) { } Please note that holding a pointer to an object inside a std::vector is generally not that good an idea as the container expects the data stored in it to have value semantics, not pointer semantics. This can lead to dangling pointers, memory leaks and also requires additional cleanup code that you don't need otherwise (to delete the items in container manually). With the code above, I've switched to holding the data inside the vector, if that's not an option you need to ensure that you're using a manual deep copy when you're copying the vector. Actually, you can reduce the code to the following if you assume the same definitions for bankAccounts and tmp: std::for_each(tmp.begin(), tmp.end(), std::mem_fun_ref(&bankAccount::increaseBalance, 50)); bankAccounts.swap(tmp); The main advantage of the code above is that in both cases, it is exception safe without any further special handling.
3,258,869
3,275,445
Qt Creator problem. UI changes not showing when project is built
I'm making changes to a form in Creator but when I build the changes are not being "refreshed". I've gone so far as to remove every element from the form and get rid of every stylesheet but when I build the project I get the same result; as if I had never made a change at all. What gives? Am I missing something obvious? (obvious to everyone but me.. obviously)
I guess you're using QtCreator 2.0? I found the same strange issue. You have two options: Remove the ui_{the_name_of_design}.h from the project's build dir. Then run qmake again. make clean or Build → Rebuild All But the second option even doesn't help with me. By the way that's why is good to use a different build dir than that where the sources are. If some changes don't appear to be applied, just delete the content of build dir, and everything goes fine as well. Cheers
3,259,137
3,259,150
Can I read a dynamical length variable using fread without pointers?
I am using the cstdio (stdio.h) to read and write data from binary files. I have to use this library due to legacy code and it must be cross-platform compatible with Windows and Linux. I have a FILE* basefile_ which I use to read in the variables configLabelLength and configLabel, where configLabelLength tells me how much memory to allocate for configLabel. unsigned int configLabelLength; // 4 bytes char* configLabel = 0; // Variable length fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_); configLabel = new char[configLabelLength]; fread(configLabel,1, configLabelLength,baseFile_); delete [] configLabel; // Free memory allocated for char array configLabel = 0; // Be sure the deallocated memory isn't used Is there a way to read in configLabel without using a pointer? For example is there a solution where I can use the c++ vector library or something where I do not have to worry about pointer memory management.
Just do: unsigned int configLabelLength; // 4 bytes* fread((char *) &configLabelLength, 1, sizeof configLabelLength, baseFile_); std::vector<char> configLabel(configLabelLength); fread(&configLabel[0], 1, configLabel.size(), baseFile_); The elements in a vector are contiguous. * I assume you know that unsigned int isn't necessary always 4 bytes. If you pay attention to your implementation details that's fine, but it'll be a bit easier if you adopt Boost's cstdint.hpp and just use uint32_t.
3,259,366
3,316,664
Cross Compiler Binary Execute Error
I just built a cross compiler using crosstools "mips-unknown-linux-gnu-gcc" and I compiled a hello world program. The compilation went fine using the command: "mips-unknown-linux-gnu-g++ hello.cpp -o hello" but when I run the command "./hello" I get the following error: babbage-dasnyder 50% mips-unknown-linux-gnu-g++ hello.cpp -o hello babbage-dasnyder 51% ./hello ./hello: Exec format error. Wrong Architecture. Why is this? Did I make the wrong cross-compiler? I'm running this on a linux machine. Just as a note, crosstools did say it could run a trivial program: + /home/seas/grad/dasnyder/opt/crosstool/gcc-3.4.5-glibc-2.3.6/mips-unknown-linux-gnu/bin/mips-unknown-linux-gnu-gcc -static hello.c -o mips-unknown-linux-gnu-hello-static + /home/seas/grad/dasnyder/opt/crosstool/gcc-3.4.5-glibc-2.3.6/mips-unknown-linux-gnu/bin/mips-unknown-linux-gnu-gcc hello.c -o mips-unknown-linux-gnu-hello + test -x /home/seas/grad/dasnyder/opt/crosstool/gcc-3.4.5-glibc-2.3.6/mips-unknown-linux-gnu/bin/mips-unknown-linux-gnu-g++ + cat + /home/seas/grad/dasnyder/opt/crosstool/gcc-3.4.5-glibc-2.3.6/mips-unknown-linux-gnu/bin/mips-unknown-linux-gnu-g++ -static hello2.cc -o mips-unknown-linux-gnu-hello2-static + /home/seas/grad/dasnyder/opt/crosstool/gcc-3.4.5-glibc-2.3.6/mips-unknown-linux-gnu/bin/mips-unknown-linux-gnu-g++ hello2.cc -o mips-unknown-linux-gnu-hello2 + echo testhello: C compiler can in fact build a trivial program. testhello: C compiler can in fact build a trivial program. + test '' = 1 + test '' = 1 + test '' = 1 + test 1 = '' + echo Done. Done.
Just as a note, crosstools did say it could run a trivial program: testhello: C compiler can in fact build a trivial program. When you cross-compile to a different architecture, you are generating instructions for the new architecture and thus you may not be able to run these instructions on your current architecture. You are cross-compiling to be able to compile the code on a more powerful machine and then transfer it to the device for testing. If you are wanting to test the code directly on your machine you need to compile with your native architecture's compiler.
3,259,684
3,259,729
Cannot convert 'this' pointer to Class&
Can someone tell why i'm getting this error when compling this class? class C { public: void func(const C &obj) { //body } private: int x; }; void func2(const C &obj) { obj.func(obj); } int main() { /*no code here yet*/}
The C::func() method doesn't promise that it won't modify the object, it only promises that it won't modify its argument. Fix: void func(const C &obj) const { // don't change any this members or the compiler complains } Or make it a static function. Which sure sounds like it should be when it takes a C object as an argument.
3,259,686
3,265,881
std::tr1::function and std::tr1::bind
I have a problem using a very complicated C function in a C++ class (rewriting the C function is not an option). C function: typedef void (*integrand) (unsigned ndim, const double* x, void* fdata, unsigned fdim, double* fval); // This one: int adapt_integrate(unsigned fdim, integrand f, void* fdata, unsigned dim, const double* xmin, const double* xmax, unsigned maxEval, double reqAbsError, double reqRelError, double* val, double* err); I need to supply a void function of type integrand myself, and adapt_integrate will calculate the n-dimensional integral. The code in calcTripleIntegral (below) works as a standalone function if func is a standalone function). I want to pass a (non-static!) class member function as the integrand, as this can be easily overloaded etc... class myIntegrator { public: double calcTripleIntegral( double x, double Q2, std::tr1::function<integrand> &func ) const { //...declare val, err, xMin, xMax and input(x,Q2) ...// adapt_integrate( 1, func, input, 3, xMin, xMax, 0, 0, 1e-4, &val, &err); return val; } double integrandF2( unsigned ndim, const double *x, void *, // no matter what's inside unsigned fdim, double *fval) const; // this qualifies as an integrand if it were not a class member double getValue( double x, double Q2 ) const { std::tr1::function<integrand> func(std::tr1::bind(&myIntegrator::integrandF2, *this); return calcTripleIntegral(x,Q2,func); } } On GCC 4.4.5 (prerelease), this gives me: error: variable 'std::tr1::function func' has initializer but incomplete type EDIT:What is the error in my code? I have now tried compiling with GCC 4.4, 4.5 and 4.6, all resulting in the same error. Either no work has been done on this, or I did something wrong /EDIT Thanks very much! If I'm not clear enough, I'll gladly elaborate. PS: Could I work around this without tr1 stuff by using a function pointer to a function defined somewhere in myIntegrator.cpp? FINAL UPDATE: ok, I was mistaken in thinking TR1 provided a one/two-line solution for this. Bummer. I'm "converting" my classes to namespaces and copypasting the function declarations. I only need one base class and one subclass which reimplemented the interface. C function pointer + C++ class = bad news for me. Thanks anyways for all the answers, you've shown me some dark corners of C++ ;)
If you are just trying to pass a member function into a c-style callback, you can do that with out using std::t1::bind or std::tr1::function. class myIntegrator { public: // getValue is no longer const. but integrandF2 wasn't changed double getValue( double x, double Q2 ) { m_x = x; m_Q2 = Q2; // these could be members if they need to change const double xMin[3] = {0.0}; const double xMax[3] = {1.0,1.0,1.0}; const unsigned maxEval = 0; double reqAbsError = 0.0; double reqRelError = 1e-4; double val; adapt_integrate( 1, &myIntegrator::fancy_integrand, reinterpret_cast<void*>(this), 3, xMin, xMax, maxEval, reqAbsError, reqRelError, &val, &m_err); return val; } double get_error() { return m_error; } private: // use m_x and m_Q2 internally // I removed the unused void* parameter double integrandF2( unsigned ndim, const double *x, unsigned fdim, double *fval) const; static double fancy_integrand( unsigned ndim, const double* x, void* this_ptr, unsigned fdim, double* fval) { myIntegrator& self = reinterpret_cast<myIntegrator*>(this_ptr); self.integrateF2(ndim,x,fdim,fval); } double m_x double m_Q2; double m_err; };
3,259,728
3,273,591
Using Qt signals and slots with multiple inheritance
I have a class (MyClass) that inherits most of its functionality from a Qt built-in object (QGraphicsTextItem). QGraphicsTextItem inherits indirectly from QObject. MyClass also implements an interface, MyInterface. class MyClass : public QGraphicsTextItem, public MyInterface I need to be able to use connect and disconnect on MyInterface*. But it appears that connect and disconnect only work on QObject* instances. Since Qt does not support multiple inheritance from QObject-derived classes, I cannot derive MyInterface from QObject. (Nor would that make much sense for an interface anyway.) There is a discussion of the problem online, but IMO the proposed solution is fairly useless in the common case (accessing an object through its interface), because you cannot connect the signals and slots from MyInterface* but must cast it to the derived-type. Since MyClass is one of many MyInterface-derived classes, this would necessitate "code-smelly" if-this-cast-to-this-else-if-that-cast-to-that statements and defeats the purpose of the interface. Is there a good solution to this limitation? UPDATE: I noticed that if I dynamic_cast a MyInterface* to QObject* (because I know all MyInterface-derived classes also inherit eventually from QObject, it seems to work. That is: MyInterface *my_interface_instance = GetInstance(); connect(dynamic_cast<QObject*>(my_interface_instance), SIGNAL(MyInterfaceSignal()), this, SLOT(TempSlot())); But this really seems like I am asking for undefined behavior....
You found the answer yourself: the dynamic_cast works as you would expect. It is not undefined behavior. If the instance of MyInterface you got is not a QObject, the cast will return null and you can guard yourself against that (which won't happen, since you said all instances of the interface are also QObjects). Remember, however, that you need RTTI turned on for it to work. I would also offer a few other suggestions: Use the Q_INTERFACES feature (it's not only for plug-ins). Then you'd work in terms of QObject and query for MyInterface using qobject_cast when it is really needed. I don't know your problem in detail, but since you know that all MyInterface instances are also QObjects, this seems to be the most sensible approach. Add a QObject* asQObject() abstract method to MyInterface and implement it as { return this; } in all subclasses. Having a QGraphicsTextItem (composition) instead of being one (inheritance).
3,259,741
3,259,766
How do I use a priority queue in c++?
For example we have priority_queue<int> s; which contains some elements. What will be correct form of the following code: while (!s.empty()) { int t=s.pop();// this does not retrieve the value from the queue cout<<t<<endl; }
Refer to your documentation and you'll see pop has no return value. There are various reasons for this, but that's another topic. The proper form is: while (!s.empty()) { int t = s.top(); s.pop(); cout << t << endl; } Or: for (; !s.empty(); s.pop()) { cout << s.top(); << endl; }
3,259,848
3,259,885
c++: set<customClasS* how to overload operator<(const customClass&*...)?
Good Evening (depending on where u are right now). I am a little confused with the stl stuff for sorted sets... I want to store pointers of a custom class in my set and I want them to be sorted by my own criterion and not just the pointer size. Anyone has an idea how to do this? Since it is impossible to do it like operator<(const foo &*rhs, const foo &*lhs){..}; Any suggestions? Thanks in advance and kind regards.
std::set's second template parameter is the method it uses for comparisons. So you can do something like this: struct dereference_compare { template <typename T> bool operator()(const T* pX, const T* pY) const { return *pX < *pY; } }; typedef std::set<T*, dereference_compare> set_type;
3,259,849
3,259,890
How to eliminate the '\n' at the end of a txt file
I'd like to eliminate the extra '\n' at the end of a txt file. Which function can be used to do this job in c / c++. Thanks advanced
One approach would be to iterate of the file line-by-line using getline, saving off that data for later. After each line is read, write the previous line (with \n). When no more data is available write the final line without the \n anymore. Alternately seek to the end to get the size, read the data in blocks of some chunk size, rewriting them until the second-to-last character. If the last character is a \n don't write it, otherwise do write it.
3,259,934
3,260,037
Clearing Contents of a File in C++ knowing only the FILE *
Is it possible to clear the contents (ie. set EOF to the beginning/reset the file) in C++ knowing just the FILE*? I'm writing to a temp file with wb+ access and wish to sometimes clear it and truncate it without adding the calls to fclose and fopen. I dont think it's possible... but if not, why not? Thanks in advance!
It will depend on your platform. The POSIX standard provides ftruncate(), which requires a file descriptor, not a FILE pointer, but it also provides fileno() to get the file descriptor from the FILE pointer. The analogous facilities will be available in Windows environments - but under different names.
3,260,022
3,260,051
How to handle a float overflow?
If a float overflow occurs on a value, I want to set it to zero, like this... m_speed += val; if ( m_speed > numeric_limits<float>::max()) { // This might not even work, since some impls will wraparound after previous line m_speed = 0.f } but once val has been added to m_speed, the overflow has already occurred (and I'm assuming that the same problem would occur if i did if (( m_speed + val ) > ..). How can I check to make sure an overflow is going to occur, without causing an overflow?
You could do: if (numeric_limits<float>::max() - val < m_speed) { m_speed = 0; } else { m_speed += val; } Another method might be: m_speed += val; if (m_speed == numeric_limits<float>::infinity()) m_speed = 0; But do keep in mind when an overflow actually occurs, the result is undefined behavior. So while this probably works on most machines, it isn't guaranteed. You're better of catching it before it happens. Because this isn't trivial to read at first, I'd wrap it into a function: template <typename T> bool will_overflow(const T& pX, const T& pValue, const T& pMax = std::numeric_limits<T>::max()) { return pMax - pValue < pX; } template <typename T> bool will_underflow(const T& pX, const T& pValue, const T& pMin = std::numeric_limits<T>::min()) { return pMin + pValue > pX; } m_speed = will_overflow(m_speed, val) ? 0 : m_speed + val;
3,260,072
3,260,308
Calling command prompt from Qt application without freezing?
In my Qt GUI application, I am calling the command prompt through: system("lots.exe & of.exe && commands.exe"); It opens up the command prompt (like I want it to), but freezes the Qt GUI application until I close the command prompt. Is there someway to prevent this? I saw that there is a QProcess class, but can't get it to bring up the command prompt. Any help would be greatly appreciated!
QProcess is really the answer. If you want to use something like system() you'll have to either put the call in another thread or use popen or something simmilar for your platforms. QProcess does have the setReadChannel which you could use to display your own console window to show the output.
3,260,172
3,260,232
My Cross Compiler Always Compiles the Same File
I'm testing to make sure that my cross compiler is working. When I compile hello world it seems to compile fine but when I change hello.cpp to the same program that loops 1000 times the elf file generated is exactly the same size. No matter what changes I make the file is always the same size and as far as I can tell, has the same contents. What would cause this?
Without more details, it would be hard to help you much. But here are some ideas: As Bobby says, are you sure that you're passing the right files to it? Are you sure that the executable that you're running is the one being generated? Is the compilation actually succeeding? The executable you're running could be the one from the last successful run of the compiler rather than your current attempts to compile. As viraptor suggested, are you absolutely sure that the files are the same? Does diff say that they're the same? It's possible that whatever changes you're making are getting optimized out - especially if you're making changes in code that isn't even called. Really, the odds are that you're not really doing what you think your doing. Make sure that your compilation commands - be they on the command-line or in a make file or whatever - are correct. You should probably delete your executable to make sure that a new one is actually being generated. See what the compiler does if you specifically try and compile junk. It shouldn't compile. If it is, then you're not compiling what you think you're compiling.
3,260,296
3,284,855
Error w/ C++ poco and HTTPSStreamFactory
I am trying to build a C++ app to access a XML resource. Using http the code works fine, from what I can tell from the docs, all I need to do to for the https to work is to make sure ssl is install (yes the dev edition is installed), and change the StreamFactory to HTTPSStreamFactory. Here is the code that works : Poco::Net::HTTPStreamFactory::registerFactory(); Poco::URI uri(argv[1]); std::auto_ptr<std::istream> pStr(Poco::URIStreamOpener::defaultOpener().open(uri)); std::string str; StreamCopier::copyToString(*pStr.get(), str); Here is the code that fails Poco::Net::HTTPSStreamFactory::registerFactory(); Poco::URI uri(argv[1]); std::auto_ptr<std::istream> pStr(Poco::URIStreamOpener::defaultOpener().open(uri)); std::string str; StreamCopier::copyToString(*pStr.get(), str); When I make a request w/ HTTPSStreamFactory this is the error message I get : NULL pointer: _pInstance [in file "/home/chpick/poco-1.3.6p2/Util/include/Poco/Util/Application.h", line 422] I have attached the Application.h inline Application& Application::instance() { poco_check_ptr (_pInstance); return *_pInstance; } Any help would be great. Thanks
I ended up going about it a different way : Here is what I did. const Poco::URI uri(xmlParams.restURI); std::string path(argv[1]); const Poco::Net::Context::Ptr context = new Context(Context::CLIENT_USE, "", "", "", Context::VERIFY_NONE, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context ); Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET, argv[1] ); req.setKeepAlive(false); std::string strToSend = "/"; session.sendRequest(req) << strToSend; Poco::Net::HTTPResponse res; std::istream& rs = session.receiveResponse(res); // typedef std::istream XMLCharInputStream; std::string str; StreamCopier::copyToString(rs, str); std::istringstream istr(str); InputSource source(istr); parser.parse(&source);
3,260,517
3,260,596
Storing map's first element to a vector in the most generic form. Best solution
My goal is to store all the keys of a map (first item) to a vector and I'm doing the following. template < class vecDet> class storeInto { public: storeInto(vecDet& source) : VectorInfo(source) { } ~storeInto(); template <class pairdet> void operator()(pairdet& pairinfo) { VectorInfo.push_back(pairinfo.first); } private: vecDet& VectorInfo; }; template<class mapDet, class vecDet> void storeMapToVector(const mapDet& mapContA, vecDet& vecContA) { for_each(mapContA.begin(), mapContA.end() , storeInto<vecDet>(vecContA)); } Finally, from my main program, I'm calling the storeMapToVector() as follows storeMapToVector<mapinfo,vector<char> >(mapContents, vecContents); where mapinfo is declared as follows typedef map<char,int> mapinfo; Is there a better way to do this? Is there anything wrong with this?
Your code looks like it would work at first glance. However, there's a much simpler way to do this: I haven't evaluated your code, but there is certainly a much easier way to do what you want built into most STL implementations: vecContents.resize(mapContents.size()); std::transform(mapContents.begin(), mapContents.end(), vecContents.begin(), select1st<pair<const char, int> >()); Alternatively: vecContents.resize(mapContents.size()); std::transform(mapContents.begin(), mapContents.end(), vecContents.begin(), select1st<mapinfo::value_type>()); There is 1 wrinkle though - select1st is a SGI extension. It's in almost every STL implementation but where varies. For GNU, you have to do: #include <ext/functional> using __gnu_cxx::select1st; // or just using namespace __gnu_cxx; See this answer for using it in Visual Studio.
3,260,601
3,260,709
How to use KDTree to make top-k query and range query on arbitrary dimensions
I have used KD-tree(libkdtree++) to store a multi-dimensional data set, and the requirements here is this data set can support top-k/range queries on different dimensions. For example, a KDTree<3, Point> tree: to find the top 100 points whose have highest Point[1](y axis) values. From the implementation of libkdtree++, what's similar is the "find_within_range" functions, however it is counted based on "Manhattan distance", which equals max(x_dist, max(y_dist, z_dist)) here. How can I just use range query on one dimension?
Looking at the code, it looks like you can't do that in a straightforward way, ridiculously enough. If I were you I'd be tempted to either hack the library or write my own kd-tree. I'd ask on their mailing list to be sure, but it looks like you might have to do something like this: kdtreetype::_Region_ r(point_with_min_y); r.set_low_bound(min_x, 0); r.set_high_bound(max_x, 0); r.set_low_bound(min_z, 2); r.set_high_bound(max_z, 2); r.set_high_bound((min_y + max_y) / 2, 1); double search_min = min_y, search_max = max_y; // binary search to get 100 points int c; while (c = tree.count_within_range(r) != 100) { if (c > 100) search_max = (search_min + search_max) / 2; else search_min = (search_min + search_max) / 2; r.set_high_bound((search_min + search_max) / 2); } tree.visit_within_range(r, process_min_y_point); This is a horribly inefficient binary search for the Y at which count(points with y <= Y) == 100. I'm not familiar with the library, but that's the best I've got on a cursory inspection.
3,260,922
3,260,963
__typeof -identifier not found
For some reason I keep getting error C3861: '__typeof': identifier not found when I compile my program! I'm including the following libraries: <iostream> <stdlib> <stdio> Any ideas? thanks Edit: More example User.h class User{} main.cpp void f(User* p) { . . . __typeof(p) ... . . . . }
http://msdn.microsoft.com/en-us/library/x2xw8750%28VS.71%29.aspx __typeof only exists for /clr:oldSyntax. Are you trying to use Managed extensions to C++ or are you expecting __typeof to work like C++0x's decltype? If so, if you are using VS 2010 you can use decltype.
3,260,942
3,260,975
removing duplicates from a c++ list
I have been looking for an effective solution to remove duplicates from a C++ list. The list consists of pointers to a class object which has an attribute ID. I want to remove duplicates based on that ID. for my purpose, the unique method of the STL list will work in which we can pass a BinaryPredicate. i.e. void unique( BinPred pr ); I searched on the internet about how to use this method, n got an example in which we can declare a function returning boolean and use the "name" of that function as Binary Predicate. But it's not working. What actually is this binary predicate and how do i use it ? ... Any help will be appreciated. Here is the code snippet: class SP_MDI_View { .. .. bool removeDupli(SP_DS_Node*, SP_DS_Node*); bool DoReductionGSPN(SP_DS_Node*, SP_ListNode*, SP_DS_Node*); .. .. } SP_MDI_View::DoReduction( ... ) { SP_ListNode setZ; // typedef list<SP_DS_Node*> SP_ListNode, where SP_DS_Node is some other class setZ.clear(); setZ.merge(tempsubset); setZ.merge(setX); setZ.push_back(*cs_iter); setZ.unique(removeDupli); //Error here } bool SP_MDI_View::removeDupli(SP_DS_Node* first, SP_DS_Node* second) { return ( (first->GetId())==(second->GetId()) ); }
You could write a function like: bool foo (int first, int second) { return (first)==(second) ); } Also, you might need to declare the function as static if your using it in class.
3,260,947
3,264,137
How is this 3D rendering on the desktop done
I read a topic on OpenGL.org where a guy made this: http://coreytabaka.com/programming/cube-demo/ He said to release the source code but he never did, does anyone how I could get the same idea? Has to do with clearing the window with alpha but drawing on it as well.. just don't get how to get OpenGL setup like that. From there I can do my stuff but I'd like a base for this running in C++ with VisualStudio, Anybody has something like this laying around ? Or can show pieces of the code to get this kind of rendering done.
Render the 3d scene to a pbuffer. Use a color key to blend the pbuffer to screen.
3,261,093
3,261,131
Function template in a namespace in a separate file compiles fine, but the linker cannot find it
This problem is in defining and declaring a function template in a namespace that is defined in an external file from where the function is instantiated. Here's the smallest reproducible example I could come up with. 4 files follow: The function template declaration in a named namespace: // bar.h #include <algorithm> namespace barspace { template <typename Iter> void DoSomething (Iter first, Iter last); } The function template definition in a separate file: // bar.cpp #include "bar.h" namespace barspace { template <typename Iter> void DoSomething (Iter first, Iter last) { typedef typename std::iterator_traits<Iter>::value_type val_t; std::sort (first, last); } } // namespace barspace The header for the main program // foo.h #include "bar.h" #include <vector> Lastly, the main program where the function template is called: //foo.cpp #include "foo.h" int main () { std::vector<double> v_d; for (int i = 0; i < 10; i++) { v_d.push_back (i); } barspace::DoSomething (v_d.begin(), v_d.end()); return 0; } I compile as follows: g++ -c -o bar.o bar.cpp g++ -c -o foo.o foo.cpp These run fine. Now for linking: g++ bar.o foo.o -o foobar And the resulting compiler error about the undefined reference: foo.o: In function `main': foo.cpp:(.text+0x6e): undefined reference to `void barspace::DoSomething<__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > > >(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >)' collect2: ld returned 1 exit status There is an obvious problem with the code not getting made available from within the namespace, or from the bar compilation unit. Furthermore, when I try to place the definition of DoSomething in the bar.h header, as I would to circumvent the issues when defining class template methods in separate .cpp files, I get the same error. Can you shed some light unto my compiler linking error?
You are trying to hide the implementation of your templated function into the cpp file, which, unfortunately, is not possible for most compilers. Templated functions/classes are instantiated when used, so at the point where you are calling DoSomething, the compiler needs the definition of the function to be able to compile it. There are a couple of solutions. Move the function body into the header file. You had trouble doing that before, but i'd say it's related to something else. This is the preferred approach. Include the cpp file from foo.cpp. (wild, but not that uncommon). Instantiate the template for double: // bar.cpp #include "bar.h" namespace barspace { template<> void DoSomething<double> (double first, double last) { typedef typename std::iterator_traits<double>::value_type val_t; std::sort (first, last); } } // namespace barspace
3,261,128
3,261,261
Do templates support variable numbers of parameters
I'm trying to determine if the following scenario is appropriate for a template, and if so how it would be done. I have a base class, event_base. It is inherited by specific types of events. class event_base_c { //... members common to all events ... // serialize the class for transmision virtual std::string serialize(void); }; class event_motion_c : public event_base_c { //... members for a motion event ... // serialize the class for transmission virtual std::string serialize(void); }; class event_alarm_c : public event_base_c { //... members for a motion event ... // serialize the class for transmission virtual std::string serialize(void); }; Events get serialized and sent from one various process to an event logger, which recreates the event object from the serialized data. My question is with regards to the processes that are sending the events. We cannot include a 'send()' method in the event class. I have been told that I need to create an event_sender object that knows how to send the serialized event. So the code from one process might be: if (motion_detected on sensor1) { event_motion_c Event(sensor1, x, y, z); event_sender EventSender; EventSender.report(Event.serialize()); } While some other process might report an alarm using similar code such as: if (alarm) { event_alarm_c Event(alarm_id, alarm_type); event_sender EventSender; EventSender.report(Event.serialize()); } This feels like a template candidate to me, but what stops/confuses me is that the constructor for the different event classes have different number of parameters. I do not know if templates support something like that, and if they do, I don't know the syntax for doing so. I could easily define this as a macro such as: #define SEND_EVENT(evt_class, args...) \ { \ evt_class Event(#args); \ event_sender EventSender; \ \ EventSender.report(Event.serialize()); \ } Then the coder would simply use: SEND_EVENT(event_motion_c, sensor1, x, y, z); and SEND_EVENT(event_alarm_c, alarm_type); But I am hesitant to make a macro for this. Do templates support variable numbers of parameters? And if so, how is that done?
C++ does not support variadic templates, but C++0x will, and some compilers already have support for this (including G++ with the --std=c++0x flag). Wikipedia has examples of how to use this feature.
3,261,178
3,261,189
What is an lvalue reference to function?
In §14.1.4, the new C++0x standard describes the non-types allowed as template parameters. 4) A non-type template-parameter shall have one of the following (optionally cv-qualified) types: integral or enumeration type, pointer to object or pointer to function, lvalue reference to object or lvalue reference to function, pointer to member. What is an "lvalue reference to function"? What does it look like in a template paramemter list. How is it used? I want something like this: //pointer to function typedef int (*func_t)(int,int); int add( int lhs, int rhs ) { return lhs + rhs; } int sub( int lhs, int rhs ) { return lhs - rhs; } template< func_t Func_type > class Foo { public: Foo( int lhs, int rhs ) : m_lhs(lhs), m_rhs(rhs) { } int do_it() { // how would this be different with a reference? return (*Func_type)(m_lhs,m_rhs); } private: int m_lhs; int m_rhs; }; int main() { Foo<&add> adder(7,5); Foo<&sub> subber(7,5); std::cout << adder.do_it() << std::endl; std::cout << subber.do_it() << std::endl; }
Your func_t is of type pointer to function; you can also declare a type that is a reference to a function: typedef int (&func_t)(int, int); Then your main() would look like so: int main() { Foo<add> adder(7,5); Foo<sub> subber(7,5); std::cout << adder.do_it() << std::endl; std::cout << subber.do_it() << std::endl; }
3,261,227
3,318,224
How to serialize an object to send over network
I'm trying to serialize objects to send over network through a socket using only STL. I'm not finding a way to keep objects' structure to be deserialized in the other host. I tried converting to string, to char* and I've spent a long time searching for tutorials on the internet and until now I have found nothing. Is there a way to do it only with STL? Are there any good tutorials? I am almost trying boost, but if there is how to do it with STL I'd like to learn.
I got it! I used strinstream to serialize objects and I sent it as a message using the stringstream's method str() and so string's c_str(). Look. class Object { public: int a; string b; void methodSample1 (); void methosSample2 (); friend ostream& operator<< (ostream& out, Object& object) { out << object.a << " " << object.b; //The space (" ") is necessari for separete elements return out; } friend istream& operator>> (istream& in, Object& object) { in >> object.a; in >> object.b; return in; } }; /* Server side */ int main () { Object o; stringstream ss; o.a = 1; o.b = 2; ss << o; //serialize write (socket, ss.str().c_str(), 20); //send - the buffer size must be adjusted, it's a sample } /* Client side */ int main () { Object o2; stringstream ss2; char buffer[20]; string temp; read (socket, buffer, 20); //receive temp.assign(buffer); ss << temp; ss >> o2; //unserialize } I'm not sure if is necessary convert to string before to serialize (ss << o), maybe is possible directly from char.
3,261,242
3,261,249
problem with casting float -> double in C when fread
I have a problem with casting from float to double when fread; fread(doublePointer,sizeofFloat,500,f); if i change double pointer to float pointer, it works just fine. However,i need it to be double pointer for laster on, and i thought when i write from small data type (float)to bigger data type(double)'s memory, it should be fine. but it turns out it doesnt work as i expected. what is wrong with it, and how do i solve this problem. i know i can solve it by converting it one by one. but i have a huge amount of data. and i dont wanna extra 9000000+ round of converting.. that would be very expensive. and is there any trick i can solve it? is there any c++/c tricks thanks
If you write float-formatted data into a double, you're only going to get garbage as a result. Sure, you won't overflow your buffer, but that's not the only problem - it's still going to be finding two floats where it expects a double. You need to read it as a float, then convert - casting (even implicitly) in this manner lets the compiler know that the data was originally a float and needs to be converted: float temp[500]; int i; fread(temp, sizeof(temp[0]), 500, f); for (i = 0; i < 500; i++) doublePointer[i] = temp[i];
3,261,400
3,262,617
C++0x passing arguments to variadic template functions
What does it mean to take a variable number of arguments by reference? Does it mean that each of the arguments are passed by reference? Consider for example the following functions which performs some processing on each its arguments: void f() // base case for recursion { } template <typename Head, typename ... Tail> void f(Head& head, Tail&... tail) { // Do processing on head process(head); // Now recurse on rest of arguments f(tail...); } Now if I have: int a, b, c; ... f(a, b, c); Will this result in instantiations of f(int&, int&, int&), f(int&, int&), and finally f(int&)? How about if I change the second parameter of f() to be "Tail..." instead of "Tail&...". Will the instantiations now be f(int&, int, int), f(int&, int), and finally f(int&), meaning that e.g. 'c' will be copied through the first two calls and the last call will be modifying a copy instead of the original? Could someone point to a good reference that explains how exactly variadic templates work?
I think your intuition is correct, you can read all the details from the current draft ISO spec (it is not finalized yet) and you can test them out with GCC > 4.3
3,261,402
3,261,447
what is the equivalent to passing by address in c#
void Afunction(int* outvar) { if(outvar) *outvar = 1337; } note the qualities: it allows you to optionally pass a variable by reference, so that it can be set by the function. my closest guess would be (ref int? outvar) but that produces ref (int?) NOT (ref int)? which is what I need this functionality is hardly a scarcely used feature of c or c++, so I assume there must be some equivalent? Edit: so let me try a good example, I think a Colision check function is a prime example, where you have the primary test being whether or not two objects are in contact, then the optional output of the projection vector, calculating the projection vector takes extra time, so you only want to do it if they want it, on the other hand, it usually uses alot of the info calculated when doing the collision test. bool Collide(colObject obj1, colObject obj2, Vector3* projection) { //do a bunch of expensive operations to determine if there is collision if(!collided)return false; if(projection != NULL) { //do more expensive operations, that make use of the above operations already done, //to determine the proj vect *proj = result; } return true; } note that I am currently just porting c++ code to c#, so I might not have though of any real 'out of the box' solutions
The best you can get in C# is Action<int>, like this: void MyFunction(Action<int> valueReceiver) { if (valueReceiver != null) valueReceiver(1337); } Usage: MyFunction(null); MyFunction(v => someVariable = v);