question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,110,824
1,110,890
Eclipse-CDT: How do I handle permission denied errors opening sockets?
My program opens a socket on port 80, but if I don't run it as root (with sudo) then it fails to open the socket with a permission error. This means my application doesn't work when I launch it in the debugger. So: Can I tell Eclipse-CDT somehow to launch the app using sudo? Or, can I somehow enable my program to have...
For debugging purposes, I'd pass --port 8080 as an argument, or use some other configuration method, and open on 8080. No need for root permissions then.
1,110,954
1,110,974
What is the easiest way to call a Java method from C++?
I'm writing a C++ program which needs to be able to read a complex and esoteric file type. I already have a Java program for handling these files which includes functionality to convert them into simpler file formats. My idea is, whenever my program needs to read info from a complex file, to have it call the Java met...
How often do you need to do this? If it's not that often you can shell out and do it there. Just generate the command line to do it. JNI works, but it's a bit of a pain to get set up. Once you have it set up it should work just fine.
1,110,985
1,111,005
Class doesn't support operators
I created a vector out of a struct to store multiple types of values. However, I can't get input to work. #include "std_lib_facilities.h" struct People{ string name; int age; }; int main() { vector<People>nameage; cout << "Enter name then age until done. Press enter, 0, enter to continue.:\n"; ...
Why not do: People p; cin >> p.name; cin >> p.age; nameage.push_back( p ); You can't just cin >> p, as istream doesn't understand how to input a "People" object. So you can either define operator>> for People, or you can just read in the individual fields into a People object. Also, note, you need to push_back an obje...
1,111,078
1,111,099
reduce the capacity of an stl vector
Is there a way to reduce the capacity of a vector ? My code inserts values into a vector (not knowing their number beforehand), and when this finishes, the vectors are used only for read operations. I guess I could create a new vector, do a .reseve() with the size and copy the items, but I don't really like the extra c...
std::vector<T>(v).swap(v); Swapping the contents with another vector swaps the capacity. std::vector<T>(v).swap(v); ==> is equivalent to std::vector<T> tmp(v); // copy elements into a temporary vector v.swap(tmp); // swap internal vector data Swap() would only change the internal data st...
1,111,376
1,111,628
How-to do unit-testing of methods involving file input output?
I'm using C++Test from Parasoft for unit testing C++ code. I came across the following problem. I have a function similar to the next one (pseudocode): bool LoadFileToMem(const std::string& rStrFileName) { if( openfile(rStrFileName) == successfull ) { if( get_file_size() == successfull ) { ...
For unit-testing THIS function, you should use stubs for each of the called functions. Each called function then has its own unit test suite, which exercises that function. For read_entire_file_to_buffer(), you want at least one test file that overflows the buffer, massively, to verify that you do not crash and burn wh...
1,111,415
1,111,683
Make GDC front end emit intermediate C/C++ code?
While investigating the D language, I came across GDC, a D Compiler for GCC. I downloaded the version for MinGW from here: http://sourceforge.net/projects/dgcc/files/ Documentation was almost nonexistent, but it did say that most of the command line switches were the same as for the GCC compiler. However, that doesn'...
No. Front-ends to GCC generate a language-independent representation that is then compiled directly to assembly. This is the case for the C, C++, Obj-C, D, Fortran, Java, Ada, and other front-ends. There is no intermediate C or C++ representation, nor can one be generated.
1,111,440
1,111,470
Undefined reference error for template method
This has been driving me mad for the past hour and a half. I know it's a small thing but cannot find what's wrong (the fact that it's a rainy Friday afternoon, of course, does not help). I have defined the following class that will hold configuration parameters read from a file and will let me access them from my progr...
Templated code implementation should never be in a .cpp file: your compiler has to see them at the same time as it sees the code that calls them (unless you use explicit instantiation to generate the templated object code, but even then .cpp is the wrong file type to use). What you need to do is move the implementation...
1,111,479
1,111,977
Keep a stream from fstream open through member functions
I am trying to keep a stream to a file /dev/fb0 (linux framebuffer) open throughout several Qt member functions. The goal is to use a myscreen::connect function to open up the framebuffer bool myscreen::connect() { std::fstream myscreen_Fb; myscreen_Fb.open("/dev/fb0") QImage* image; image = new QImage(w, h, QImage::F...
That is because myscreen_Fb is, in fact, not declared in the scope of the blit function. Here you declared it in the connect() function. Declare myscreen_Fb as a member variable of the myscreen class. It will be accessible to all functions in that instance of the class. class myscreen { public: myscreen( void ...
1,112,005
1,112,079
Does the anonymous namespace enclose all namespaces?
In C++ you specify internal linkage by wrapping your class and function definitions inside an anonymous namespace. You can also explicitly instantiate templates, but to be standards conforming any explicit instantiations of the templates must occur in the same namespace. AFAICT this should compile, but GCC fails on it:...
An anonymous namespace is logically equivalent to namespace _TU_specific_unique_generated_name { // ... } using namespace _TU_specific_unique_generated_name; A namespace, anonymous or otherwise, has no effect on the linkage of its members. In particular members of an anonymous namespace do not magically get intern...
1,112,126
1,112,131
VS 2005 rebuilds project without changing any files
This is a really strange issue. One day my project started to do a rebuild every time I launched it in the debugger, even if I hadn't changed the code. ie. I would go Build->Build Solution, then Debug->Start Debugging, it would rebuild when I tried to start debugging. The specific file that it recompiles is shown (left...
One possibility is a time stamp issue. Can you check the time on the files and see if their modified date is at some point in the future?
1,112,254
1,112,286
(Obj) C++: Instantiate (reference to) class from template, access its members?
I'm trying to fix something in some Objective C++ (?!) code. I don't know either of those languages, or any of the relevant APIs or the codebase, so I'm getting stymied left and right. Say I have: Vector<char, sizeof 'a'>& sourceData(); sourceData->append('f'); When i try to compile that, I get: error: request for m...
This: Vector<char, sizeof 'a'>& sourceData(); has declared a global function which takes no arguments and returns a reference to Vector. The name sourceData is therefore of function type. When you try to access a member of that, it rightfully complains that it's not a class/struct/union, and operator-> is simply inap...
1,112,456
1,112,493
Cross-platform way of hiding cryptographic keys in C++?
My application needs to use a couple of hard-coded symmetric cryptographic keys (while I know that storing a public key would be the only perfect solution, this is non-negotiable). We want the keys to be stored obfuscated, so that they won't be recognizable by analyzing the executable, and be "live" in memory for as li...
your scoped_key can be simply a KeyHolder object on the stack. Its constructor takes the obfuscated buffer and makes a real key out of it and its destructor zeros out the memory and deallocates the memory. As for how to actually obfuscate the key in the binary, One silly choice you might try is put inside a much larg...
1,112,531
1,112,543
What is the best way to use two keys with a std::map?
I have a std::map that I'm using to store values for x and y coordinates. My data is very sparse, so I don't want to use arrays or vectors, which would result in a massive waste of memory. My data ranges from -250000 to 250000, but I'll only have a few thousand points at the most. Currently I'm creating a std::string w...
Use std::pair<int32,int32> for the key: std::map<std::pair<int,int>, int> myMap; myMap[std::make_pair(10,20)] = 25; std::cout << myMap[std::make_pair(10,20)] << std::endl;
1,112,584
1,112,589
std::vector of functions
I want a std::vector to contain some functions, and that more functions can be added to it in realtime. All the functions will have a prototype like this: void name(SDL_Event *event); I know how to make an array of functions, but how do I make a std::vector of functions? I've tried this: std::vector<( *)( SDL_Event *)>...
Try using a typedef: typedef void (*SDLEventFunction)(SDL_Event *); std::vector<SDLEventFunction> functions;
1,112,716
1,112,728
Why can't you use a Template when iterating
When compiling : #include <vector> template<class T> class foo { void bar() { std::vector<T> x; std::vector<T>::iterator i = x.begin(); } }; int main() { return 0; } I get : # g++ ~test.cpp test.cpp: In member function `void foo<T>::bar()': test.cpp:7: error: expected `;' before "i" S...
You can, but you need to tell it that iterator there is a type (it doesn't know, because in general it can depend on T - as vector is a template type, and could in theory have specializations for some T where iterator is a function or something else). So, you have to use typename to indicate that it is always a type: t...
1,112,724
1,112,739
Why isn't there an operator[] for a std::list?
Can anyone explain why isn't the operator[] implemented for a std::list? I've searched around a bit but haven't found an answer. It wouldn't be too hard to implement or am I missing something?
Retrieving an element by index is an O(n) operation for linked list, which is what std::list is. So it was decided that providing operator[] would be deceptive, since people would be tempted to actively use it, and then you'd see code like: std::list<int> xs; for (int i = 0; i < xs.size(); ++i) { int x = xs[i]; ...
1,112,827
1,112,885
Loading Native DLL as Debug Module in Managed C# Code for Windows CE
I am writing a Windows CE application in C# that references a native C++ DLL (that I am also coding) using the following method: [DllImport("CImg_IP_CE.dll")] public static unsafe extern void doBlur(byte* imgData, int sigma); This actually works fine but I am unable to debug the DLL. When I check the debug modu...
I found the answer through this post: http://www.eggheadcafe.com/conversation.aspx?messageid=31762078&threadid=31762074 In summary, the same question was asked and the response was: No, you can't step from managed code through a P/Invoke call into native code in the Smart Device debugger. You might be able to use A...
1,112,840
1,113,209
Trouble restarting exe
I need to restart the program that im working on after an update has been downloaded except im running into some issues. If i use CreateProcess nothing happens, if i use ShellExecute i get an 0xC0150002 error and if i use ShellExecute with the command "runas" it works fine. I can start the command prompt fine using Cre...
Ok worked it all out in the end. The first time my exe ran it used the default paths and as such loaded vld (a leak detector dll) from the default path. However in the exe i modified the dll path to be the bin folder ([app]\bin) when i restarted the exe using CreateProcess it picked up on a different vld dll (this was ...
1,113,082
1,113,161
Beginner's Guide to Setting Up Qt for C++
I'm interested in playing around with GUIs and I've been trying to set up Qt for Visual Studio 2008 and MinGW but have failed miserably—in that at times I'd compile the library and it still wouldn't work and others the compile would fail. Can anyone recommend a good guide to set up Qt (or another GUI toolkit if setting...
I have covered Qt and VS 2008 integration in my blog. Have a look at it here... http://cplusplus-mortals.blogspot.com/2009/04/qt-part-3-configuration-for-visual.html
1,113,095
1,113,189
From C++ Tools to.... ? Trying to be exposed to modern tools
I'm a long-time C++ programmer developing on Windows, and have been using Visual Studio for developing unmanaged C++. In the past 2-3 months, for the first time, I have been exposed to the world of C# and Java. Man, I'm astounded by the productivity gain! In particular: C# and Java have so many cool tools (TestDriven...
I agree, too. No matter if it is C# or Java. Both are very modern languages and have a huge community contributing new Technologie implementation and Frameworks. Depending on the field you worked in with C++ moving to e.g. C# can be a big productivity boost. The choice of the language also depends on your field. Java i...
1,113,214
1,113,227
C++ development for Linux on Windows
I am trying to setup a development environment for Linux C++ application. Because I'm limited to my laptop (vista) which provides essential office applications, I want to program and access email, word at the same time. I'd prefer a local Windows IDE. SSH to a company linux server and using VI doesn't seem productive t...
Why not install a Linux virtual machine on your laptop, in VMware or similar? That way you can test while you're developing too.
1,113,578
1,114,704
Threading Building Blocks (TBB) for Qt-based CD ripper?
I am building a CD ripper application in C++ and Qt. I would like to parallelize the application such that multiple tracks can be encoded concurrently. Therefore, I have structured the application in such a way that encoding a track is a "Task", and I'm working on a mechanism to run some number of these Tasks concurr...
TBB is suppose to work well, even transparently, with other threading mechanisms so theoretically there should be nothing preventing you from using QT's thread classes in the same program. If there is something that works more naturally with QT threads, like the GUI, use them and keep the TBB stuff segregated as best ...
1,113,694
1,113,814
How to set up a local test/build machine?
I am about to start a new personal project. It aims to be a pretty big one so I thought it would be a good idea to keep some sort of CVS. I have also read lot of interesting stuff about unit testing and I would like to include some system that automatically builds the project and runs a series of test after each check...
It seems that most open source continuous integration servers are built on java and does not support C++ "out-of-the-box". However there are some links you can start with (note that for running most open source continuous integration servers you need a java environment): What continuous integration tool is best for a ...
1,113,704
1,130,203
Cache design: flyweight of mutable entity objects based on an immutable key
A lot of different screens in my app refer to the same entity/business objects over and over again. Currently, each screen refers to their own copy of each object. Also, entity objects may themselves expose access to other entity objects, again new copies of objects are created. I'm trying to find a caching solution. I...
As long as you are happy affecting intrinsic state, then from the internals in boost/flyweight/key_value.hpp it looks like you can get away with a const_cast. If you have your own key extractor you should ensure it doesn't vary with the operations that making x mutable will expose it to. flyweight<key_value<long, Some...
1,113,981
1,114,002
Visual C++ argv question
I'm having some trouble with Visual Studio 2008. Very simple program: printing strings that are sent in as arguments. Why does this: #include <iostream> using namespace std; int _tmain(int argc, char* argv[]) { for (int c = 0; c < argc; c++) { cout << argv[c] << " "; } } For these arguments: prog...
By default, _tmain takes Unicode strings as arguments, but cout is expecting ANSI strings. That's why it's only printing the first character of each string. If you want use the Unicode _tmain, you have to use it with TCHAR and wcout like this: int _tmain(int argc, TCHAR* argv[]) { for (int c = 0; c < argc; c++) ...
1,114,017
1,114,031
Is it good practice to use size_t in C++?
I've seen people use size_t whenever they mean an unsigned integer. For example: class Company { size_t num_employees_; // ... }; Is that good practice? One thing is you have to include <cstddef>. Should it be unsigned int instead? Or even just int? Just using int sounds attractive to me since it avoids stupid bu...
size_t may have different size to int. For things like number of employees, etc., this difference usually is inconsequential; how often does one have more than 2^32 employees? However, if you a field to represent a file size, you will want to use size_t instead of int, if your filesystem supports 64-bit files. Do reali...
1,114,115
1,114,131
Undefined symbol error for base class in C++ shared library
I compiled the following code as a shared library using g++ -shared ...: class Foo { public: Foo() {} virtual ~Foo() = 0; virtual int Bar() = 0; }; class TestFoo : public Foo { public: int Bar() { return 0; } }; extern "C" { Foo* foo; void init() { // Runtime error: undefined symbol: _ZN3FooD2Ev f...
We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor.
1,114,219
1,114,271
Visual C++ 2008 Forms Incredibly Slow
In Visual C++ 2008 Express Edition when adding forms all of the default handlers for buttons, check boxes, etc go into FormName.h by default. So when I do this most of my handler code now goes in the header, then I switch back to the "Design View" to see the form designer. Once I have any reasonable size interface goin...
It's a known problem with using Windows Forms designer with C++ in Visual Studio. You have to move your definitions of member functions manually from a header file to corresponding source file. You might want to take a look at this thread where I raised this issue on msdn c++ group. Welcome to Visual C++. ps. Developer...
1,114,237
1,114,263
Unhandled exception when dereferencing char pointer in Visual C++ 2008
I'm trying to do some classic C development in Visual C++ 2008 that will modify the characters of a string like so: void ModifyString(char *input) { // Change first character to 'a' *input = 'a'; } I'm getting a unhandled exception when I try to change a character. It seems like I could do this in Visual Studio 6...
You're probably passing a string literal somewhere: ModifyString("oops"); // ERROR! C and C++ allow you to implicitly cast from string literals (which have type const char[]) to char*, but such usage is deprecated. String constants are allowed to be allocated in read-only memory (and they usually are), so if you att...
1,114,447
1,185,085
How to use C#-like attributes in C++
I'm considering the use of C++ for a personal project. I would like to make it platform independent (no Mono please, since some platforms don't yet support it), and that's why I considered C++. I have one doubt, however. I've grown quite fond of C#'s attributes, and I would like to know if I can use something similar i...
To "attach additional behavior to a class in runtime" in most any OO language I recommend the Strategy design pattern -- have the class (and/or its instances) hold (through a pointer in C++, a [reseatable] reference in other languages) an instance of a suitable interface / abstract class known as the "strategy interfac...
1,114,594
1,114,631
MSXML DOM: Add namespace declaration to an existing node in a tree
Problem description: Read an xml file, traverse to a particular node (element), if it does not have a particular namespace declaration, add the required namespace declaration, and write out the file. I need to do this in C++ using Microsoft's MSXML DOM APIs. The namespaceURI property on IXMLDOMNode COM object is read-o...
Guessing that you mean to add a default namespace to an element its first important to understand that this is not strictly possible. The namespace that an element's name belongs to forms it fully qualified name hence "adding" a default namespace is tantamount to renaming the element. There is no mechanism built into...
1,114,608
1,114,949
Helgrind for Windows?
Helgrind is a Valgrind tool for detecting synchronisation errors in C, C++ and Fortran programs that use the POSIX pthreads threading primitives. Anyone knows an equivalent tool for windows? After googling a bit I haven't found anything...
For the people that eventually should land there: I've found that: Intel thread checker: should be pretty similar to Hellgrind.
1,114,792
1,115,340
How to initialize a static char* with gettetxt() using local operating system environment?
Is there a standard or common way in C++ to handle static strings that need to be set by gettext()? Here is an example using the answer to Complete C++ i18n gettext() “hello world” example as a base just changing the literal hello world to a static char* hws and char* hw. It looks like hws is getting initialized to the...
You need to split gettext usage into two parts. First, you just mark the string with a macro, such as gettext_noop, so that xgettext will extract it. Then, when you refer to the the global variable, you wrap the access with the true gettext call. See Special Cases in the gettext manual. N.B. Your variable hws is not a ...
1,114,860
1,114,897
Which is the best C++ compiler?
Can a C++ compiler produce a not so good binary? You can think here of the output's robustness and performance. Is there such a thing as the "best" C++ compiler to use? If not, what are the strong points, and of course, the not-so-strong (known Bugs and Issues) points, of the well-known compilers (g++, Intel C++ Compil...
G++ seems to be the most popular. It's free, portable and quite good. The Windows port (MinGW) was really dated the last time I used it (maybe one year ago). The Intel C++ compiler is considered as the one which generates the fastest code (however it's known that it generates bad SIMD code for AMD processors). You can ...
1,114,914
1,114,922
Add Library to Visual Studio 2008 C++ Project
I'm completely new to Visual Studio and I'm having some trouble getting a project started with Visual Studio 2008. I'm experimenting with MAPI, and I'm getting error messages like this when I go to build the project: "unresolved external symbol _MAPIUninitialize@0 referenced in function _main" I know I need to link to...
It's under Project Properties / Configuration Properties / Linker / Input / Additional Dependencies. The help tip at the bottom of the screen says "Specifies additional items add to the line line (ex: kernel32.lib)".
1,114,969
1,114,982
Boost::regex issue, Matching an HTML span element
I don't get it. I created this regular expression: <span class="copy[Green|Red].*>[\s]*(.*)[\s]*<\/span> to match certain parts of HTML code (a part between spans). For instance the following: <span class="copyGreen">0.12</span> <span class="copyRed"> 0.12 </span> Now, this works beautifully with RegexBuddy and o...
For one thing, this: [Green|Red] doesn't do what you think it does. You want: (?:Green|Red) [Green|Red] is a character class made up of the letters GRred|, not a way of alternating between matches. The way you've written it, it will match exactly one of those characters followed by any number of other characters. T...
1,114,991
1,115,199
Lua bindings to C++ and garbage collection
Ok, here's a problem I'm having. I have Lua bindings to a rendering engine that has an internal render manager that keeps its own track of pointers for the render scene and manages them. The problem is that when I'm using it from Lua, if i don't keep a Lua reference to every single object i add to the C++ render manage...
A simple way to prevent Lua from garbage collecting an object is to put that object into a table (call it uncollectable) and then to put that table into the Lua registry. Your other option is to use an extra level of indirection with every Lua object, i.e., use "light userdata". The light userdata points to a pointer ...
1,115,356
1,115,415
Efficiency of c++ built ins
I am fairly new to C++, having much more C experience. I am writing a program that will use the string class, and began to wonder about the efficiency of the "length()" method. I realized though that I didn't have a good answer to this question, and so was wondering if the answer to this and similar questions exist som...
At present, time complexity of size() for all STL containers is underspecified. There's an open C++ defect report for that. The present ISO C++ standard says that STL containers should have size() of constant complexity: 21.3[lib.basic.string]/2 The class template basic_string conforms to the requirements of a Sequenc...
1,115,428
1,116,078
Run an Application in GDB Until an Exception Occurs
I'm working on a multithreaded application, and I want to debug it using GDB. Problem is, one of my threads keeps dying with the message: pure virtual method called terminate called without an active exception Abort I know the cause of that message, but I have no idea where in my thread it occurs. A backtrace would re...
You can try using a "catchpoint" (catch throw) to stop the debugger at the point where the exception is generated. The following excerpt From the gdb manual describes the catchpoint feature. 5.1.3 Setting catchpoints You can use catchpoints to cause the debugger to stop for certain kinds of program events, such as C++...
1,115,464
1,115,484
MSVC: union vs. class/struct with inline friend operators
This piece of code compiles and runs as expected on GCC 3.x and 4.x: #include <stdio.h> typedef union buggedUnion { public: // 4 var init constructor inline buggedUnion(int _i) { i = _i; } friend inline const buggedUnion operator - (int A, const buggedUnion &B) { ...
It is difficult to say which one is right, since unnamed structs are not allowed by the standard (although they are a common extension), and as such the program is ill-formed. Edit: It does seem to be a bug in msvc, since the following code, which is perfectly valid, fails to compile. union buggedUnion { friend bug...
1,115,474
1,115,927
C++: TR1 vs GSL vs Boost for statistical distributions?
in my previous post I was asking how to generate numbers following a normal distribution. Since I have also other distributions to generate and I saw 3 libraries might provide them (GSL, TechnicalReport1(doc link?), Boost), I was wondering which one you would choose. As a side note: the reference platform for my appli...
Here are some notes on getting started with random number generation using C++ TR1.
1,115,511
1,115,533
Set IP_HDRINCL to setsockopt function in win32
I'm fighting with raw sockets in Win32 and now I'm stuck, the soetsockopt function give me the 10022 error (invalid argument), but I think I pass the correct arguments... of course I'm wrong u_u' sock = socket(AF_INET,SOCK_RAW,IPPROTO_UDP); if (sock == SOCKET_ERROR) { printf("Error socket(): %d", WSAGetLastError());...
As far as I remember you need to use int on = 1 instead of char...
1,115,633
1,115,649
Should I use std:: and boost:: prefixes everywhere?
In my C++ code I don't use the declarations using namespace std; or using namespace boost;. This makes my code longer and means more typing. I was thinking about starting to use the "using" declarations, but I remember some people arguing against that. What is the recommended practice? std and boost are so common there...
I use using namespace only in C++ files, not in headers. Besides, using hole namespace not needed in most of times. For instance, you could write using boost::shared_ptr or using std::tr1::shared_ptr to easily switch between shared_ptr implementations. Sample: #include <iostream> using std::cout; int main() { cou...
1,115,876
14,764,809
Autocompletion in Vim
In a nutshell, I'm searching for a working autocompletion feature for the Vim editor. I've argued before that Vim completely replaces an IDE under Linux and while that's certainly true, it lacks one important feature: autocompletion. I know about Ctrl+N, Exuberant Ctags integration, Taglist, cppcomplete and OmniCppComp...
Try YouCompleteMe. It uses Clang through the libclang interface, offering semantic C/C++/Objective-C completion. It's much like clang_complete, but substantially faster and with fuzzy-matching. In addition to the above, YCM also provides semantic completion for C#, Python, Go, TypeScript etc. It also provides non-seman...
1,115,891
1,115,895
Covariant virtual functions and smart pointers
In C++, a subclass can specify a different return type when overriding a virtual function, as long as the return type is a subclass of the original return type (And both are returned as pointers/references). Is it possible to expand this feature to smart pointers as well? (Assuming a smart pointer is some template clas...
Is it possible to expand this feature to smart pointers as well? (Assuming a smart pointer is some template class) No: C++ doesn't know/allow covariant or contravariant templates. There's no relation between types Ptr<A> and Ptr<B>, even if A inherits from B.
1,116,018
1,116,035
Is assert and unit-testing incompatible?
I have some concerns related to the fact of testing some functions containing the assert macro from assert.h. If the assert fails the test fails also. This leaves me with some test cases that will never work. For example a function instead of indicating failure (return false or something similar) asserts. Is there a so...
No, unit testing is what you do during development. Asserts are a run-time construct. In my experience, most of the time asserts are turned off in production. But you should always be testing. CppUnit is a fine test framework. It's part of the nUnit family for C++.
1,116,040
1,116,055
Memory-efficient C++ strings (interning, ropes, copy-on-write, etc)
My application is having memory problems, including copying lots of strings about, using the same strings as keys in lots of hashtables, etc. I'm looking for a base class for my strings that makes this very efficient. I'm hoping for: String interning (multiple strings of the same value use the same memory), copy-on-wr...
If most of your strings are immutable, the Boost Flyweight library might suit your needs. It will do the string interning, but I don't believe it does copy-on-write.
1,116,187
1,116,427
Just adding some documentation triggers recompilation: Is there a solution?
Sometimes, when I look through my header files I'd like to add something little to the (doxygen) documentation. That might be a quick note about the use of some function parameter, or just fixing a little typo. But then I think: Oh no, that'll trigger a recompile on the next make call! And for certain basic headers the...
How about checking out (you do version control, don't you?) another copy of the codebase in a different directory, just for these kinds of edits? It can be a separate branch, or not. Then, when these kinds of small changes occur to you, you just make them here. You can commit them directly: now they are in a safe place...
1,116,213
1,116,259
Profiling instructions
I want to count several cpu instructions in my code. e.g. I would like to know how many additions, how many multiplications, how many float operations, how many branches my code executes. I currently use gprof under Linux for profiling my c++ code but it only gives the number of calls to my functions, and I manually es...
You may be able to use Valgrind's Callgrind with the --dump-instr=yes flag to achieve this
1,116,225
1,117,132
Refusing connection from a host
I'm writing a simple tcp server application using sockets. As far as I know I can obtain the client's ip address and port after calling accept(). Now lets assume I have a banlist and I want to ban some ip addresses from my server. Is there a better way than accepting the connection and then dropping it? Is there a way...
The TCP implementation normally completes the TCP 3-way handshake before the user process even has access to the connection, and the accept() function merely gets the next connection off the queue. So it is too late to pretend that the server is down. This works the same way for regular TCP data; the TCP implementati...
1,116,503
1,116,583
High-quality libraries for C++
We all know about Boost. What other free C++ libraries are worth using? Why? Are they easily usable with common compilers?
See: What modern C++ libraries should be in my toolbox?
1,116,569
1,213,720
desktopdock or stardock in Qt
Is there any opensource/sample application in qt/c++, just like desktopdock or objectdock..?
XQDE is an OSX-style dock written in Qt.
1,116,602
1,116,646
Where can I see the list of functions that interact with errno?
In the book "The C Programming Language" it says: "Many of the functions in the library set status indicators when error or end of file occur. These indicators may be set and tested explicitly. In addition, the integer expression errno (declared in <errno.h>) may contain an error number that gives further informat...
The standard says this about errno: The value of errno is zero at program startup, but is never set to zero by any library function. The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in...
1,116,641
1,116,763
Is returning by rvalue reference more efficient?
for example: Beta_ab&& Beta::toAB() const { return move(Beta_ab(1, 1)); }
Beta_ab&& Beta::toAB() const { return move(Beta_ab(1, 1)); } This returns a dangling reference, just like with the lvalue reference case. After the function returns, the temporary object will get destructed. You should return Beta_ab by value, like the following Beta_ab Beta::toAB() const { return Beta_ab(1...
1,116,654
1,116,656
Function template with an operator
In C++, can you have a templated operator on a class? Like so: class MyClass { public: template<class T> T operator()() { /* return some T */ }; } This actually seems to compile just fine, but the confusion comes in how one would use it: MyClass c; int i = c<int>(); // This doesn't work int i = (int)c(); // Ne...
You need to specify T. int i = c.operator()<int>(); Unfortunately, you can't use the function call syntax directly in this case. Edit: Oh, and you're missing public: at the beginning of the class definition.
1,116,721
1,116,816
COM: how to get more details about COM errors?
Greets, When working with DirectX, you get this nice header to #include called DxErr9.h which has really helpful functions like: DXGetErrorString9 and DXGetErrorDescription9 They tell you everything you need to know about the error given the HR. But now working with COM and OLE, I find I'm kind of on my own with th...
Additionally, you should look at the error info. Part of the COM system is the concept of the error information, which is a per-thread global which can be set and cleared at various times. You query for it in response to an error, and if it is set, it will have more useful information than just looking at the HRESULT. ...
1,116,735
1,116,843
i++ less efficient than ++i, how to show this?
I am trying to show by example that the prefix increment is more efficient than the postfix increment. In theory this makes sense: i++ needs to be able to return the unincremented original value and therefore store it, whereas ++i can return the incremented value without storing the previous value. But is there a good ...
In the general case, the post increment will result in a copy where a pre-increment will not. Of course this will be optimized away in a large number of cases and in the cases where it isn't the copy operation will be negligible (ie., for built in types). Here's a small example that show the potential inefficiency of ...
1,116,779
1,116,792
using header files from another project (directory)
I am using Visual Studio 2008, and I need to use certain header files from another project. I have tried to add the path in "Additional Include Directories" in C/C++ General properties pane, but my project still puts out the same errors (fatal error C1083: Cannot open include file: 'tools/rcobject.h'. All the other cp...
In the "Additional Include "Directories", did you put the path to the "tools" directory, or the path to the directory that includes the "tools" directory? It needs to be the latter. How the preprocessor works to resolve #include directives, is to take the path specified in the #include and then append it to each of the...
1,117,101
1,208,159
<list> throws unhandled exception when calling push_front()
I'm working on a GUI in SDL. I've created a slave/master class that contains a std::list of pointers to it's own slaves to create a heirarchy in the GUI (window containing buttons. Button a label and so on). It worked fine for a good while, until I edited a completely different class that doesn't effect the slave/maste...
Finally after looking through every nook and cranny I've found the bug! It was completely unexpected and I feel a bit embarrassed about it. I had recently re-arranged the files. Prior to that I had generic classes in one folder and my user interface files in a subfolder. I copied the GUI files to the main folder and I ...
1,117,230
1,117,476
Best aproach to java like adapters event-handling in C++
I'm doing some research in how to implement a event-handling scheme in C++ that can be easyest as its to implements an adpter to a class in java. The problem is that with the approach shown below, I will need to have all adapters already implemented with its function overriding in the devived class (because the linker ...
Take a look at Boost.Signals library for an example of how you can implement event handling without classes with virtual functions (http://www.boost.org/doc/libs/1_39_0/doc/html/signals.html).
1,117,284
1,117,297
C++ file parse number of arguments
I got a pack of c++ files with static source code (already developped, not needed to do anything to them). There is an program/lib/way to get a list of the number of params each function withing one of those files? I mean, getting a result like: #File a.cpp ##a() -> 3 paramss ##foo() -> 0 params (void) #File b.cpp ##t...
You could try running Doxygen over the source files. Since the content is (presumably) undocumented, you need to configure doxygen to extract content from undocumented files. If you just want to browse a list of the available functions, you could use the HTML output. You could also configure Doxygen output to be XML, a...
1,117,292
1,117,299
What's the Right Way to use the rand() Function in C++?
I'm doing a book exercise that says to write a program that generates psuedorandom numbers. I started off simple with. #include "std_lib_facilities.h" int randint() { int random = 0; random = rand(); return random; } int main() { char input = 0; cout << "Press any character and enter to generate a...
Option 2 isn't difficult, here you go: srand(time(NULL)); you'll need to include stdlib.h for srand() and time.h for time().
1,117,424
1,117,435
Data structure similar to a 2-argument map
Is there a data structure (readily available in STL or boost), that accepts two arguments and maps it to a certain value? Examples would be for returning certain information in a coordinate grid or getting the weight of an edge in a graph: coordinate_quadrant(-1,-1) = 3 weight_of(u,v) = 10 The quadrant example could ...
You could use std::map< std::pair<Type1,Type2>, Type3 >.
1,117,481
1,117,484
Can the default destructor be generated as a virtual destructor automatically?
Can the default destructor be generated as a virtual destructor automatically? If I define a base class but no default destructor, is there a default virtual destructor generated automatically?
No. There is a cost associated with making a method virtual, and C++ has a philosophy of not making you pay for things that you don't explicitly state that you want to use. If a virtual destructor would have been generated automatically, you would have been paying the price automatically. Why not just define an empty v...
1,117,486
1,121,418
WinForm not receiving messages except right after creation
I've got some unmanaged code sitting in a DLL. It publishes some methods that my calling (managed) code uses to hook into some COM notifications. Rather than deal with unmanaged code calling back into managed code, I've created a hidden Control derived object and am passing its handle property which the unmanaged cod...
Did you try passing your managed window's handle as a HandleRef? C# can marshal a HandleRef as an IntPtr and vice versa, I've seen Microsoft use that trick quite a bit when decompiling some of their stuff. You can also load up a .Net profiler and watch the GC. It would be nice to know if your app is breaking right af...
1,117,693
1,118,444
Initializing template base-class member types in derived-class initializer lists
Here is some code outlining a problem I've been wrestling with. The final problem (as far as g++ is concerned at the moment) is that: "error: 'Foo-T' was not declared in this scope" when performing the Bar::Bar(...) constructor routine. Otherwise, the problem I'm attempting to learn my way through is one of setting bas...
The Foo_T type will not be looked up in the base class when used in the derived (Bar) constructor. Bar (const foo_arg_t bar_arg, const a_arg_t a_arg) : Foo<T>(bar_arg) // base-class initializer { Foo_T = TypeA(a_arg); TypeA, etc. // Won't compile, per the standard } This is per the C++ standard, which says unq...
1,117,755
1,117,767
What is the difference between function template and template function?
What is the difference between function template and template function?
The term "function template" refers to a kind of template. The term "template function" is sometimes used to mean the same thing, and sometimes to mean a function instantiated from a function template. This ambiguity is best avoided by using "function template" for the former and something like "function template inst...
1,117,831
1,123,427
Local System only ACL in Windows
I am using a named pipe for communications between two processes and want to restrict acess to any user on the local system in Windows. I am building up and ACL for use in the SECURITY_ATTRIBUTES passed to CreateNamedPipe. I am basing this code on that from Microsoft. SID_IDENTIFIER_AUTHORITY siaLocal = SECURITY_LOCAL_...
I am afraid this is a cross between RTFM and c's complete lack of strict typing. The second parameter for AllocateAndInitializeSid is actually a count of the sub authorities not the first sub authority. So by changing the code to: SID_IDENTIFIER_AUTHORITY siaLocal = SECURITY_LOCAL_SID_AUTHORITY; if( !AllocateAndInitial...
1,117,873
1,118,283
pointer to const vs usual pointer (for functions)
Is there any difference between pointer to const and usual pointer for functions? When it is suitable to use const qualifier for stand alone functions? I wrote short sample to illustrate my question: #include <iostream> using namespace std; int sum( int x, int y ) { return x + y; } typedef int sum_func( int, int ); i...
Your code is ill-formed with regard to C++03. You can not ever construct a const (or volatile) qualified function type. Whenever you do, your program becomes ill-formed. This rule has been changed for C++1x, to make the compiler ignore the const / volatile. C++ compilers will usually already implement this rule even in...
1,118,203
1,181,799
Error linking with GCC 4.3.2 on RHEL 5.3 and libstdc++.so. Any GCC gurus?
Trying to use the RHEL5.3 GCC 4.3.2 compiler to build my software on that platform. I get the following error no matter what I try when compiling with -O2, but it builds fine without optimization. Any ideas? /usr/bin/ld: myapp: hidden symbol `void std::__ostream_fill<char, std::char_traits<char> >(std::basic_ostream<...
It turns out to be a GCC bug in RHEL 5.3 :-/. https://bugzilla.redhat.com/show_bug.cgi?id=493929. I sent an email to the maintainer, Jakub Jelinek, who said that RHEL 5.4 (which is due out soon) will have a fix and also will bump to GCC 4.4. A workaround is to use -fno-inline, but this has some obvious drawbacks.
1,118,227
1,118,483
glibmm timeout signal
I'm working on a plugin for a smaller application using gtkmm. The plugin I'm working on checks certain conditions (the date had changed and a new day started) after every minute and starts some actions if the conditions are true. In the initialization part of the plugin I have the following piece of code that uses Gli...
I've tried to reproduce with the following code : #include <iostream> #include <glibmm.h> unsigned counter = 0; bool checkNewDay() { std::cout << "Checking for new day ..." << std::endl; counter++; std::cout << "counter = " << counter << std::endl; return true; } int main() { static const unsig...
1,118,272
1,118,299
Is there a database implementation that has notifications and revisions?
I am looking for a database library that can be used within an editor to replace a custom document format. In my case the document would contain a functional program. I want application data to be persistent even while editing, so that when the program crashes, no data is lost. I know that all databases offer that. On ...
Berkeley DB is an undemanding, light-weight key-value database that supports locking and transactions. There are bindings for it in a lot of programming languages, including C++ and python. You'll have to implement revisions and notifications yourself, but that's actually not all that difficult.
1,118,428
1,118,943
Portable periodic timer for period around 100ms
Hej! I am looking for a portable way of periodically dispatching a task in a C++ project. The use of libraries such as boost should be avoided in this particular project. The resolution requirement is not too serious: between 5Hz to 20Hz on an average Netbook. The project uses OpenGL to render the HMI but since I am wo...
As most straightforward way to achieve this is to use Sleep(100ms) in a cycle, all you need is a portable Sleep. For Linux it can be implemented as follows void Sleep(unsigned long ulMilliseconds) { struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = ulMilliseconds * 1000; select(1, NULL, NULL...
1,118,482
1,118,739
C++ TR1: how to use the normal_distribution?
I'm trying to use the C++ STD TechnicalReport1 extensions to generate numbers following a normal distribution, but this code (adapted from this article): mt19937 eng; eng.seed(SEED); normal_distribution<double> dist; // XXX if I use the one below it exits the for loop // uniform_int<int> dist(1, 52); for (unsigne...
This definitely would not hang the program. But, not sure if it really meets your needs. #include <random> #include <iostream> using namespace std; typedef std::tr1::ranlux64_base_01 Myeng; typedef std::tr1::normal_distribution<double> Mydist; int main() { Myeng eng; eng.seed(1000); My...
1,118,680
1,118,696
Explicit keyword on multi-arg constructor?
I recently came across some weird looking class that had three constructors: class Class { public: explicit Class(int ); Class(AnotherClass ); explicit Class(YetAnotherClass, AnotherClass ); // ... } This doesn't really make sense to me - I thought the explicit keyword is to protect ...
In C++11 multi-parameter constructors can be implicitly converted to with brace initialization. However, before C++11 explicit only applied to single-argument constructors. For multiple-argument constructors, it was ignored and had no effect.
1,118,905
1,118,939
Why am I getting a symbol lookup error?
I am writing a library, which is dynamically loaded in my main-application with dlsym. I have the following files: library.h #include <ilibrary.h> #include <igateway.h> class LibraryImpl; class Library: public ILibrary { public: static ILibrary* instance(); IGateway* getGateway() const; protected: Libra...
I put the error through c++filt, it says that the mangled name stands for BCGateway::instance() This suggests that you call BCGateway::instance() somewhere and forgot to link against BCGateway.o or you even forgot to define BCGateway::instance().
1,119,134
1,119,334
How do malloc() and free() work?
I want to know how malloc and free work. int main() { unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char)); memset(p,0,4); strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes** cout << p; free(p); // Obvious Crash, but I need how it works and why crash. cout << p; ret...
OK some answers about malloc were already posted. The more interesting part is how free works (and in this direction, malloc too can be understood better). In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will ...
1,119,220
2,496,429
Finding perfmon counter id via winreg
I have an app that collects Perfmon counter values through the API exposed in winreg.h - in order to collect Perfmon counter values I must make a call to RegQueryValueExW passing in the id of the Perfmon counter I'm interested in, and in order to obtain that ID I need to query the registry for the list of Perfmon count...
I realize that this is old, but in case it helps: Tim is right, parsing the binary data yourself is difficult. Prepare yourself for a world of pain. I'd recommend PDH (encapsulates the registry accesses for you), or if that fails, WMI (though note that WMI is much slower). You cannot get data for just a performance co...
1,119,357
1,120,022
Platform C Preprocessor Definitions
I'm writing a small library in C++ that I need to be able to build on quite a few different platforms, including iPhone, Windows, Linux, Mac and Symbian S60. I've written most of the code so that it is platform-agnostic but there are some portions that must be written on a per-platform basis. Currently I accomplish th...
I have this sourceforge pre-compiler page in my bookmarks.
1,119,370
1,119,390
Where do I find the definition of size_t?
I see variables defined with this type but I don't know where it comes from, nor what is its purpose. Why not use int or unsigned int? (What about other "similar" types? Void_t, etc).
From Wikipedia The stdlib.h and stddef.h header files define a datatype called size_t1 which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t. The actual type of size_t is platform-dependent; a common mistake is ...
1,119,375
1,119,464
Why can't I const_cast the return of the conversion operator?
I've got a conversion operator that returns a const pointer, and I need to const_cast it. However, that doesn't work, at least under MSVC8. The following code reproduces my problem: class MyClass { public: operator const int* () { return 0; } }; int main() { MyClass obj; int* myPtr; // comp...
To make it work you have to do : myPtr = const_cast<int*>(static_cast<const int*>(obj)); When you const_cast directly, the compiler look for the cast operator to int*.
1,119,401
1,119,436
How do I dynamically bind a socket to only one network interface?
Currently I do the following to listen on any available port on all interfaces: // hints struct for the getaddrinfo call struct addrinfo hints, *res; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // Fill in addrinfo with getaddrinfo if (getadd...
Take a look at SO_BINDTODEVICE. Tuxology has a good description of this
1,119,443
1,119,454
Speed of C program execution
I got one problem at my exam for subject Principal of Programming Language. I thought for long time but i still did not understand the problem Problem: Below is a program C, that is executed in MSVC++ 6.0 environment on a PC with configuration ~ CPU Intel 1.8GHz, Ram 512MB #define M 10000 #define N 5000 int a[M][N]; v...
Row-major order versus column-major order. Recall first that all multi-dimensional arrays are represented in memory as a continguous block of memory. Thus the multidimensional array A(m,n) might be represented in memory as a00 a01 a02 ... a0n a10 a11 a12 ... a1n a20 ... amn In the first loop, you run through ...
1,119,574
1,123,502
Unique Machine ID for a Windows CE Device
I need to generate unique machine ID for a CE 6.0 device. On Windows OS, I was using the WMI to obtain some hardware identifiers from which I constructed this ID. Apparently, WMI is not supported on Win CE so I am looking for alternatives. At the moment I am playing with OS image that I have constructed in Platform Bui...
If you're building the OS, then you need to implement the IOCTL so that KernelIoControl returns something. How its derived is completely up to you. I've seen the MAC as a base, as well as the serial number of on-board flash. How you'd do that for your particular platform I can't say, but as an example for x86 you mig...
1,119,585
1,121,161
VIM: is there an easy way to manage Visual Studio solutions / makefile projects from Vim?
I tried using Visual Studio instead of VIM(+plugins), but to be honest - the only advantage of VS over VIM is it's ability to automatically manage my project. I know of existence of ViEmu for VS, but I would like to do the opposite - is there any way to manage projects from within VIM? I tried both c.vim plugin and P...
Maybe I don't understand the question. VS is full features IDE - you edit, compile and debug without leaving it. vim in contrast is not IDE - its very powerful text editor. Yet vim has some build-in functionality oriented for programmers (e.g. :make command, compilation, automatic indentation etc.). vim is coming fro...
1,119,683
1,119,916
Live RX and TX rates in linux
I'm looking for a way to programatically (whether calling a library, or a standalone program) monitor live ip traffic in linux. I don't want totals, i want the current bandwidth that is being used. I'm looking for a tool similar (but non-graphical) to OS X's istat menu's network traffic monitor. I'm fairly certain some...
We have byte and packet counters in /proc/net/dev, so: import time last={} def diff(col): return counters[col] - last[iface][col] while True: print "\n%10s: %10s %10s %10s %10s"%("interface","bytes recv","bytes sent", "pkts recv", "pkts sent") for line in open('/proc/net/dev').readlines()[2:]: iface, counter...
1,120,478
1,120,614
Capturing a time in milliseconds
The following piece of code is used to print the time in the logs: #define PRINTTIME() struct tm * tmptime; time_t tmpGetTime; time(&tmpGetTime); tmptime = localtime(&tmpGetTime); cout << tmptime->tm_mday << "/" <<tmptime->tm_mon+1 << "/" << 1900+tmptime->tm_year << " " << tmptime->tm_hour << ":" << tmptime->tm_mi...
To have millisecond precision you have to use system calls specific to your OS. In Linux you can use #include <sys/time.h> timeval tv; gettimeofday(&tv, 0); // then convert struct tv to your needed ms precision timeval has microsecond precision. In Windows you can use: #include <Windows.h> SYSTEMTIME st; GetSystemT...
1,120,721
1,120,829
Where to find API documentation for NVIDIA 3D Vision?
I'd like to start coding for NVIDIA 3D Vision and wonder where can I find the documentation for it?
The docs should be on the nVidia developer site, though I think that it may be called 3D sterio there. As there isn't a visible heading for either, the info you're looking for may be included in the OpenGL or DirectX docs.
1,120,813
1,120,835
Am I going to be OK for threading with STL given these conditions?
I have a collection of the form: map<key, list<object> > I only ever insert at the back of the list and sometimes I read from the entire map (but I never write to the map, except at initialization). As I understand it, none of the STL containers are thread safe, but I can only really have a maximum of one thread per...
If the map is never modified at all during the multi-threaded scenario, then you're fine. If each thread looks at its own list, then that's thread-private data, so you're also fine. Take care not to try and lookup keys with [] because that will insert (modify) if the key doesn't exist in the map yet. However, I'm curio...
1,120,831
1,121,276
Linking VS2005 static library with gcc in Windows
Is it possible to link a static library built with VS2005 into an application that is to be built with gcc (in Cygwin)?
Unlike UNIX where there was no standard C++ ABI for years, Windows has had a standard C++ ABI from the beginning. So, yes, it's possible. But it can be difficult.
1,120,833
1,121,016
Derived template-class access to base-class member-data
This question is a furtherance of the one asked in this thread. Using the following class definitions: template <class T> class Foo { public: Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg) { /* do something for foo */ } T Foo_T; // either a TypeA or a TypeB - TBD foo_arg_t _foo_ar...
You can use this-> to make clear that you are referring to a member of the class: void Bar<T>::BarFunc () { std::cout << this->_foo_arg << std::endl; } Alternatively you can also use "using" in the method: void Bar<T>::BarFunc () { using Bar<T>::_foo_arg; // Might not work in g++, IIRC std::cou...
1,120,903
1,121,519
Keeping objects in sync across a network?
In my application, I have two DLLs. One is written in C# and the other in C++. They communicate with each other across a network. Each has a list of object instances that are expected to be in sync with each other at all times. What network libraries are available for doing this?
This is actually a fairly difficult problem to get done correctly, and as such, there are many ways to approach it. I think the best way to do it would be to use something like Protocol buffers, which has both a c++ and c# library. Depending on the size of your data, you could simply serialize the entire data object, a...
1,121,032
1,121,139
Detect if C++ binary is optimized
Is there a flag or other reliable method to detect if a compiled C++ binary was compiled with optimizations? I'm okay with compiler-specific solutions. Edit: This is for a build deployment system, which could accidentally deploy binaries that were not built properly. A water-tight solution is unlikely, but it will sa...
Recent versions of GCC have a way to report which flags were used to compile a binary (third bullet point). There is a related command line switch (--fverbose-asm) that "only records the information in the assembler output file as comments, so the information never reaches the object file." The --frecord-gcc-switches ...
1,121,052
1,121,089
Can you put a library inside a namespace?
I am working with OpenCV and I would like to put the entire library inside it's own namespace. I've looked around quite a bit but haven't found an answer... Can you do this without modifying the library source code? If then how?
Basically no. You could attempt to do it by writing wrappers and macros, but it would be unlikely to work. If you really need to do this, a better approach is to fork the library and make the needed namespace additions. Of course, you would REALLY need to do it to take this approach, and I suspect you don't.
1,121,509
1,122,170
C++ include file browser
I have a very large project with tons of convoluted header files that all include each other. There's also a massive number of third-party libraries that it depends on. I'm trying to straighten out the mess, but I'm having some trouble, since a lot of the time I'll remove one #include directive only to find that the ...
http://www.profactor.co.uk/includemanager.php
1,121,791
1,122,073
Optimisation of division in gcc
Here's some code (full program follows later in the question): template <typename T> T fizzbuzz(T n) { T count(0); #if CONST const T div(3); #else T div(3); #endif for (T i(0); i <= n; ++i) { if (i % div == T(0)) count += i; } return count; } Now, if I call this temp...
I'm guessing its just the severely old GCC version you are running. The oldest compiler I have on my machine - gcc-4.1.2, performs the fast way with both the non-const and the wrap versions (and does so at only -O1).
1,121,971
1,121,997
What is the purpose of the ## operator in C++, and what is it called?
I was looking through the DXUTCore project that comes with the DirectX March 2009 SDK, and noticed that instead of making normal accessor methods, they used macros to create the generic accessors, similar to the following: #define GET_ACCESSOR( x, y ) inline x Get##y() { DXUTLock l; return m_state.m_##y;}; ... GET_A...
Token-pasting operator, used by the pre-processor to join two tokens into a single token.
1,122,096
1,122,128
What is the underlying type of a c++ enum?
This may have been answered elsewhere but I could not find a suitable response. I have this code: enum enumWizardPage { WP_NONE = 0x00, WP_CMDID = 0x01, WP_LEAGUES = 0x02, WP_TEAMS = 0x04, WP_COMP = 0x08, WP_DIVISIONS = 0x10, WP_FORMULAS = 0x20, WP_FINISHED = 0x40, }; Whi...
From N4659 C++ 7.2/5: For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which in...
1,122,195
1,122,578
c++ templatized interface
This is best described in pseudo-code: class Thing {}; interface ThingGetter<T extends Thing> { T getThing(); } class Product extends Thing {}; class ProductGetter<Product> { Product getThing() { // Some product code } } class SpecialProductGetter extends ProductGetter { Product getThing() {...
Since the question comes from someone with a Java background, I will interpret it in Java terms. You want to define a generic interface that will return an object derived from T: template<typename T> struct getter { virtual T* get() = 0; // just for the signature, no implementation }; Note the changes: the function...
1,122,203
1,124,146
How do I get all the shader constants (uniforms) from a ID3DXEffect?
I'm creating an effect using hr = D3DXCreateEffectFromFile( g_D3D_Device, shaderPath.c_str(), macros, NULL, 0, NULL, &pEffect, &pBufferErrors ); I would like to get all the uniforms that this shader is using. In OpenGL I used glGetActiveUniform and glGet...
D3DXHANDLE handle = m_pEffect->GetParameterByName( NULL, "Uniform Name" ); if ( handle != NULL ) { D3DXPARAMETER_DESC desc; if ( SUCCEEDED( m_pEffect->GetParameterDesc( handle, &desc ) ) ) { // You now have pretty much all the details about the parameter there are in "desc". } } You can also it...