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,737,193
1,737,401
Different implementation of a templated class method for a particular class template type
I have a templated class with a method for which I need a different implementation for a specific template type. How do i get it done?
You can specialise the method for that type. E.g. template<typename T> struct TemplatedClass { std::string methodA () {return "T methodA";} std::string methodB () {return "T methodB";} std::string methodC () {return "T methodC";} }; // Specialise methodA for int. template<> std::string TemplatedClass<int...
1,737,324
1,756,489
Experiences using Wt C++ framework?
Has anyone seriously used Wt? Did it work well? Did you experience certain limitations? Or advantages? Wt is a C++ library for developing web applications. Please avoid the discussion of whether C++ is a good language for web development. I just want to give Wt a try because it seems like it could be a fun thing to ...
I have not personally used the framework, but have discussed it with a few people that have. They didn't really have any limitations, but I found it hard to believe they were compiling every time. Their main comment was that it was quite a light load on the server in terms of memory usage. Personally, I think the inter...
1,737,668
1,737,708
How do I integrate Boost into a Visual C++ project?
I'm trying to link up some of the boost stuff with a visual C++ project of mine and am not sure what the best way to do this is, I'm specifically interested in the singleton class.
I don't want to RTFM but Boost Getting Started on Windows is the first place to go. As you can see from the TOC, it is a very coherent walkthrough. Get Boost The Boost Distribution Header-Only Libraries Build a Simple Program Using Boost Build From the Visual Studio IDE Or, Build From the Command Prompt Error...
1,737,955
1,738,371
C++ Data Structure for storing 3 dimensions of floats
I've implemented a 3D strange attractor explorer which gives float XYZ outputs in the range 0-100, I now want to implement a colouring function for it based upon the displacement between two successive outputs. I'm not sure of the data structure to use to store the colour values for each point, using a 3D array I'm lim...
I'd probably think bout some kind of 3-d binary search tree. template <class KEY, class VALUE> class BinaryTree { // some implementation, probably available in libraries public: VALUE* Find(const KEY& key) const { // real implementation is needed here return NULL; } }; // this tree no...
1,738,089
1,738,173
When trying to include '#include <boost/regex.hpp>' I get: 1>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc100-mt-gd-1_39.lib'
Not sure why i get that, I downloaded libs from here and while I have a lib called 'libboost_regex-vc90-mt-gd-1_39.lib I don't have one which is called 'libboost_regex-vc100-mt-gd-1_39.lib', renaming the one with vc90 to vc100 works but I'm not sure if this is the ideal solution? #include "stdafx.h" #include <regex> #i...
You are probably using Visual Studio 2010 (this is where vc100 comes from), but the downloaded lib was built with 2008 (vc9) Visual Studio 2010 comes with TR1, include <regex> and enjoy.
1,738,401
1,738,489
libtiff.3.dylib: unknown required load command 0x80000022
Has anyone found a fix for this? I read that it has something to do with new dylib format in Snow Leopard... (This is the lib I get back from MacPorts.) Thanks, rui
What are you trying to use that library with? Chances are you have an old version of some build tool or app. Have you updated all of your MacPorts installation? sudo port selfupdate sudo port -u upgrade outdated EDIT: Based on your additional information, more questions: You have -I /sw/include and -L /sw/lib which ...
1,738,536
1,738,550
Abstract class in c++
Let's say I've got class: class Bad_Date { private: const char* _my_msg; public: const char* msg() const { return _my_msg; } }; And I would like to not be able to create any object of this class but I don't really want to put anything else there and make it pure virtual fnc. Is there any other way to make this class...
If you need a base class, you may need a virtual destructor. Make it pure virtual and you've got your abstract class. If you don't need a virtual destructor (ie the class is not used polymorphically), you can make the constructor protected (not private).
1,738,671
1,738,678
Pass enums by value or reference?
My general rule is to pass by value for primitive types and pass by reference for objects (obviously const'd if need be). However, I'm not sure what route to take with enumerated types. I'd assume that pass by value is preferred since they are seemingly small, but I'd like to hear others thoughts.
No other thoughts. An enum is just an integral value in a fancy dress (or suit, if you prefer). It has no internal structure and will travel in a register given a chance. If you'd pass an int by value, pass an enum that way, too.
1,738,673
1,873,172
Streaming the desktop
I want to create a C++ cross-platform (Windows and MacOS X) application that sends the screen as a video stream to a server. The application is needed in the context of lecture capture. The end result will be a Flash based web page that plays back the lecture (presenter video and audio + slides/desktop). I am currently...
My solution was to write a simple GUI application in Qt that invokes a VLC process in the background. This works really well.
1,738,790
1,740,919
Build management in C++ & good IDEs on Linux
I am starting to write a moderately sized project in C++ requiring a fairly large amount of files and dependencies on other projects. Do you think manually maintaining a Makefile for this project is the best approach? Are there other better alternatives for C++ that make build management and dependency management of fi...
Others have already recommended using CMake. To my mind you should manage your project with CMake then decide on your favourite IDE. CMake allows you to describe the project to be built, instead of how to build it. For example: I want to create a shared library called foo with source files a.cpp, b.cpp and c.h and ...
1,738,928
1,738,943
How to break into code when a file has been touched
I inherited an application using a large number of text based files for configuration. The file's names are constructed dynamically in the software, so I can't search directly for a file name in the source code. Is there any way to break into a program running in the debugger when it touches a particular text file?
If you know the place where the files are being open or if the dynamically created file names are assigned to some variable, create an conditional breakpoint that breaks the code execution only if the filename is matching the file that you're interested in.
1,739,102
1,739,115
Concatenating strings in macros - C++
What's the easiest way to concatenate strings defined in macros. i.e. The pseudo code I'm looking for would be like: #define ROOT_PATH "/home/david/" #define INPUT_FILE_A ROOT_PATH+"data/inputA.bin" #define INPUT_FILE_B ROOT_PATH+"data/inputB.bin" ... #define INPUT_FILE_Z ROOT_PATH+"data/inputZ.bin" The only way I kno...
The compiler will automatically concatenate adjacent strings: #define ROOT_PATH "/home/david/" #define INPUT_FILE_A ROOT_PATH "data/inputA.bin" Or more generic: #define INPUT_FILE_DETAIL(root,x) root #x #define INPUT_FILE(x) INPUT_FILE_DETAIL(ROOT_PATH "data/", x)
1,739,134
1,739,148
Print text into a Windows input text box
Background I'm trying to write an application in C++ that will run on Vista. The application will take input from a the user (via input text box), perform some manipulation of that text, and will direct the user to click on an input box in another application. I'd like my application to print text into the second appli...
You are proposing to violate very basic Windows user interface conventions. I strongly recommend that you push the manipulated text onto the clipboard, and let the user use Paste to put it in the target text box. If you insist on your original plan, you will have to use complex Win32 APIs to get a handle to the target ...
1,739,154
1,739,476
Any likely causes of a double-free in ncurses?
I have an ncurses app that does the following, sometimes instantly after launch, sometimes after some fiddling. malloc: *** error for object 0x100300400: double free Program received signal SIGABRT, Aborted (gdb) where #0 0x00007fff846a7426 in read () #1 0x00007fff83f3d775 in _nc_wgetch () #2 0x00007fff83f3de3f in wget...
It looks like you are using glibc, likely on an x86_64 Linux system. The tool to use for any kind of heap corruption on Linux/x86_64 is Valgrind. It will just immediately give you the answer, so there is no point in guessing where the problem might be (and it could be anywhere).
1,739,184
1,739,210
How does one properly use the Unix exec C(++)-command?
Specifically, I need to call a version of exec that maintains the current working directory and sends standard out to the same terminal as the program calling exec. I also have a vector of string arguments I need to pass somehow, and I'm wondering how I would go about doing all of this. I've been told that all of this ...
If you have a vector of strings then you need to convert it to an array of char* and call execvp #include <cstdio> #include <string> #include <vector> #include <sys/wait.h> #include <unistd.h> int main() { using namespace std; vector<string> args; args.push_back("Hello"); args.push_back("World"); ...
1,739,259
1,739,265
How to use QueryPerformanceCounter?
I recently decided that I needed to change from using milliseconds to microseconds for my Timer class, and after some research I've decided that QueryPerformanceCounter is probably my safest bet. (The warning on Boost::Posix that it may not works on Win32 API put me off a bit). However, I'm not really sure how to imple...
#include <windows.h> double PCFreq = 0.0; __int64 CounterStart = 0; void StartCounter() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) cout << "QueryPerformanceFrequency failed!\n"; PCFreq = double(li.QuadPart)/1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; } doub...
1,739,374
1,739,381
Does C++ have standard libraries for common File Utilities
I am looking for standard libraries in C++ that would allow me to do things like: Traverse a directory recursively search for files within a directory Check if file exists, folder exists or not and create it if not present. Check a folder hierarchy exists or create it if not found. Equivalent of mkdir -p Uncompressing...
No, but if you want a good library implementation, you might look into Boost.Filesystem; it has widely used, cross-platform facilities for doing most of those things.
1,739,614
1,739,685
What is the difference between Go's multithreading and pthread or Java Threads?
What is the difference between Go's multithreading approach and other approaches, such as pthread, boost::thread or Java Threads?
Quoted from Day 3 Tutorial <- read this for more information. Goroutines are multiplexed as needed onto system threads. When a goroutine executes a blocking system call, no other goroutine is blocked. We will do the same for CPU-bound goroutines at some point, but for now, if you want user-level parallelism ...
1,739,643
1,767,635
Easier way to find (visual) position of QModelIndex in QTreeView
I'm interested in calculating the physical position of a node in QTreeView and can't find a way to do this (other than calculating it myself, which is cumbersome and error prone given the robustness of QTreeView). Is there a standard way of finding the draw position of data associated with a QModelIndex (something simi...
There's a method in QAbstractItemView that does exactly what I needed: The signature is: virtual QRect visualRect ( const QModelIndex & index ) const
1,739,777
1,739,788
C++ Classes - Pointers question
I had a quiz at school and there was this question that I wasn't sure if I answered correctly. I could not find the answer in the book so I just wanted to ask you. Point* array[10]; How many instances of class Point are created when the above code is called? I answered none because it only creates space for 10 instanc...
It creates no Points. What it does is creates an array of ten pointers that can point to Point objects (it doesn't create space for ten instances). The pointers in the array are uninitialized, though, and no Point objects are actually created.
1,740,006
1,740,059
Custom C++ manipulator problem
I'm trying to implement my own stream manipulator inside my logging class. It's basically endline manipulator which changes state of a flag. However when I try to use it, I'll get: ftypes.cpp:57: error: no match for ‘operator<<’ in ‘log->Log::debug() << log->Log::endl’ /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../...
That's not how manipulators work - it's all about types. What you want is something like: class Log { ... struct endl_tag { /* tag struct; no members */ }; static const struct endl_tag endl; ... LogStream &debug() { /* somehow produce a LogStream type here */ } } LogStream &operator<<(LogStream &s, const struct endl_t...
1,740,093
1,745,781
Unable to use SetTransform in D3D9
What might stop IDirect3DDevice9::SetTransform from working? I've looked at alot of tutorials for using transformation matrices in Direct3D9, including this one here. And as far as I can tell, they all do it the same way. I'm trying to write some code just to translate a texured polygon. I call SetTransform with a matr...
You set "D3DFVF_TLVERTEX" which means that you are supplying "Transform and Lit" vertices in the vertex buffer, therefore the device is not going to apply a transformation matrix to these vertices.
1,740,366
1,740,400
Programmatically parse and edit C++ Source Files
I want to programmatically parse and edit C++ source files. I need to change/add code in certain sections of code (i.e. in functions, class blocks, etc). I would also (preferably) be able to get comments as well. Part of what I want to do can be explained by the following piece of code: CPlusPlusSourceParser cp = new C...
This is similar to AST from C code If your comfortable with Java antlr can easily parser your code into an abstract syntax tree, and then apply transformation to that tree. A default AST transform is to simply print out the original source.
1,740,449
1,740,469
String concatenation query c++
#include <stdio.h> #include <string.h> #include <conio.h> #include <iostream> using namespace std; char a[21]; // If this is put inside the function unter -> junk output char* b=""; void unter() { char *new_str = ""; strcpy(a, new_str); char str_temp[10]=""; int chnum =0, neig...
a is a char array and b is a pointer that points to a, so when printing them, they always print the same thing. When you move the declaration for a into unter, it is destroyed when unter returns, leaving b a dnagling pointer, so you get garbage when you print it.
1,740,640
1,740,702
fcntl issues compiling C++
{net04:~/xxxx/wip} gcc -o write_test write_test.c In file included from write_test.c:4: global.h:10: warning: `b' initialized and declared `extern' This code uses fcntl.h and the file-handling functions defined - like open(), write(), close() etc.. The code compiles and works as intended. {net04:~/xxxx/wip} gcc -o w...
C++ is more strict about headers - you need: #include <unistd.h> to properly get the functions indicated. global.h should not be defining b - headers shouldn't initialise variables. When compiling you should use -Wall -Werror and that will force you to fix all the dodgy bits of your code. To get exit() cleanly you'll...
1,740,989
1,741,094
How do I extract the network protocol from the source code of the server?
I'm trying to write a chat client for a popular network. The original client is proprietary, and is about 15 GB larger than I would like. (To be fair, others call it a game.) There is absolutely no documentation available for the protocol on the internet, and most search results only come back with the client's scripti...
If your original code is encrypted with some well known library like OpenSSL or Ctypto++ it might be useful to write your wrapper for the main entry points of these libraries, then delagating the call to the actual library. If you make such substitution and build the project successfully, you will be able to trace ever...
1,741,099
1,741,108
VC++ Error on template inheritance
This is child's play, but I'm a bit of a vc n00b. I get an error: error C2143: syntax error : missing ',' before '<'. on the second line of the following code: template<int i, int j> class B : public A<i, j> { } template<int i, int j> class A { } Thanks for the help!
You forgot the semi-colons and the declaration of A(just declare A before B to avoid writing the declaration): template<int i, int j> class A { }; template<int i, int j> class B : public A<i, j> { };
1,741,485
1,741,602
How to convert string from one charset to another in C++?
How to convert string from one charset to another in C++ in a portable way? For example I want to convert to wstring to UTF-8 character array or . How to do this? I am asking some standard way no chilkatsoft, wxWidgets, Qt. Its a plain C++ application. Though some simple class or methods will do the job.
The Boost Serialization library contains a UTF-8 codecvt facet.
1,741,720
1,741,761
c++ problem with polymorphism and vectors of pointers
Consider the following example code: class Foo { }; class Bar : public Foo { }; class FooCollection { protected: vector<shared_ptr<Foo> > d_foos; }; class BarCollection : public FooCollection { public: vector<shared_ptr<Bar> > &getBars() { // return d_foos won't do here... } }; I have a prob...
template<class T> class MyContainer { vector<shared_ptr<T> > d_foos; public: vector<shared_ptr<T> > & getVector(); }; class FooCollection : public MyContainer<Foo> { }; class BarCollection : public MyContainer<Bar> { };
1,741,775
1,741,948
How do I catch keyboard events in X11?
I'm writing an LCD controller, and one feature I want to add is the ability to catch keyboard strokes so that you can do stuff like instant messaging over the LCD. I found xsnoop.c but it's outdated. I'm using xorg-x11-server 1.6.4-0.1.fc11 on Fedora 11. I'm also using Qt. I didn't find anything in the docs that might ...
I've just tried compiling xsnoop.c and there was a line #include <vroot.h> which needs to be just removed, but apart from that it works.
1,741,997
1,742,055
Separating Enums from Class Definitions using Namespaces in C++?
I'm working with a legacy class that looks like this: class A { enum Flags { One = 1, Two = 2 }; }; I'd like to pull out all the enums into a new namespace defined in a new header: // flags.h namespace flags { enum Flags { One = 1, Two = 2 }; }; Then pull these enums back into the class so that I can include j...
A using directive is illegal at class scope. Instead of a namespace you could define a class and then inherit from it: struct flags { enum Flags { One=1, Two=2 }; }; class A : public flags { ... }; But this looks like a misuse of inheritance to me, to be honest. As an alternative you could bite the bullet and use...
1,742,273
1,782,435
Qt (Creator) with WinSocks (ws2_32)
I want to use an older code-fragment in my Qt-project, which is using WinSocks. I created my program with Qt Creator and I don't know, how I can link to the ws2_32-Library. I already added LIBS += -lws2_32 to my .pro, but nothing happened. So how can I link to this library? edit: Where can I find the ws2_32.lib to inc...
ok, when you know it, it's really simple.The Qt-SDK comes with a WinSock2-Library, called libws2_32.a.The only thing you have to do, is to enter this line in your .pro: LIBS += C:\Qt\2009.04\mingw\lib\libws2_32.a this includes the winsock2-library to your project and you have nothing else to do. You may do this s...
1,742,282
1,742,685
Crash within CString
I am observing a crash within my application and the call stack shows below mfc42u!CString::AllocBeforeWrite+5 mfc42u!CString::operator=+22 No idea why this occuring. This does not occur frequently also. Any suggestions would help. I have the crash dump with me but not able to progress any further. The operation ...
I have a suggestion that might be a little frustrating for you: CString::AllocBeforeWrite does implicate to me, that the system tries to allocate some memory. Could it be, that some other memory operation (specially freeing or resizing of memory) is corrupted before? A typical problem with C/C++ memory management is, t...
1,742,329
1,742,564
When implementing several COM interfaces at once how do I upcast to IUnknown?
Suppose my COM object implements two or more COM interfaces: class CMyClass : public IPersistFile, public IPersistStream { }; when implementing QueryInterface() I need to be able to return an IUnknown* pointer. Since both base interfaces are derived from IUnknown I cannot upcast implicitly - such upcast would be umbig...
Mark Ransom already gave the correct answer - any will do, as long as it's consistent - but picking the first one has one minor advantage. Due to layout rules, the IUnknown* of the first interface will point to the start of the object. Any other IUnknown* will point to subsequent vtable pointers elsewhere in the object...
1,742,657
1,742,827
C# objects and C++ objects, the difference
When creating an object instance as such in C# Myclass mc = new Myclass(); This mc is now a reference to a Myclass object created in memory. It's like a 'pointer' to that memory. Is it the same or comparable to doing this in (Managed or Unmanaged) C++: MyCppClass *mcCppClass = new MyCppClass(); Because this actuall...
An important difference, which no one seems to have mentioned yet, is this: Myclass mc = new Myclass(); in C#, this is the only correct way to create a new object. When you need an object, this is how you create it. MyCppClass *mcCppClass = new MyCppClass(); In C++, this is how you can create an object, and how you o...
1,742,700
1,742,905
Does a destructor always get called for a delete operator, even when it is overloaded?
I'm porting a bit of an old code from C to C++. The old code uses object-like semantics, and at one point separates object destruction from freeing the now-unused memory, with stuff happening in between: Object_Destructor(Object *me) { free(me->member1), free(me->member2) } ObjectManager_FreeObject(ObjectManager *me, ...
You can separate destruction from deletion, but you probably don't really want to. If you allocate the memory with new char[] or malloc, and then call placement new, then you can separate destruction (which you do by directly calling the destructor) from deletion (or free). But then you're no longer calling the class's...
1,742,750
1,742,776
How is a union different from a struct? Do other languages have similar constructs?
Possible Duplicate: Difference between a Structure and a Union in C I see this code for a union in C: union time { long simpleDate; double perciseDate; } mytime; What is the difference between a union and a structure in C? Where would you use a union, what are its benefits? Is there a simila...
So in your example, when I allocate time: int main() { time t; } The compiler can interpret the memory at &t as if it is either a long: t.simpleDate; or as if its a double: t.perciseDate; So if the raw hex of the memory at t looks like 0x12345678; That value can be "parsed" as either a double or long, depending...
1,742,848
1,742,911
Why exactly do I need an explicit upcast when implementing QueryInterface() in an object with multiple interfaces()
Assume I have a class implementing two or more COM interfaces: class CMyClass : public IInterface1, public IInterface2 { }; Almost every document I saw suggests that when I implement QueryInterface() for IUnknown I explicitly upcast this pointer to one of the interfaces: if( iid == __uuidof( IUnknown ) ) { *ppv =...
The problem is that *ppv is usually a void* - directly assigning this to it will simply take the existing this pointer and give *ppv the value of it (since all pointers can be cast to void*). This is not a problem with single inheritance because with single inheritance the base pointer is always the same for all classe...
1,742,859
1,742,961
std::vector::reserve performance penalty
inline void add(const DataStruct& rhs) { using namespace boost::assign; vec.reserve(vec.size() + 3); vec += rhs.a, rhs.b, rhs.c; } The above function was executed for about 17000 times and it performed (as far as I can see. There was some transformation involved) about 2 magnitudes worse with the call to vect...
GCC implementation of reserve() will allocate exact number of elements, while push_back() will grow internal buffer exponentially by doubling it, so you are defeating the exponential growth and forcing reallocation/copy on each iteration. Run your test under ltrace or valgrind and see the number of malloc() calls.
1,743,053
1,743,112
Are there C/C++ compilers that do not require standard library includes?
All applicants to our company must pass a simple quiz using C as part of early screening process. It consists of a C source file that must be modified to provide the desired functionality. We clearly state that we will attempt to compile the file as-is, with no changes. Almost all applicants user "strlen" but half o...
GCC will happily compile the following code as is: main() { printf("%u\n",strlen("Hello world")); } It will complain about incompatible implicit declaration of built-in function ‘printf’ and strlen(), but it will still produce an executable. If you compile with -Werror it won't compile.
1,743,277
1,743,284
Is there a tool for Visual Studio to track (or break on) variable value?
Is there is a tool or a setting in the Visual Studio debugger to stop on breakpoints or when a variable is set to a particular value? I mean, if I know that value will be set to "HELLO," I want the debugger will stop the same way it would if it reached a breakpoint?
You're looking for a Conditional Breakpoint.
1,743,309
1,743,345
Displaying an EMF file
Got a quick question about Windows EMF/EMF+ files. Reading the documentation, I realize that an EMF/EMF+ file is just a bunch of GDI/GDI+ commands. So what's the supported way for reading in an EMF/EMF+ file and then displaying it in either MFC or WinForms? Thanks, Alex
Here is how it is done (for EMF) in MFC (or did I misunderstand the question?) Here is more elaborate article on the subject.
1,743,365
1,745,508
Is there a C or C++ embeddable library for reading email through pop?
I'm looking for a not too big C or C++ library that would allow to read email through pop on Windows. The smallest the better. It would be better if it could support SSL.
There is also this CPJNOPO3Connection which supports ssl. I have not used this library but the SMTP one with great success both on Windows and Windows CE
1,743,511
1,743,581
How to programmatically tell if two variables are on the same stack? (in Windows)
I'm in a thread. I have an address. Is that address from a variable on the same stack that I'm using? static int *address; void A() { int x; atomic::CAS(address, 0, &x); // ie address = &x // ... } void B() { int y; int * addr = atomic::read(address); // ie addr = address if (addr && on_same_st...
How about something crazy like (untested): declspec(__thread) void* stackBottom; void Thread1Routine(void* arg) { volatile int bottom; stackBottom = &bottom; ... (do stuff which ends up calling on_same_stack()) ... } bool on_same_stack(void* p) { volatile int top; return ((LONG_PTR)p >= (LONG_PTR)&top) &&...
1,743,803
1,743,874
C++ linker - Lack of duplicate symbols
Why does the following code not give me a duplicate symbol linker error for Impl? I ran across this problem in some code I inherited and I'm recreating a shorter version here for simplicity. I have two classes, Foo and Bar, that each define a different version of the same struct (Impl) in each of their .cpp files. So ...
You're violating the one definition rule, and the compiler/linker isn't required to tell you about it.
1,743,832
1,743,866
C++ Access to command line arguments outside main?
I have a couple command line apps that both end up calling into com objects. Rather than adding new interface to these com objects, can they access the parameters passed from the command line? Edit: Sort of how I can call GetModuleFileName to get the file name. Im wondering if there is an equivalent method to get the a...
The Win32 API that you're looking for is: GetCommandLine. Your COM object probably needs to run within your process though. To convert the command line to an argv style array of strings, call the CommandLineToArgvW function.
1,743,964
1,745,302
Determining value based on adjacent cells in matrix
Input: a maze represented by an arbitrarily sized matrix of bools. (Out of bounds counts as 0) 00100 00100 01110 11111 01110 00100 Output: a nice looking representation of the maze (neighbourhood gets mapped to a wchar_t): ┌─┐ │1│ ┌┘1└┐ ┌┘111└┐ |11111| └┐111┌┘ └┐1┌┘ └─┘ Edit: Basically each 0 gets map...
Inspired by Doug T.'s solution I wrote the following myself. Basically I run through the matrix twice (poor performance :/). The first time I'll draw walls around every 1 in the matrix, I do this with bit-masks. The second time I clean up all the "inwards-pointing"-walls. Example setup: // Add padding to output-matrix...
1,743,999
1,744,021
Function returning variable by reference?
In C++, function() = 10; Works if function returns a variable by reference, right? Would someone please elaborate on this in detail?
Consider this piece of code first int *function(); ... *function() = 10; Looks similar, isn't it? In this example, function returns a pointer to int, and you can use it in the above way by applying a unary * operator to it. Now, in this particular context you can think of references as "pointers in disguise". I.e. ref...
1,744,016
1,744,061
The Price of DuplicateHandle
I'm writing a class library that provides convenient object-oriented frontends to the C API that is the Windows Registry. I'm curious, however, what the best course of action is for handling HREGs, for instances where my key class is copied. I can either Allocate a heap integer and use it as a reference count. Call Re...
I suspect you'll find that DuplicateHandle has very little overhead. The kernel already manages a reference count for each open object, and DuplicateHandle adds a new entry to the kernel handle table for the destination process, and increments the object reference count. (DuplicateHandle also normally does security che...
1,744,144
1,744,302
Adding an include guard breaks the build
I added #ifndef..#define..#endif to a file of my project and the compiler fails. As soon as I remove it or put any other name in the define it compiles fine. What could be the problem? Sounds like the file is already declared, but I do not know where. I'm fine just removing it, but I really want to know why this is ...
Is this macro used as an include guard? If so, it sounds like you're duplicating a name used elsewhere. This is a common problem when people don't think about the scope an include guard must have—you should include much more information in it than just the file name. Include guard goals: generate once, when creating...
1,744,194
1,744,328
Visualizing C++ to help understanding it
I'm a student who's learning C++ at school now. We are using Dev-C++ to make little, short exercises. Sometimes I find it hard to know where I made a mistake or what's really happing in the program. Our teacher taught us to make drawings. They can be useful when working with Linked Lists and Pointers but sometimes my...
This is unrelated to the actual title but I'd like to make a simple suggestion concerning how to understand what's happening in the program. I don't know if you've looked at a debugger but it's a great tool that can definitely vastly improve your understanding of what's going on. Depending on your IDE, it'll have more ...
1,744,407
1,744,793
Cache Line Alignment (Need clarification on article)
I've recently encountered what I think is a false-sharing problem in my application, and I've looked up Sutter's article on how to align my data to cache lines. He suggests the following C++ code: // C++ (using C++0x alignment syntax) template<typename T> struct cache_line_storage { [[ align(CACHE_LINE_SIZE) ]] T da...
You can't have arrays of size 0, so 1 is required to make it compile. However, the current draft version of the spec says that such padding is unecessary; the compiler must pad up to the struct's alignment. Note also that this code is ill-formed if CACHE_LINE_SIZE is smaller than alignof(T). To fix this, you should pro...
1,744,513
1,745,413
SetupDiGetDeviceInterfaceDetail returns only "\" for the path of all USB HID objects
I can tell how many USB HID devices I have (7), but every time I try to get details on any device, the path returned for it is always "\", making it so that I can't access the device at all. I'm using code that is very similar in procedure to this code: HANDLE connectDeviceNumber(DWORD deviceIndex) { GUID hidGUID;...
Surely you are compiling with UNICODE defined? Then you Log() formatting string is wrong. Fix: Log("Opening device with path: %ls", deviceDetail->DevicePath);
1,744,523
1,745,377
SSL_accept with blocking socket
I made a server with SSL and blocking sockets. When I connect with telnet (so it does not do the handshake), the SSL_accept blocks indefinitely and blocks every new handshake/accept (and by definition new connections). How can I solve this awful problem ?
Why not just set the socket stream to non-blocking mode before calling SSL_accept(), and then block on something like select() with a timeout if SSL_accept() returns SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE? Alternatively, you can block on select() before calling SSL_accept(). Either should work. That way you can...
1,744,888
1,744,917
Cannot Debug Unmanaged Dll from C#
I have a DLL that was written in C++ and called from a C# application. The DLL is unmanaged code. If I copy the DLL and its .pdb files with a post build event to the C# app's debug execution dir I still can't hit any break points I put into the DLL code. The break point has a message attached to it saying that "no sym...
To debug into your C++ DLL you need to enable mixed mode debugging on the startup application in your solution. Right click on project -> Properties Go to Debug Tab Check "Enable unmanaged code debugging" This will allow you to debug into native code for an F5 style scenario. If you want to enable it for attachin...
1,744,902
1,839,629
How might I obtain the IContextMenu that is displayed in an IShellView context menu?
Building a file open dialog replacement. Much of it works now, but I would like to generate the view-mode drop-down for the toolbar directly from the shell view object. Looking at IShellView2, I can see IShellView2::GetView() will give me the FOLDERVIEWMODE's supported. However, that doesn't give me the names of thes...
Try IShellView::GetItemObject with SVGIO_BACKGROUND as uItem to get a IContextMenu on the view object : http://msdn.microsoft.com/en-us/library/bb774832%28VS.85%29.aspx
1,745,045
29,316,214
std::locale breakage on MacOS 10.6 with LANG=en_US.UTF-8
I have a C++ application that I am porting to MacOSX (specifically, 10.6). The app makes heavy use of the C++ standard library and boost. I recently observed some breakage in the app that I'm having difficulty understanding. Basically, the boost filesystem library throws a runtime exception when the program runs. With ...
I have encountered this problem very recently on Ubuntu 14.04 LTS and on a Raspberry Pi running the latest Raspbian Wheezy. It has nothing to do with OS X, rather with a combination of G++ and Boost (at least up to V1.55) and the default locale settings on certain platforms. There are Boost bug tickets sort of related ...
1,745,349
1,745,403
Saving QList<T> to a file?
I've got a QList of QLineEdit*'s QList<QLineEdit*> example; Example will hold 100 items of lineEdits. When I try to save or load to a file, it fails to save or load the QList properly, if at all. I get a much lower than expected count of data. I see on QList<T>'s resource page here that there's the correct operator ...
QList<QLineEdit*> is a list of pointers (basically ints so if you write that to a file you won't get much useful information. The text() method should do what you are looking for. foreach( const QLineEdit* le, example ) { if( le ) { ds << le->text(); } } Note the differences between displayText and text. To...
1,745,487
1,745,667
What can be instantiated?
What types in C++ can be instantiated? I know that the following each directly create a single instance of Foo: Foo bar; Foo *bizz = new Foo(); However, what about with built-in types? Does the following create two instances of int, or is instance the wrong word to use and memory is just being allocated? int bar2; in...
So long as we're talking about C++, the only authoritative source is the ISO standard. That doesn't ever use the word "instantiation" for anything but class and function templates. It does, however, use the word "instance". For example: An instance of each object with automatic storage duration (3.7.2) is associated w...
1,745,693
1,745,758
Get text width in MFC
I'm wanting to dynamically resize a CButton to the width of the text within it. Is there either a built-in way to do this in MFC, or a way of calculating the pixel width of some specified text (so that I can use CWnd::SetWindowPos)?
You can use CDC::GetTextExtent to calculate the width of text in a certain font. Use CWnd::GetDC to get the Device Context from the control displaying the text.
1,745,942
1,745,963
C++ template parameter in array dimension
I have have the following code using templates and array dimension as template non-type parameter template<int n> double f(double c[n]); ... double c[5]; f<5>(c); // compiles f(c); // does not compile should not the compiler to be able to instantiate the second f without explicit template parameter? I am using g++4....
It works when using references: template<size_t n> double f(double (&c)[n]);
1,746,008
1,746,017
Casting UINT64 to float?
Is it safe to cast a UINT64 to a float? I realize that UINT64 does not hold decimals, so my float will be whole numbers. However, my function to return my delta-time returns a UINT64, which isn't a very useful type for the function I'm currently working with. I'm assuming a simple static_cast<float>(uint64value) wil...
Large values of UINT64, (an 8 byte value) may be truncated if you cast them to a float, which is only 4 bytes.
1,746,136
1,750,710
How do I "normalize" a pathname using boost::filesystem?
We are using boost::filesystem in our application. I have a 'full' path that is constructed by concatenating several paths together: #include <boost/filesystem/operations.hpp> #include <iostream>   namespace bf = boost::filesystem; int main() { bf::path root("c:\\some\\deep\\application\\folder"); bf::pat...
Boost v1.48 and above You can use boost::filesystem::canonical: path canonical(const path& p, const path& base = current_path()); path canonical(const path& p, system::error_code& ec); path canonical(const path& p, const path& base, system::error_code& ec); http://www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/r...
1,746,352
1,746,417
How to have templated function overloads accept derived classes from different base classes?
I want to be able to define template <class TX> void f(const TX &x){ ... } template <class TY> void f(const TY &x){ ... } where TX must be derived from BaseX and TY must be derived from BaseY (how do I specify this kind of thing?), and I want to be able to call it as f(DerivedX<T>()) It is most important that I can a...
You can use is_base_of from Boost.TypeTraits like so: #include <boost/type_traits.hpp> #include <boost/utility.hpp> class BaseX { }; class BaseY { }; class DerivedX : public BaseX { }; class DerivedY : public BaseY { }; template <typename TX> boost::enable_if<boost::is_base_of<BaseX, TX>, void>::type f(const TX& x) ...
1,746,402
1,746,505
What's A QT Or Open Source C++ Template For Ordinal Sorting
I am looking for a special template class, hopefully either a QT template or a self-contained open source library. This template class is intended to act as a container for a set of objects. Each object in the set has an integer-valued weight function but the weight function itself is arbitrary. It could range uniforml...
The data structure you're looking for is a heap. The stdlib has std::make_help, push_heap, and pop_heap. There is also std::priority_queue. (I'm not sure why you'd avoid these, unless there's some other requirement you haven't told us about.) A tree such as a map will also work, but it will sort every item. If you ...
1,746,499
1,746,515
Iterator and 2d vector
vector< vector<int> >::iterator temp = mincost.end(); vector<int> a = *temp; if ( *temp != *(temp--) ) return 0; mincost is a 2d vector, I want to get the last vector<int> of this vector and last--. I don't really understand about iterator :) . Help me !! :D Thx ^^
minconst.end() points to the element one-past-the-end of the vector minconst; it doesn't point to the last element in the vector. Since you want the last two elements, you should first test to be sure the vector actually has two elements in it, otherwise inevitably you'll run into problems. Then, accessing the last el...
1,746,594
1,746,662
middle of linked list
how to find the middle of the linked list when we are not informed of its size and it must be performed using only one loop and only one pointer.
How about LinkedList * llist = getLList(); // the linked list Node * node = llist.head; while ( node ) { node = node.next; if ( node ) { node = node.next; llist.remove( llist.head ); } } // now llist.head is (er, um... was) the middle node. // hope you didn't need the rest of the list.
1,747,151
1,747,159
Need help on getArea() function
I'm trying to calculate the area of the circle and the rectangle by using the existing data (radius ,width, and height). But i have some errors, i hope you can help me fix it. #include <iostream> #include <vector> #include <string> using namespace std; class Shape { public: virtual void Draw () = 0; virtual voi...
Rectangle::GetArea method should be const. You declared it non-const, so it is not considered an override of Shape::GetArea, so Rectangle is considered abstract.
1,747,220
1,747,381
Why is this the same even when object pointers differ in multiple inheritance?
When using multiple inheritance C++ has to maintain several vtables which leads to having "several views" of common base classes. Here's a code snippet: #include "stdafx.h" #include <Windows.h> void dumpPointer( void* pointer ) { __int64 thisPointer = reinterpret_cast<__int64>( pointer ); char buffer[100]; ...
When multiple inheritance is used in a virtual function call, the call to the virtual function will often go to a 'thunk' that adjusts the this pointer. In your example, the casted1 pointer's vtbl entry doesn't need a thunk becuase the IDerived1 sub-object of the CClass happens to coincide with the start of the CClas...
1,747,254
1,747,273
C-style Variable initialization in PHP
Is there such a thing as local, private, static and public variables in PHP? If so, can you give samples of each and how their scope is demonstrated inside and outside the class and inside functions?
I don't know about C++ but there's how PHP works about: For Function scopes: <?php $b = 6; function testFunc($a){ echo $a.'-'.$b; } function testFunc2($a){ global $b; echo $a.'-'.$b; } testFunc(3); testFunc2(3); ?> The output is 3- 3-6 Code inside functions can only be accessed varia...
1,747,494
1,747,561
Conjugate function for complex number
I am trying to create a function that conjugate a complex number for example A(2, 3) will turn into A(2,-3) by typing ~A i have done a little code below but i guess it's wrong, i hope you can help me slove this. i have quoted the part that i did wrong in the code below. #include <iostream> using namespace std; ...
try Complex Complex::operator~() const { Complex conj; conj.imaginenary = -1 * imaginenary; conj.real = real; return conj; } But it might be wiser to remove the operators from the class definition and create (friend) functions instead. It works better with implicit type conversion.
1,747,660
1,747,775
strange std::vector problem with uint32_t on Visual Studio 2008
This works fine: std::vector<int> v; v.push_back(123); but this throws a std::length_error: std::vector<uint32_t> v;// or vector<unsigned __int32> v.push_back(123); It seems to be triggered by resizing, because std::vector<uint32_t> v; v.reserve(2); triggers a debug assertion "iterator not dereferencab...
This #include <iostream> #include <vector> int main() { std::vector<unsigned __int32> v; v.reserve(2); std::cout << v.capacity() << '\n'; return 0; } runs without any hiccups for me in VS 2008. It prints 2. What does this do for you? If it works, too, then my first few guesses are: You invoked und...
1,747,691
1,747,788
Handling a resource effectively using auto pointers
I have a code which looks like this: class Parent { auto_ptr<Resource> ptr2Resc; public: void parentMethod(int i ) { SomeOtherClass someOthrPtr = new SomeOtherClass(ptr2Resc); } }; The ctor of SomeOtherClass: SomeOtherClass(auto_ptr<Resource> ptrRes); So now when i call parentMethod, the auto_ptr gets swapped and...
Following is the quote from Josuttis book regarding passing auto_ptr by reference: You might think about passing auto_ptrs by reference instead. However, passing auto_ptrs by reference confuses the concept of ownership. A function that gets an auto_ptr by reference might or might not transfer ownership. Al...
1,747,744
1,750,443
How do I split a large MFC project into smaller projects
We have a large MFC/C++ Visual Studio 2005 solution which currently consists of two projects: Code (around 1500 .h/.cpp files, linked dynamically to MFC) Resource DLL (we translate the resources using an external tool) What options do we have (lib, dll, ...)? Where do we start? Is there a technical sample of this ...
Clearly there is no universal answer to you question. First you need to create some simple program using DLL's or statically linked libs (simply as an exercise). Before you know how to create such application from scratch it is not advisable to attempt fragmenting real-life project. There are couple of MS tutorials her...
1,747,976
1,748,053
C++ array delete operator syntax
After I do, say Foo* array = new Foo[N]; I've always deleted it this way delete[] array; However, sometimes I've seen it this way: delete[N] array; As it seems to compile and work (at least in msvc2005), I wonder: What is the right way to do it? Why does it compile the other way, then?
You can check this MSDN link: delete[N] operator. The value is ignored. EDIT I tried this sample code on VC9: int test() { std::cout<<"Test!!\n"; return 10; } int main() { int* p = new int[10]; delete[test()] p; return 0; }; Output is: Test!! So the expression is evaluated but the return value is...
1,748,473
1,748,519
Character decoding Conversion Function Implementation
I need to implement a character encoding conversion function in C++ or C( Most desired ) from a custom encoding scheme( to support multiple languages in single encoding ) to UTF-8. Our encoding is pretty random , it looks like this Because of the randomness of this mapping, I am thinking to use std::map for mapping ou...
If your code points are contiguous, just make a big char * array and translate using that. I don't really understand what you mean by UTF-8 codepoint. UTF-8 has representations, and Unicode has codepoints. If you want code points, use an array of ints. const int mycode_to_unicode [] = { 0x00ff, 0x0102, // etc....
1,748,624
1,748,645
Circular dependencies of declarations
I am trying to implement example of visitor pattern, but I have trouble with circular dependecies of declarations of classes. When I do forward declaration of class Visitor, classes Russia and England doesn't know that Visitor has method visit, but when I extend forward declaration of Visitor for method accept, I need ...
class Visitor; class England : public Land { public: void accept(const Visitor *v); // Only declaration }; // Define Visitor class Visitor { //... }; // Now implementation void England::accept(const Visitor *v) { v->visit(this); }
1,748,827
1,748,864
Virtual tables are undefined
I wrote some code but I am unable to compile it: #include <cstdio> #include <vector> using namespace std; class Visitor; class Land { public: virtual void accept(const Visitor *v); }; class England : public Land { public: void accept(const Visitor *v); }; class Russia : public Land { public: voi...
I already answered it there. The rules for vtable instantiation are explained in your compiler documentation. Here, it is waiting to see the definition (body) of Land::accept, which you declared to be a non-pure virtual, but never defined. Either define it, or make it pure virtual.
1,748,856
1,748,886
Inconsistent results from printf with long long int?
struct DummyStruct{ unsigned long long std; int type; }; DummyStruct d; d.std = 100; d.type = 10; /// buggy printf, unsigned long long to int conversion is buggy. printf("%d,%d\n",d.std, d.type); // OUTPUT: 0,100 printf("%d,%d\n", d.type, d.std); // OUTPUT: 10,100 printf("%lld,%d\n",d.std, d.type);...
Its your usage that is the problem. Unless the types specified in the format string are exactly the same as the types in the parameters then things will not work correctly. This is because the compiler pushes the parameters as-is onto the stack. There is not type checking or conversion. At run-time the code is pulling ...
1,748,902
1,749,086
Linux inter-process reentrant semaphore
I'm porting a Windows application to Linux and I have a synchronization problem. In Windows I'm using a system-level named mutex to sync access to a shared memory block. How do I emulate that in Linux? I've created a SystemV semaphore, using semget. The problem is that it is not reentrant, if I already hold it it will ...
You can just use a shared (interprocess), recursive pthread_mutex_t. Create a normal pthread_mutex (stored in shared memory) and set its attributes using pthread_mutexattr_settype with the PTHREAD_MUTEX_RECURSIVE flag, and then call pthread_mutexattr_setpshared with the PTHREAD_MUTEX_SHARED flag. That will give you a ...
1,749,229
1,749,284
Direct-X in C++ Game Programming
I am reletively new to c++ programming can anyone please tell me how does Direct-X SDK is helpful and how does it works and how can we use it in game programming.I Downloaded it and I found lots of header files and documentation also tells something about game programming.
DirectX is a library (a large collection of classes, really) that allows you to "talk" to the video adapter, sound card, keyboard, mouse, joystick, etc. It allows you to do it much more efficiently then other "standard" Windows functions. This is important because games need all the performance gain you can get - and D...
1,749,311
1,749,351
friend function within a namespace
When a friend function is included in the namespace, its definition needs to be prefixed with namespace to compile it, here is the sample code: test.h: #ifndef TEST_H #define TEST_H namespace TestNamespace { class TestClass { public: void setValue(int &aI); int value(); private: ...
The TestClass is being used in the testFunc method. Since you have included the namespace "using namespace TestNamespace;" it works fine. For testFunc method you are defining the implementation, you need to tell compiler that testfunc belongs to namespace TestNamespace: you can do it either: in .cpp namespace TestNames...
1,749,519
1,749,605
C++ 64-bit std::ostream support
I am about to make the transition from using standard FILE pointers from some older code to using C++ streams but I need to have LARGEFILE seeking support (the compiler flags that activate this support are: -D_FILE_OFFSET_BITS=64 et al) which I am able to obtain by using the off64_t datatype. My original question was ...
So I performed a quick test on a 16GB file and it seems to have worked. Here is the code that I used. // compiled with : g++ -o largefile -D_FILE_OFFSET_BITS=64 largefile.cpp #include "iostream" #include "fstream" int main (int argc, char * argv[]) { char line[4096]; std::ifstream stream ("/home/jbell...
1,749,531
1,749,556
help on typedefs - basic c/c++
i have been going through some code and came across a statement that somehow disturbed me. typedef GLfloat vec2_t[2]; typedef GLfloat vec3_t[3]; From my perspective, a statement such as typedef unsigned long ulong; Means that ulong is taken to mean unsigned long Now, can the statement below mean that vec2_t[2...
Basically a typedef has exactly the same format as a normal C declaration, but it introduces another name for the type instead of a variable of that type. In your example, without the typedef, vec2_t would be an array of two GLfloats. With the typedef it means the vec2_t is a new name for the type "array of two GLfloat...
1,749,534
1,749,604
Multiple dispatch in C++
I am trying to understand what multiple dispatch is. I read a lot of various texts but I still have no idea what multiple dispatch is and what it is good for. Maybe the thing I am missing is piece of code using multiple dispatch. Please, can you write a little piece of code in C++ using multiple dispatch so that I can ...
Multi-dispatch is the ability to choose which version of a function to call based on the runtime type of the arguments passed to the function call. Here's an example that won't work right in C++ (untested): class A { }; class B : public A { }; class C : public A { } class Foo { virtual void MyFn(A* arg1, A* arg2) {...
1,749,597
1,749,661
how do aim bots in fps games work?
I was curious if anyone had any experience/knowledge about aim bots in online FPS games such as Counter-Strike. I am curious and would like to learn more about how the cursor knows how to lock on to an opposing player. Obviously if I wanted to cheat I could go download some cheats so this is more of a learning thing. W...
Somewhere in the game memory is the X,Y, and Z location of each player. The game needs to know this information so it knows where to render the player's model and so forth (although you can limit how much the game client can know by only sending it player information for players in view). An aimbot can scan known me...
1,749,650
1,749,969
Game programming for windows in C++ or C#
I just learned the basics of c++ and c#,just the simple basics of the language.And I want to pursue game programming can anyone please tell me where to start off I read somewhere that Direct-X is used for game programming and I downloaded it from Microsoft's website but I just didn't understood it.From where did you pe...
From reading your comments to the original question, it would seem that you have fallen into the trap of setting your sights far too high. The game 'World of Goo' did not happen overnight. It took a long time using lots of third party libraries to do the video/audio/physics/gameplay elements and a very good working kno...
1,749,740
1,749,770
Are thread and process ids unique?
I am using a static library; it has a function which uses the current time and creates a unique id, which is then inserted into my database. This number should be unique in my database table. There are two processes running in parallel. Sometimes they simultaneously call this function, and the same number is generated...
Use the database to generate them. How to do that depends on the database, but Postgres calls them sequences for an example.
1,749,767
1,750,005
Track handle creation / deletion
I have a large old program which has some rather complex graphical displays (all via standard API calls). The program appears to be working fine, but I recently looked at the "handles" field of Windows Task Manager when this program was running and noticed that the number of handles was gradually and relentlessly creep...
Please try this link for advice. Problem is complex and somebody has written tutorial on how to tackle it. Update: here is one more link that can help.
1,749,951
1,750,199
C++ IntelliSense 'auto' feature? Where is it? How to get it 'on'?
I would like to enable the IntelliSense 'auto' feature (like the Visual Studio C# 2008 Express) but I am using Visual Studio C++ 2008 Express Edition and in the Tools > Options > Text Editor > C/C++ (there is no option 'IntelliSense' (like Visual C#). How do I get this feature enabled? I know I can get a shortcut in pl...
In C++, IntelliSense is turned on by default (and AFAIK there isn't even an official way to turn it off). However, when you're coming from C#, you might think it's turned off, because it's so much less powerful in C++. (The reason for this is that C++ is much, much harder to parse. You can find more information on the ...
1,750,275
1,761,635
how to display IBitmapImage on CDC
What is the best way to display IBitmapImage on a device context. I am using Windows CE 6.0. void CImaginingTestView::OnDraw(CDC* pDC) { CImaginingTestDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); IBitmapImage* pBitmapImage = pDoc->GetBitmapImage(); if (pBitmapImage) { // how to draw my bit...
Assuming you're talking about the Imaging API, take a look at the IImage interface an in particular its Draw Method.
1,750,442
1,750,454
Performance of 32-bit integers in a 64-bit environment (C++)
We've started compiling both 32- and 64-bit versions of some of our applications. One of the guys on my project is encouraging us to switch all of our 32-bit integers to their 64-bit equivalents, even if the values are guaranteed to fit in a 32-bit space. For example, I've got a value that is guaranteed to never exce...
I think you have a huge case of pre-mature optimization staring you in the face. Never make micro changes like this in your application until a profiler has definitively told you that it is a source of significant performance problems. Otherwise you'll spend a lot of time fixing non-problems.
1,750,514
1,750,661
Including commented Class declaration in implementation file
Everyone knows the advantages of a more readable code. So in order to make my code more readable what i do normally is include the commented class declaration in the implementation file of that class. This way i need not have to browse through various include directories to go to the definition. So, Is this a good pra...
This is actually counter-productive, because now you have to change three locations instead of two when modifying class declaration, and one of these locations won't be checked by compiler to catch any mismatches. Also, in large and quickly-evolving projects comments always get obsolete, so they cannot be trusted. All ...
1,750,517
1,750,549
Import C++ classes in python?
so.. let's say i have this C function: PyObject* Foo(PyObject* pSelf, PyObject* pArgs) { MessageBox(NULL, "Foo was called!", "Info", MB_OK); return PyInt_FromLong(0); } and then, I have to do this: static PyMethodDef Methods[] = { {"Foo", Foo, METH_NOARGS, "Dummy function"}, {NULL, NULL, 0, NULL} }; P...
boost.python enables you to do that very effectively.
1,750,937
1,750,958
I need high performance. Will there be a difference if I use C or C++?
I need to write a program (a project for university) that solves (approx) an NP-hard problem. It is a variation of Linear ordering problems. In general, I will have very large inputs (as Graphs) and will try to find the best solution (based on a function that will 'rate' each solution) Will there be a difference if I w...
No. The biggest performance gains/flaws will be on the algorithm you implement, and how much unneeded work you perform (Unneeded work could be everything from recalculating a previous value that could have been cached, to using too many malloc/free's vs using memory pools, passing large immutable data by value instead...
1,751,330
1,752,457
ITaskbarList3 undeclared?
I'm trying to write some c++ code to use the ITaskbarList3, but I'm getting that error. I have confirmed that I am including shobjidl.h (but I checked and this file only defines up to ITaskbarList2). I have Visual Studios 2008 (SP1) and I have Microsoft Windows SDK for Windows Server 2008 installed. Does anyone know wh...
You need to install the Windows 7 SDK. That has an update shobjidl.h with ITaskbarList3.
1,751,346
1,751,368
interpret signed as unsigned
I have a value like this: int64_t s_val = SOME_SIGNED_VALUE; How can I get a uint64_t u_val that has exactly the same bit pattern as s_val, but is treated as unsigned? This may be really simple, but after looking on Stackoverflow and elsewhere I haven't turned up the answer.
int64_t s_val = SOME_SIGNED_VALUE; uint64_t u_val = static_cast<uint64_t>(s_val); C++ Standard 4.7/2 states that: If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [Note...
1,751,352
1,920,101
automake dependency tracking for nonstandard C++ suffix
how can i force automake to generate dependency tracking for nonstandard C++ suffix files? in particular I mean generating .deps directory file content. I am using libtool as well. Thanks
Take a look at this section in the automake manual regarading default _SOURCES. It looks like saying: bin_PROGRAMS = target AM_DEFAULT_SOURCE_EXT = .foo will get you past the first step. So, now automake knows where to look for the first dependency (target.foo), and it will ask GCC to compute the dependencies of tar...
1,751,441
1,752,594
How to subtract one audio wave from another?
How to subtract one audio wave from another? In general and in C# (or if we cannot do it in C# in C/C++) I have sound wave A and sound wave B (BTW: they are in PCM) I want to subtract B from A What do I need? Open Source Libs (NOT GPL, but LGPL will be ok) Tutorials on how to do such operation (with or without using...
If the samples are normalised to the same level, and are stored in a signed format such that the "zero level" is 0 or 0.0, the answer is fairly simple: S_C = (S_A / 2) - (S_B / 2); for each sample S_A and S_B in A and B. If you are using unsigned values for the samples then you will need to do more work: first, you ne...
1,751,671
1,751,702
boost::format - attempting to use HTML as formatter string - need some help
I'm attempting to use boost::format, where my formatting string is the HTML below. I intend to insert 3x std::strings at locations specified by %s placeholders. In other words - I'm opening the below *.html file for reading, read it's contents into a single std::string and use it as the formatter. Next I'm attempting t...
boost::format uses % to delimit format specifications; so the % characters in your CSS are confusing it; it is trying to evaluate them as format specifications. You'll need to replace those with %% to get just a literal % character in the output. If that doesn't help, then I would recommend trying to edit your template...