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
4,570,069
4,570,111
How to make child control handle accelerator command of parent CView
I have a CFormView, and a child CListCtrl control. I can handle accelerator events, like Ctrl+C, Ctrl+V ... in CFormView without problem, by defining below message handler: ON_COMMAND(ID_EDIT_COPY, &CMyFormView::OnEditCopy) Now I want my CListCtrl handle these commands differently. I want to implement OnEditC...
Use same ON_COMMAND macro in CMyListCtrl. ON_COMMAND(ID_EDIT_COPY, &CMyListCtrl::OnEditCopy) All you have to do is overriding OnCmdMsg method. BOOL CMyFormView::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo) { if (GetFocus() == m_myListCtrl && m_myListCtrl->OnCmdMsg(nID, ...
4,570,135
4,570,161
"delete from table" doesn't delete table?
I create "database.db" and everything goes ok but why wouldn't it delete the table at the end? Everytime i run it, i get "table already exist" error message on creating the table. int main() { sqlite3 *db; //Database Handle char *zErr; int rc; char *sql; rc = sqlite3_open("database.db", &db); if(rc) { cout <...
You need to use drop table. delete deletes rows in the table. rc = sqlite3_exec(db, "drop table test", NULL, NULL, &zErr); SQLite will auto-increment an integer field declared as the primary key. See here.
4,570,147
4,570,369
Safe String Functions In Mac OS X and Linux
are there are equivalent secure string functions in Mac OSX and Linux just like the ones in Windows (strcpy_s,strncpy_s..etc) ? What about functions that convert between multi-byte and wide characters?
There are two strategies for safe string manipulation. The Linux / glibc maintainers refuse to add safe functions, arguing that you should keep the length of your strings at hand and use memcpy. On the other hand, Mac OSX includes strlcpy and strlcat from BSD. snprintf and asprintf can be used on both platforms to muc...
4,570,194
4,570,730
Log with timestamps that have millisecond accuracy & resolution in Windows C++
I'm aware that for timing accuracy, functions like timeGetTime, timeBeginPeriod, QueryPerformanceCounter etc are great, giving both good resolution & accuracy, but only based on time-since-boot, with no direct link to clock time. However, I don't want to time events as such. I want to be able to produce an exact timest...
First, some functions: // ========================================================================== #define NOMINMAX #define _AFXDLL #include "afxwin.h" // TRACE #include "windows.h" // ULARGE_INTEGER #include "mmSystem.h" // timeGetTime #pragma comment(lib, "Winmm.lib") // timeG...
4,570,366
4,570,374
How to access a local variable from a different function using pointers?
May I have any access to a local variable in a different function? If so, how? void replaceNumberAndPrint(int array[3]) { printf("%i\n", array[1]); printf("%i\n", array[1]); } int * getArray() { int myArray[3] = {4, 65, 23}; return myArray; } int main() { replaceNumberAndPrint(getArray()); } The ...
myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior. In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it th...
4,570,389
4,570,418
Chess piece hierarchy design: inheritance vs type fields
I have a base class for pieces class piece; and an array containing derived objects piece* board[8][8]; Advantage, clean design through virtual functions. Disadvantage, if I have to find a piece in the board or compare a piece I have to revert to dynamic casting (or typeid). It’s ugly and could be a performance hog ...
I would go with the class hierarchy. For finding a piece you can keep a separeted list for each piece type. So you know where to look for each piece type. For comparison you can rely on virtual methods too. Another aproach is to use a component architecture (like described here: http://cowboyprogramming.com/2007/01/05/...
4,570,832
4,570,889
Comparing shared_ptr to managed language references
Could someone explain to a C++ programmer most important differences between Java (and C# as well) references and shared_ptr (from Boost or from C++0x). I more or less aware how shared_ptr is implemented. I am curious about differences in the following ares: 1) Performance. 2) Cycling. shared_ptr can be cycled (A and B...
Performance: shared_ptr performs pretty well, but in my experience is slightly less efficient than explicit memory management, mostly because it is reference counted and the reference count has to allocated as well. How well it performs depends on a lot of factors and how well it compares to Java/C# garbage collectors ...
4,570,875
4,570,911
A Couple Questions About Creating Windows
In trying to get a grasp on creating windows (in Windows OS), I encountered this function definition LRESULT CALLBACK Window::MsgRouter(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) (taken from here) Me being only a beginner in C++ I interpreted that to mean that it's return type was both LRESULT and CALLBACK...
No, it's not a type, it's a modifier. Both CALLBACK and WINAPI resolve to __stdcall, which is standard calling convention for WinAPI functions. WPARAM and LPARAM are message parameters' types, all types used in the API are documented on MSDN.
4,570,914
4,570,953
Forward declaring enum in C header included in C++
I have C headers which forward declare enums. Apparently, this is not possible in C++, so all of the pre-processor wraps of the form extern "C" { #include <header.h> } are not going to help. Is there any way to include these headers in a C++ translation unit without requiring me to edit the C headers? Fortunatel...
Forward declared enums are available in C++0x. If your compiler doens't support it yet, then wrapping enums in namespaces will avoid violation of ODR. P.S. a good explanation: http://www.devx.com/cplus/Article/42478/1954?pf=true
4,570,946
4,571,436
unique synthesised name
I would like to generate various data types in C++ with unique deterministic names. For example: struct struct_int_double { int mem0; double mem1; }; At present my compiler synthesises names using a counter, which means the names don't agree when compiling the same data type in distinct translation units. Here's what...
Do you actually need the names to agree? Just define the structs separately, with different names, in the different translation units and reinterpret_cast<> where necessary to keep the C++ compiler happy. Of course that would be horrific in hand-written code, but this is code generated by your compiler, so you can (an...
4,571,155
4,571,446
Initialization of array on heap
How do i manually initiate values in array on heap? If the array is local variable (in stack), it can be done very elegant and easy way, like this: int myArray[3] = {1,2,3}; Unfortunately, following code int * myArray = new int[3]; myArray = {1,2,3}; outputs an error by compiling error: expected primary-expression be...
This is interesting: Pushing an array into a vector However, if that doesn't do it for you try the following: #include <algorithm> ... const int length = 32; int stack_array[length] = { 0 ,32, 54, ... } int* array = new int[length]; std::copy(stack_array, stack_array + length, &array[0]);
4,571,163
4,571,234
FMOD Compiling trouble
I'm trying to get started with FMOD but I'm having some issues compiling the example code in this tutorial: http://www.gamedev.net/reference/articles/article2098.asp I'm using MinGW, I placed the libfmodex.a file in MinGW's include folder (I also tried linking directly to the filename) but it doesn't work. Here's the o...
That is an old tutorial, the FMOD API has changed since then. For example, instead of FSOUND_SAMPLE, it is now FMOD::Sound (I think). Have a look inside your fmod.h and you can see what classes and functions you should be using.
4,571,225
4,571,266
Wait for tasks to get completed in threadpool
I have created a thread pool in C++ which stores all tasks in a queue. Thread pool start n number of threads which takes tasks from queue , process each task and then delete tasks from queue. Now , I want to wait till all tasks get completed. Checking for empty queue for completion of tasks may not work as , task can b...
Do you need to wait for all threads to finish, or do you just need to check? If you just need to check, you can have a variable that stores the number of currently executing tasks, and InterlockedIncrement it at the beginning of a thread, then InterlockedDecrement it at the end. If you need to wait, and you have a smal...
4,571,355
4,571,683
Why would one use nested classes in C++?
Can someone please point me towards some nice resources for understanding and using nested classes? I have some material like Programming Principles and things like this IBM Knowledge Center - Nested Classes But I'm still having trouble understanding their purpose. Could someone please help me?
Nested classes are cool for hiding implementation details. List: class List { public: List(): head(nullptr), tail(nullptr) {} private: class Node { public: int data; Node* next; Node* prev; }; private: ...
4,571,486
4,580,692
How to use SOCI C++ Database library?
I'm trying to implement soci in my program but I don't know how. I'm using C++ on Linux, on a project using netbeans. I have followed the steps in: http://soci.sourceforge.net/doc/structure.html to install it, and I tried to copy the files soci.h from /src/core and soci-mysql.h from /src/backends/mysql in my project b...
The relevant bit on that page is When the configure script is run without parameters, the remaining part of the process will use /usr/local/include/soci as a default destination for SOCI header files and /usr/local/lib as a default destination for library files Now /usr/local/include ought to be in your default inclu...
4,571,607
4,571,739
C++ VS Express 2010 Intellisense
I'm trying to use Visual Studio Express 2010 to write an openGL program, so It's a win32 console application. And I can't get Intellisense to show up for anything, openGL or otherwise. What am I doing wrong, and how can I force Intellisense to show? (Like you can force the Xcode equivalent with Esc)
From MSDN: IntelliSense can stop working under certain conditions. Use the following steps to help determine why IntelliSense does not work for C++ projects. To investigate IntelliSense failure in C++ projects Make sure that the Visual C++ project contains no compilation errors. 1) If the project is a Makefile project,...
4,571,663
4,571,675
How to find files of the form $INPUTDIR/*/*/*/results.txt in C++ ( Linux )
I am trying to make a vector of filenames of the form $INPUTDIR/*/*/*/results.txt or in other words find all files of the name results.txt at a depth of 3 from the given INPUT_DIRECTORY. Any pointers ?
Try looking at the man page for the glob() function - this does exactly what you need.
4,571,666
4,571,795
nothrow or exception?
I am a student and I have small knowledge on C++, which I try to expand. This is more of a philosophical question.. I am not trying to implement something. Since #include <new> //... T * t = new (std::nothrow) T(); if(t) { //... } //... Will hide the Exception, and since dealing with Exceptions is heavier compare...
Since dealing with Exceptions is heavier compared to a simple if(t), why isn't the normal new T() not considered less good practice, considering we will have to use try-catch() to check if a simple allocation succeeded (and if we don't, just watch the program die)?? What are the benefits (if any) of th...
4,571,807
4,571,848
Is there a standard set of libraries for dynamic strings, lists, and dictionaries in C?
I'm interested in getting into C to get close to the metal performance, but would like to write in a Pythonic style and don't want to roll my own dynamic strings, lists, and dictionaries. Cython is pretty good, but would like to know how to use dynamic variables in straight C if possible. With C++ there is of course t...
Use C++; it has standard and highly-optimized versions of all of these. There's absolutely no reason or benefit to limit yourself to C. (ed: In other words, yes, that's a very standard practice. Remember, there's no requirement to use any of C++'s features when using C++; by design, you can pick and choose. I often ...
4,571,923
4,572,128
Interactions/Communications between a C++ and a Java program
I've got an app written in Java and some native C++ code with system hooks. These two have to communicate with each other. I mean the C++ subprogram must send some data to the Java one. I would've written the whole thing in one language if it was possible for me. What I'm doing now is really silly, but works. I'm hidin...
If you don't find JNI 'easy' then you are in need of an IPC (Inter process communication) mechanism. So from your C++ process you could communicate with your Java one. What you are doing with your console redirection is a form of IPC, in essence that what IPC. Since the nature of what you are sending isn't exactly clea...
4,572,116
4,572,131
Using Visual C++ for C++ instead of C++/CLI
I know how to program in C++ making console programs, but now I want to code programs with interfaces for Windows. MS VS 2010 makes things easy when coding C++ Windows applications with its drag & drop design system. (.net Framework) However, Visual Studio seems to use C++/CLI, which I'm unfamiliar with. Is there for a...
Visual C++ is perfectly happy to not use C++/CLI syntax, in fact it works even better without it. Just set "Use of .NET Framework (/clr)" setting in your project options to "No". Or use the "Win32 Application" wizard when creating your project to begin with. The "native" version of the Forms Designer is called the Dia...
4,572,335
4,572,690
QT Designer: Using .ui files for other components created with QT Designer
I have created a bunch of widgets with QT designer. What I would like to know is if these widgets can be used (drag and dropped) with other components I create with QT Designer, without having to export them and compile them as a custom widget, since it seems that the .ui file already contains most of that functionali...
Nope. Doesn't work that way. You need to do all the custom widget crap. I don't usually bother though. I just put what I've supclassed from in the designer and then use the "promotion" feature.
4,572,361
4,572,371
creating a class within another class memory allocation
If I have a few classes, say one is a base class and it is created inside another class, will it be located on the stack or heap if the "outside" class is created with the new operator but the class created inside of it isn't. For example: class baseclass { //code here }; class outside { baseclass mybase; ...
Yes. That's correct. It does not require an additional new or delete for it though.
4,572,409
4,572,424
Is this a valid C statement?
Let's say I write char c[99] = {'Stack Overflow'}; in C or C++. It compiles fine but is this valid? By valid I meant not invoking any kind of undefined or unspecified behavior. Again if I write char c[99] = 'Stack Overflow'; gcc complains about multicharacter constant which is obvious but in the above when I am enclosi...
They both are only a single literal, so c[0] gets set to the literal and c[1] ... c[98] get filled with zero (NUL character). I think what value actually gets stuffed into c[0] is implementation dependent, but it should at least compile on any compliant compiler. EDIT: Verified against the standard, in C++0x at least: ...
4,572,419
4,572,450
Is there a C++ function that helps to evaluate parentheses?
For example, if the input is "(A + (BC)) (giggity (this text) isn't in the expression)", it would return (0, 9), because the first parenthesis is on 0 and the second is on 9? If not, please tell me how to construct a function that takes a string as its arguments so I can do it myself.
There is no function built into the standard library that does that, but it's really easy to write: pair<int,int> findparens( const char* input ) { int depth = 0; int first; for( const char* c = input; *c; ++c ) { if (*c == '(' && !depth++) first = c - input; else if (*c == ')' && !--depth) ...
4,572,438
4,611,533
Strange build errors in MFC application
I am writing a port scanning application in MFC C++ using Visual Studio 2010. When I try to compile, I get >100 errors, all connected with the files atlcore.h and afxcomctl32.h. All of them are error #C3861, "Identifier Not Found." I have not edited these files in any way. Anybody know why this would be doing that? Tha...
OK I figured it out! the reason it was not compiling and throwing all those error is because I'm using VS 2010 on a Windows XP, and the MFC support is for OSs Windows Vista and up. I tried compiling my code in Visual Studio 2008 and it worked, so I guess I just will have to use VS 2008 for MFC C++.
4,572,527
4,572,596
How to hide keys in application?
I have a C++ client/server application where the client and server are my executable. Each time a connection is made between the client and server, I generate a new encryption key for that session and I wish to transmit this session key and encrypt this session key using a static key that is built into both the client...
His method of exchanging keys "ensures" the client is valid and not an impostor. Just securely exchanging keys using D-H won't do that. In order to get the same functionality he'll need to implement a PKI system. SSL/TLS was built for this purpose which underneath it will do what he needs. You'll need to create a CA f...
4,572,787
4,572,821
SFML add to sf::String?
So I've been using SFML lately and I was wondering how I could "add" to sf::String. For example: sf::String exampleText; exampleText.SetText("I say: "); exampleText += "Blah"; Result: "I say: Blah"
sf::string doesn't offer an append method which makes sense as it's intended to be a class for the graphical display of text rather than a traditional string class. So you have to perform your string manipulation/append operations behind the scenes using your usual char array/string/stringstream classes and then call ...
4,572,814
4,572,933
How to update a user created Bitmap in the Windows API
In my code I quickly generate images on the fly, and I want to display them as quickly as possible. So the first time I create my image, I create a new BITMAP, but instead of deleting the old one and creating a new one for every subsequent image, I just want to copy my data back into the existing one. Here is my code t...
to write to a bitmap you have to Select it into a DeviceContext: hdcMemDC = CreateCompatibleDC(hdc); ... // adjust hdcMem to right sizes (see MSDN : Capturing an Image) SelectObject(hdcMemDC,bitmap); ... // your Bitmap drawing BitBlt( hdcMemDC, ... ) // to copy to hdc. ReleaseDC(hWnd, hdcMemDC); Also CreateDIBitmap(...
4,572,866
4,572,875
Algorithm for finding a rectangle constrained to its parent
Basically what I want to do is illustrated here: I start with A and B, then B is conformed to A to create C. The idea is, given TLBR rectangles A, B, make C I also need to know if it produces an empty rectangle (B outside of A case). I tried this but it just isn't doing what I want: if(clipRect.getLeft() > rect.getLe...
You seem to have a mistake in the final condition checking whether or not the intersection rectangle is empty. You check L < R && B < T, but it seems like the condition for an empty rectangle should be: L > R || B < T. By the way, you can make your code a little simpler and easier to read by using Min and Max functions...
4,573,025
4,573,060
which standard do i need to follow?
If I use vs2005 would I need to follow an old cpp standard edition? can I possibly run vs2010 with 512 RAM or would it be a very slower?
512 MB of RAM should run any of the Microsoft compilers just fine except on the largest projects. The integrated development environment (the editor which runs when you launch "Visual Studio") is another matter entirely, 512 MB of RAM will only be enough for the most trivial projects. Any system with the CPU power app...
4,573,090
4,573,104
Can we have an anonymous struct as template argument?
The title is pretty self-explanatory, but here's a simplified example: #include <cstdio> template <typename T> struct MyTemplate { T member; void printMemberSize() { printf("%i\n", sizeof(T)); } }; int main() { MyTemplate<struct { int a; int b; }> t; // <-- compiler doesn't like this ...
You are not allowed to define an unnamed type as a template argument in C++03 or even in C++0x. The best you can do it to create a named struct local to main (in C++0x1) 1 : You are not allowed to use a local type as template argument in C++03, however C++0x allows it. Also check out the Defect Report here. The propos...
4,573,091
4,573,098
Overloading Square Brackets Operator to Accept Value
I'm writing a collection class. I want to overload the square brackets operator ([]) to provide access to elements in the collection. int operator[](int i) { // Do stuff here } My problem is that I don't see how to write this so that I could use this operator to accept a value: myClassInstance[0] = value; I see n...
Write an int_proxy class that is implicitly convertible to int and is assignable from int. You'll need at least two member functions: operator int(); int_proxy& operator=(int); In this proxy class, store whatever information you need to be able to retrieve and set the value in the container. Do the retrieval in the ...
4,573,150
4,575,444
Audio bug crashing my C++ program
I'm writing a very simple game with C++ and SDL/SDL_mixer. The game uses some simple audio functions that play sound effects when something happens, and my program has been working fine until now. At a seemingly random time, the program will start making screeching and static noises (but will still be able to play soun...
It sounds like the memory area where you store the sound data is overwritten/corrupted (leading to "noise" output). That your program crashes with an access violation also points to memory corruption. Make sure that the buffer with the audio data is properly allocated and isn't freed/deleted/... while it is still in us...
4,573,222
4,573,345
Checking to see if a pointer can be freed
I've looked all over for an answer to this but can't seem to find one. (I have fairly limited experience with C++) In my library, I free a string. (Amazing, huh?) This is where the problem arises. I have a struct which contains a char* that may be allocated on the heap or may not be. While it is a valid pointer it cann...
Seeing as this is a Windows library, make the argument a BSTR. Then you require the user to allocate it properly (with SysAllocString) and you're guaranteed to use a matching deallocator. Other methods are just... bad. If your user has a different compiler, then you can't free() the string even if they did use malloc...
4,573,238
4,573,278
C++ variable to const expression
template <typename Real> class A{ }; template <typename Real> class B{ }; //... a few dozen more similar template classes class Computer{ public slots: void setFrom(int from){ from_ = from; } void setTo(int to){ to_ = to; } private: template <int F, int T> void compute(){ using boost::fusion::vector; using ...
If you don't want to use switch or if/else block statements then there is no way you can accomplish this task. Because at_c<> function template takes integral parameter which needs to be known at compile time. And your variables to_ and from_ are not known at compile time. And my answer in the following topic is someho...
4,573,279
4,573,299
Creating a Skill Calculator for Runescape
I am beginning C++. I have a long way to go and I am one to never stop learning. I want to create a project for myself that will allow me to learn as I go. It will also give me the motivation and possibly add to my portfolio when I graduate. The runescape skill calculator will ask for your current experience in the cur...
Unfortunately, a general question can only get a general answer: First, build the program to run interactively from the command line with correct behaviour. Then, (if you haven't designed it this way) extract the code into a class. This will allow you to call it from future programs. Then, write an GUI that interface...
4,573,411
4,682,316
parallel_for function causes memory leaks (sometimes)
I'm making a simple native MFC application and I'm using th Concurrency namespace to perform a simple parallel program (drawing a Mandelbrot set). The program is very very basic so far, clicking one button draws in parallel, the other draws in serial. The serial execution function is very basic and draws the right pict...
This problem is documented in the fix-list for VS2010 SP1. The feedback article is here. Beware that SP1 is still in beta right now so avoid installing it on important production machines. Download is here.
4,573,496
4,573,509
"end()" iterator for back inserters?
For iterators such as those returned from std::back_inserter(), is there something that can be used as an "end" iterator? This seems a little nonsensical at first, but I have an API which is: template<typename InputIterator, typename OutputIterator> void foo( InputIterator input_begin, InputIterator input_end, ...
If foo is checking to ensure that distance(output_begin, output_end) is sufficiently large to contain the results, what could you use as an "end" iterator? A back_inserter adds elements to the end; the distance between the place at which a back_inserter adds elements and the end of the sequence is, by definition, 0. A...
4,573,536
4,574,319
MSVC - /EHsc vs /EHa (synchronous vs asynchronous exception handling)
Could you give a bullet list of practical differences/implication? I read relevant MSDN article, but my understanding asynchronous exceptions is still a bit hazy. I am writing a test suite using Boost.Test and my compiler emits a warning that EHa should be enabled: warning C4535: calling _set_se_translator() requires /...
When you use /EHsc, the compiler will only emit code for exception filters when it can detect that the code wrapped in the try {} block might throw a C++ exception. An exception filter ensures that the destructor of any local C++ objects get called when the stack is unwound while handling an exception. It makes RAII ...
4,573,751
4,573,797
Bit twiddling for checking whether a number is in particular range
I found some interesting bit twiddling in "source\common\unicode\utf.h" file of ICU library (International Components for Unicode). The bit twiddling is intended for checking whether a number is in a particular range. // Is a code point in a range of U+d800..U+dbff? #define U_IS_LEAD(c) (((c)&0xfffffc00)==0xd800) I ha...
For these tricks to apply, the numbers must have some common features in their binary representation. 0xD800 == 0b1101_1000_0000_0000 0xDBFF == 0b1101_1011_1111_1111 What this test really does is to mask out the lower ten bits. This is usually written as onlyHighBits = x & ~0x03FF After this operation ("and not") the...
4,573,773
4,573,829
Own memory management in Objective-C++
For C++ code I can manage memory on my own by using placement new/delete operator and their arraycounterparts. Now I‘d like to use my memory manager also for Objective-C code. I thought about replacing NSObject‘s alloc: and dealloc: methods, but poseAsClass: doesn‘t work any longer. So: How can I force it using my me...
Think you're on a wrong path - the fundamentals of how the reference counting (and indeed garbage collection on non iOS devices) work are, I suspect, too embedded into the language implementation to make this a realistic possibility. I also don't understand why you'd want to do this, unless you've a particular fondness...
4,573,846
4,573,851
How to exit a process run with C++ if it takes more than 5 seconds?
I'm implementing a checking system in C++. It runs executables with different tests. If the solution is not correct, it can take forever for it to finish with certain hard tests. That's why I want to limit the execution time to 5 seconds. I'm using system() function to run executables: system("./solution"); .NET has a...
Use a QProcess with a QTimer so you can kill it after 5 seconds. Something like; QProcess proc; QTimer timer; connect(&timer, SIGNAL(timeout()), this, SLOT(checkProcess()); proc.start("/full/path/to/solution"); timer.start(5*1000); and implement checkProcess(); void checkProcess() { if (proc.state() != QProcess::...
4,574,246
7,791,906
Can I use C++11 with Xcode?
I am considering the use of some C++11 features (like auto for instance) in some cross-platform projects (Windows+Mac). On Windows, Visual Studio supports parts of the upcoming C++11 standard that would allow me to simplify parts of the code base so naturally I would be interested in starting to use these features. But...
Xcode 4.2 had finally added support for C++0X: In the project build settings screen, switch on "All" options. In the "Build Options" section, set compiler to "Apple LLVM compiler 3.0". Scroll down to "Apple LLVM Compiler 3.0 - Language" section and set "C++ Language Dialect" to "C++0X" and "C++ Standard Library" to "l...
4,574,321
4,574,380
Overriding function in C++ doesn't work
#include <cstdio> using namespace std; class A { public: virtual void func() { printf("A::func()"); } }; class B : public A { public: virtual void func() { printf("B::func()"); } }; int main() { A a = *(A *)new B(); a.func(); } The question is simple: why a->func() calls function in class A even though ...
A a = *(A *)new B(); a.func(); Here's what happens in this code, step by step: new B(): a new object of type B is allocated on the free store, resulting in its address (A*): the address of the object is cast to A*, so we have a pointer of type A* actually pointing to an object of type B, which is valid. All OK. A a: ...
4,574,437
4,574,899
Visual Studio 2010 Problem with .NET 4.0
Today I opened an C++ Project, but I just receive the "Project Target Framework Not Installed" (Targeted framework: .NETFramework,Version=v4.0) At first my Project does not use any .NET Framework / CLR. (Win32 Console Application) At second I have 4.0 installed. At third in the Project XML File I does not found an Tar...
I got my own Solution for my problem here is it, if someone have the same. I just added: <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> at <PropertyGroup Label="Globals"> I don´t know why it don´t find 4.0 but 3.5. But no matter. Win32 without CLR dont need any .NET.
4,574,479
4,574,512
What are the alternatives to public fields?
I am programming a game in java, and as the question title suggestions i am using public fields in my classes. (for the time being) From what i have seen public fields are bad and i have some understanding why. (but if someone could clarify why you should not use them, that would be appreciated) The thing is that also ...
It's common to use getters and setters instead of giving other objects permission to change your fields directly. That might not make any sense when you see that 99.99% of your getters and setters don't do anything except what you could have done with direct access to the fields. But what happens when you decide that...
4,575,098
4,575,315
Documentation concerning platform-specific macros in Linux/POSIX
When compiling a C/C++ program under Windows using Visual Studio (or a compiler that tries to be compatible) there is a predefined macro _WIN32 (Source: http://msdn.microsoft.com/en-us/library/b0084kay.aspx) that you can use for platform-specific #ifdef-s. What I am looking for is an analogon under Linux: a macro which...
I once collected the identifying macros for use by pkgsrc, a cross-platform package system: http://www.netbsd.org/docs/pkgsrc/fixes.html#fixes.build.cpp I didn't find any authoritative source back then.
4,575,192
4,575,228
Why is C++ backward compatible with C ? Why isn't there some "pure" C++ language?
C and C++ are different languages, blababla we know that. But if those language are different, why is it still possible to use function like malloc or free ? I'm sure there are all sort of dusty things C++ has because of C, but since C++ is another language, why not remove those things to make it a little less bloat an...
About "Why there's no "pure" C++ language... Well, there is at least one. The most popular one is called D, it's great, well-designed, feature-rich, pleasant to code with, and you can use C libraries with it. Ah, and almost nobody uses it. :) The direct reason is that C++ is not bad enough to give people a good reason ...
4,575,249
4,575,760
how to assign base class object to a derived class object?
Assuming I have a base class A and publicly derived class B, how should I assign A object to the A base class subobject of B? class A {...}; class B : public A {...}; A a(..); B b(..); static_cast<A&>(b) = a; ??? Is that doable without writing assignement operator for B? Are there any potential problems with casting b...
Writing another answer to demonstrate why and how assign a base class object to a derived class object. struct TimeMachineThing_Data { .. .. }; class TimeMachineThing : private TimeMachineThing_Data { static std::stack<TimeMachineThing_Data> m_stateHistory; void SaveState() { m_stateHistory.push_back(...
4,575,439
4,578,570
Can't Create Monochrome Bitmap from HBITMAP got by GDI+ Bitmap::GetHBITMAP
I am unable to Create a Monochrome Mask for a 24BPP Colour image with SetBkColor() > BitBlt[SRCCOPY]. The Mask ends up completely Black. The entire thing works only if I use LoadImage() instead to get the HBITMAP. Bitmap img(L"Ball.bmp"); HBITMAP hBM; img.GetHBITMAP(Color::White, &hBM); //hBM = LoadBitmap(GetModuleHand...
Solved it: How to genrate a monochrome bit mask for a 32bit bitmap
4,575,491
4,575,549
Template method over non-template method in derived class
class A { public: template<typename T> void func(size_t n, T values[]) { ... } }; class B : public A { public: void func(size_t n, uint32_t values[]) { ... } }; Why does function B::func() not take precedence over the function template A::func() when calling this code? uint32_t values[5]; A* obj = new B(); ob...
Two reasons- In C++ a member function only overrides a base class member function if the base class function is marked virtual. Otherwise, C++ treats the two as independent functions that coincidentally have the same name. This contrasts with Java, where functions atomatically override base class functions. In C++, ...
4,575,527
4,575,906
C++ Vectors / Classes /Threading
I'm Using Win7 / VS2008 (9) SDK 6/7.1 i faced a problem in a code that i'm using the mini version of the code as follows class CONNECTION { int/std::string/bool vars; // just to make it simple CONNECTION ( int defaultvar ); CONNECTION ( const CONNECTION& copycon ) ~CONNECTION ( ); DWORD static WIN...
std::vector is not designed to be thread safe. Therefore you have to use some sort of mutex to make sure only one thread accesses it at a time. Otherwise, if any thread resizes the vector, the vector may have to allocate new storage, copy elements, then free the old storage... and clearly freeing the old storage while...
4,575,582
4,575,625
What are the main differences between C++, D and C++0x?
We all encounter and hear them more often lately and i'd like some good comparison between them right here on stackoverflow. Links, references and articles are fine also.
My experience is mostly that C++0x tweaks certain aspects of C++, but essentially, it's the same language, just cleaner and somewhat more flexible. However, there are plenty of the major problems left in C++0x, like #include, and the automatic type deduction code for regular functions doesn't go far enough by quite som...
4,575,598
4,575,652
Function from Integers to the [0,1] float interval
Given an integer I would like to produce a unique floating point number in the interval [0,1]. (this number will be used as id). The problem I found with all functions I have thought about, is that they encounter duplicates before running out of integer values. For example if f(a:int):float = 0.a then f(16000) = 0.16 ...
As someone else pointed out you can simply cast an int to a float of the same size to get a unique float (with some post-filtering for NaN and -0 and Inf). However, that will not meet your requirement of being in [0,1]. In fact, you can use that relation to show that there are not enough floats in [0,1] to represent ...
4,575,643
4,575,677
Floating point inaccuracies
While writing a function which will perform some operation with each number in a range I ran into some problems with floating point inaccuracies. The problem can be seen in the code below: #include <iostream> using namespace std; int main() { double start = .99999, end = 1.00001, inc = .000001; int steps = (...
Your sample output only looks wrong because of how ostream rounds by default. You can set precision to get some other output. cout.precision(10); cout << (start + (inc * i)) << endl; Here's what I get now: 0.99999 0.999991 0.999992 0.999993 0.999994 0.999995 0.999996 0.999997 0.999998 0.999999 1 1.000001 1.000002 1.00...
4,575,721
4,575,768
valgrind & C++ : building std::string from character buffers
Simple C++ / valgrind question I'm hoping somebody can help out with. When running valgrind against the following code, I get two possible leaks related to std::string : ==10325== 17 bytes in 1 blocks are possibly lost in loss record 1 of 2 ==10325== at 0x402569A: operator new(unsigned int) (vg_replace_malloc.c:255...
Terminating the program by calling exit() is not really an orderly shutdown, it basically aborts the program at the current place. Therefore str and str2 are not destroyed before program termination and valgrind picks up on that. When you exit the program normally by just returning from main, the destructors for str an...
4,575,767
4,575,782
performance considerations when moving member functions that are used only by one other member function and making them local functions?
Are there performance considerations when moving member functions of a class that are used only by one other member function of that class and making them local functions at the start of the function they are being used by instead? http://www.flipcode.com/archives/Local_Functions_In_C.shtml
No, there's not. It's just a normal function call. It's worth mentioning that you can't use local structs or classes as template arguments, so if you were thinking of using them for STL comparators then forget it :)
4,575,806
4,575,834
Why does this string search and replace segfault?
colours is a std::map<string, string> where the first element of each pair is a 2 letter std::string colour code, and the second element is the 7 character std::string shell escape code for that colour. size_t i; for(map<string, string>::iterator iter = colours.begin(); iter != colours.end(); iter++) { while((i = t...
string::replace takes a start position and a length, not a start position and an end position. Also sizeof does not return the length of a string. So the third line should probably read: text.replace(i, iter->first.length(), iter->second); For what it's worth, sizeof returns the amount of stack space consumed by the...
4,575,976
4,576,136
boost::program_options - Is is possible to enforce mandatory flag?
I'm using boost::program_options in my program. I want to make a certain flag mandatory. Is is possible to do this with program_options in a way that it'll enforce this itself? i.e., throw an error message?
According to the documentation you can specify that an option is required in the option description: options_description desc; desc.add_options() ("help", "produce help") ("count", value<int>()->required(), "number of executions") ;
4,576,019
4,576,063
C++ drawing pixels question
How to make window, or more like clipping region , where I'll be able to draw pixels? It might use WinApi, however I don't want my project to look like winapi one, so it will have int main(){} instead of int WINAPI WinMain(HINSTANCE ... I have found an example, where I'm able to draw in console window int main() { ...
You won't like this - in Windows, you have to create a window, then override WM_PAINT message, then draw what you have to draw when you are called from the system. That's old-school way of doing things, and it isn't so bad. Some interesting and relevant links: http://www.winprog.org/tutorial/bitmaps.html http://www.co...
4,576,066
4,576,088
C++ -- Is there an implicit cast here from Fred* to auto_ptr<Fred>?
I saw the following code, #include <new> #include <memory> using namespace std; class Fred; // Forward declaration typedef auto_ptr<Fred> FredPtr; class Fred { public: static FredPtr create(int i) { return new Fred(i); // Is there an implicit casting here? If not, how can we return ...
std::auto_ptr does have a constructor that takes a raw pointer as its argument, but that constructor is explicit and cannot be used as a converting constructor. This code will not compile.
4,576,113
4,576,210
How to set relative paths in VS2010
I've just found some source on the web and want to compile it. When I open the project and look for the relative paths of the files it writes $(ZLibSrcDir)\adler32.c where do I set the ZLibSrcDir at Visual Studio 2010? For somehow it is trying to look at some wrong path. Thanks in advance
You can set user macros in the Property Manager. Right click a property sheet and open the properties dialog, and there's a section called User Macros. There might already be a macro called ZLibSrcDir, or you might have to create a new property sheet to be able to add it.
4,576,127
4,576,264
How to create a Log in C++?
I want to print lots of debug log prints in C++. Is there a built-in library that will allow me to turn on/off these prints without commenting them out as I do today (i.e., let the user use a -print_log/-debug flag)? EDIT: third party loggers will be welcomed. Please include a short example of how to do this.
If you're using Boost, consider using the proposed Boost.Log library. It's not yet part of the official Boost release, but I've found it to be quite good. Manually integrating it into the Boost build process was a little challenging though.
4,576,182
4,576,186
The easiest way to draw an image?
Assume you want to read an image file in a common file format from the hard drive, change the color of one pixel, and display the resulting image to the screen, in C++. Which (open-source) libraries would you recommend to accomplish the above with the least amount of code? Alternatively, which libraries would do the ab...
The CImg library is easy to use. CImg<unsigned char> img("lena.png"); // Read in the image lena.png const unsigned char valR = img(10,10,0,0); // Read the red component at coordinates (10,10) const unsigned char valG = img(10,10,0,1); // Read the green component at coordinates (10,10) const u...
4,576,282
4,576,360
Preprocessor macros: how to insert arguments?
The code has a number of following sections: int filter; #ifdef INPUTFILTER_FOO LOG4CXX_DEBUG(log, "FOO filter used"); filter = F_FOO; #endif They are used multiple times in the code (used to provide I/O, threading support etc for all testing configurations), Circa they are essential for debugging but make t...
Here's my try, although i'm not 100% sure if it works cause i'm unable to test it right now, and also different compilers handle preprocessor macros a little bit differently. But I think something like this works at least in visual studio. Basically, you have to use a helper macro to convert the parameter into a string...
4,576,307
4,576,323
C++ Allocate Memory Without Activating Constructors
I'm reading in values from a file which I will store in memory as I read them in. I've read on here that the correct way to handle memory location in C++ is to always use new/delete, but if I do: DataType* foo = new DataType[sizeof(DataType) * numDataTypes]; Then that's going to call the default constructor for each i...
Use vectors!!! Since you know the number of elements, make sure that you reserve the memory first (by calling myVector.reserve(numObjects) before you then insert the elements.). By doing this, you will not call the default constructors of your class. So use std::vector<DataType> myVector; // does not reserve anything ....
4,576,568
4,576,664
Mock implementations in C++
I need a mock implementation of a class - for testing purposes - and I'm wondering how I should best go about doing that. I can think of two general ways: Create an interface that contains all public functions of the class as pure virtual functions, then create a mock class by deriving from it. Mark all functions (wel...
Just as I would not hand-author mock objects in Java, I would also not hand-author them in C++. Mock objects are not just stubbed out classes, but are test tools that perform automated checks like making sure certain methods are called, or that they are called in order, etc. I would take a look at the various mock obje...
4,576,707
4,576,842
Bind members of different classes
In a C++ program I have two classes (structs) like struct A { int x; double y; // other members }; struct B { int x; double y2; // other members }; I'd like to somehow "bind" the corresponding members, e.g. A::x to B::x and A::y to B::y2. By "bind" I mean ability to obtain a reference to the b...
Perhaps you want some template metaprogramming along the lines of this: #include <iostream> // An item in the list of bound members template<typename Class, typename T, T Class::*Ptr, typename Next = void> struct m { typedef Class containing_type; typedef T value_type; typedef Next next; static T Class...
4,576,865
4,576,869
Rounding Decimals to whole numbers
I was looking around and could not find exactly what I was looking for. I want to round all my numbers up to the whole number. Example: 5.9 would be 6 5.5 would be 6 5.1 would be 6 5.000001122 would be 6 5.0 would be 5 I was thinking if I put them into ints that would get rid of the decimal but it did not look right a...
You're looking for the ceil() function from <math.h> or std::ceil() from <cmath>.
4,576,905
4,576,919
C# internal == public C++
Is the C++ public keyword exactly equivalent to internal keyword in C#? As far as I understand, public in C++ means "can be used everywhere within the compilation unit".
No, it's not exactly equivalent. For starters, a C++ "compilation unit" isn't equivalent to a .NET assembly. Next, in C++ there is an additional concept, "linkage", which determines whether a type can be used outside the compilation unit. Whether the same header file is included in other compilation units also affect...
4,577,056
4,577,127
How can I play sound out of just one speaker in C++?
I have a audio card that supports multiple speakers (Creative SB X-Fi). What I am trying to do is write a program in C++ (Windows 7 Environment, Visual Studio IDE) that will play a given mono wav file to one of the 4 speakers I have hooked up. Can anybody point me in the correct direction as to specific functions tha...
You can play sound through a set of surround sound speakers using DirectSound. See the MSDN page "Sounds in 3-D".
4,577,094
4,577,216
Restoring default GUI QStyle on Windows 7 OS
I'm writing a GUI application using Qt 4.7 on Windows 7 Ultimate 32 bit. I'd like to let users change the GUI style from main menu. Several QStyles (QCDEStyle, QWindowsStyle, QCleanlooksStyle etc) can be selected from the menu and I'm using QApplication::setStyle() to set the new style. I'd like to have an option to re...
After a bit of sourcediving, it turns out styles have their object names set to the style name, so you can say: QString defaultStyle = this->style()->objectName(); and later qApp->setStyle(defaultStyle);
4,577,278
4,577,807
Is SDL_Delay() thread safe?
I have been working on a C++ project that uses SDL, and wonder if it is safe to call SDL_Delay concurrently from different threads or if I need to write a wrapper to serialize access to the function. I rather avoid any overhead, as the delays I need are very small. Has anyone have tried this? I am using c++ on OS X and...
I don't have any direct experience with SDL_Delay but according to: this documentation it is not thread safe and you should probably use a wrapper.
4,577,291
4,578,081
C++: Reference and Pointer question (example regarding OpenGL)
I would like to load textures, and then have them be used by multiple objects. Would this work? class Sprite { GLuint* mTextures; // do I need this to also be a reference? Sprite( GLuint* textures ) // do I need this to also be a reference? { mTextures = textures; } void Draw( textureNumbe...
yes, this would work no need to make them be a reference: you store/pass a copy of a pointer (it's fast), and you don't plan to change this pointer outside there're many different ways to do this, and the right one depends on your other code requirements. e.g. you can use a global instance of textures: textures.cpp...
4,577,297
4,577,387
Socket Class: Receiving data on windows keeps appending additional data?
I've recently written a (dirty, yet working) Socket class for a mininmal purpose. The class itself works fine so far, except that receiving data will keep appending additional data, however, only on windows. The Additional data is usually something like (replace $RANDOM_NUMBERS with random numbers): TA,guid=$RANDOM_NU...
buffer.reserve(maxlen); n = this->readInto(&buffer[0], maxlen); if(n < 0) { throw Socket::ReadError("ERROR reading from socket"); } result = &buffer[0]; result does not know how many meaningful bytes are placed in the buffer. So it keeps reading bytes until it encounters a zero. That's how garbage gets into your ...
4,577,453
4,577,510
fcgio.cpp:50: error: 'EOF' was not declared in this scope
I am attempting to build fastcgi on a Linux Ubuntu 10.x machine. I run the following commands: ./configure make and I get the following error: fcgio.cpp: In destructor 'virtual fcgi_streambuf::~fcgi_streambuf()': fcgio.cpp:50: error: 'EOF' was not declared in this scope fcgio.cpp: In member function 'virtual int fcgi_s...
EOF is a C macro and seems that you do not have it defined in fcgio.cpp or that something has undefined it. I would first try to add #include <stdio.h> to start of fcgio.cpp.
4,577,564
4,580,404
Modifying resource contents of a running executable
All, I store my application settings in a resource. When my program first loads, I read the specified resource using WinAPI. I then parse the retrieved byte data. This works flawlessly for me. Now let's say that a user alters a setting in my application. He/she checks a checkbox control. I would like to save the upda...
It is 100% possible to write self-modifying code. It's just not very easy to do. When you launch your executable file, windows maps it in memory. This essentially locks the file and prevents edits while it is running. You can, obviously, unmap your program (by using an undocumented function in ntdll). When your file is...
4,577,616
4,577,633
Drawing Rounded Rectangle in DirectX/3D for 2D
I'm using Direct3D to draw 2D elements in a C++ application of mine, and it'd be neat if I could create rounded-rectangle GUI elements that were varying in size, but I'm not sure how to do that in the most efficient manner possible. I thought of the "easy" way which would be to have images of the four corners and then ...
Ideally you create a 9 polygons, by dividing a square up. The 9 images then draw the corners/sides/center and you can scale it however you want. You are going to need to know how to draw and texture map polygons in order to do this, it lets you scale the corners and the box if required.
4,577,784
4,577,905
Get a font filename based on Font Name and Style (Bold/Italic)
This has been driving me crazy all day. I need to get a font filename (eg. Arial.ttf) based on its name (Arial in this case) and whether it is bold, italic or both. Using those pieces of information, I need to find the font file so I can use it for rendering. Some more examples: Calibri, Bold would resolve to calibrib...
First, to my knowledge, there is no reliable way to do that. The Windows API deals with font families and mappings, not with font files, which are dealt with at a lower level. Also note that even if you manage to get the file name of a font, no rendering function (that I know of) will accept it, so what will you do wit...
4,577,838
4,577,881
Smart pointers in container like std::vector?
I am learning about smart pointers (std::auto_ptr) and just read here and here that smart pointers (std::auto_ptr) should not be put in containers (i.e. std::vector) because even most compilers won't complain and it might seem correct. There is no rule that says smart pointers won't be copied internally (by vector clas...
Yes, you really can't use std::auto_ptr with standard containers. std::auto_ptr copies aren't equivalent, and because standard containers (and algorithms) are allowed to copy their elements at will this screws things up. That is, the operation of copying a std::auto_ptr has a meaning other than a mere copy of an object...
4,577,908
4,578,135
Scaling Rotation Shearing Reflection algorithms
i use EASYBMP library and i want to know the most effective way to scale , rotate , shear and reflect algorithm. i want the most optimized to do it.
The most effective way to scale, rotate, shear and reflect is to use the power of your graphics card - for example through OpenGL. If you still want to do bitmap pixel operations yourself, typically you do this using linear algebra. This is not super easy to figure out, so I recommend finding some good study material, ...
4,578,000
4,586,874
DVB-T tune request parameters
I'm working in GraphEdit to capture video from a Pinnacle PCTV card, in preparation for writing a program that will do the same, among other things. What, precisely, is the meaning of the tune request parameters? How do I find the appropriate values to use, and is there a way to do so automatically? (ie, not to have t...
TransEdit can help you find some parameters. The ONID you can find on dvbservices.com. As far as I know you need to be able to configure the following values: IDVBTLocator::put_CarrierFrequency() IDVBTLocator::put_Bandwidth() IDVBTuneRequest::put_SID() IDVBTuneRequest::put_TSID() IDVBTuneRequest::put_ONID() For the Ba...
4,578,239
4,589,346
debugging with netbeans
I'm running netbeans under mac os x. When I debug it is terribly slow and often crashes. Has anyone else found the same issue with it?
Try giving it a larger amount of memory: http://gapes.wordpress.com/2010/08/04/tuning-jvm-switches-for-performance/
4,578,249
4,578,267
How to find the longest word in a text document?
I'm looking for a way to find the longest word ( base on length ) in a text document using STL and boost. Here is my solution. However, it wasn't good at all, there were too many operations( token, sort .. ). Is there any simpler way to solve this problem? // utility and memory #include <utility> #include <functional>...
You can use std::max_element. Just give to it iterator pair and the comparator which you've already written.
4,578,253
4,578,317
What is the best way to parse python script file in C/C++ code
I am embedding python in C/C++ program. What I am trying to do is to parse the python script file from the C/C++ program, break the file to "blocks" so that each "block" is an a valid command in python code. Each block I need to put into std::string. For example: #PythonScript.py import math print "Hello Python" i = ...
If you want to do syntax analysis you should look into Pythons grammar (and maybe use Bison as a parser generator) Python grammar specs: http://docs.python.org/reference/grammar.html http://inst.eecs.berkeley.edu/~cs164/sp10/python-grammar.html
4,578,291
4,578,380
C++ How does Allegro or SDL create window?
How does Allegro or SDL create window for Windows and how to do it by myself? I'm trying to write WinApi wrapper for games, but I'm completly lost, when I see basic WinApi template and want to wrap it to something like this init(); while() { update(); } exit();
They use CreateWindowEx. A really simple WinAPI app that creates a window looks a little like this: #include <Windows.h> // If you're using MSVC, this is the easiest HINSTANCE. Other compilers // get it from WinMain and pass in to constructor. extern "C" IMAGE_DOS_HEADER __ImageBase; HINSTANCE hInstance = (HINSTANCE)&_...
4,578,316
4,578,337
adding class to mfc project
I am trying to add a class which holds the object of the gui. The file is COptimataModulDlg, and the new class I want to add is Manager. I've tried writing this and it didnt work: //Manager.h #pragma once class Manager { public: Manager(); ~Manager(); private: COptimataModulDlg omg; //the problem i...
You probably didn't #include the file where COptimataModulDlg is defined in Manager.h? Maybe it is included in manager.cpp?
4,578,423
5,387,992
Side by side madness - running binaries on the same computer
Here's my configuration: Computer A - Windows 7, MS Visual Studio 2005 patched for Win7 compatibility (8.0.50727.867) Computer B - Windows XP SP2, MS Visual Studio 2005 installed (8.0.50727.42) My project has some external dependencies (prebuilt DLLs - either build on A or downloaded from the Internet), a couple of D...
Your question has the answer to your problem: Computer A has VC runtime of version 8.0.50727.867, and Computer B has only version 8.0.50727.42. You built your libraries on Computer A, and they depend on version 867 of VC runtime. (This can be found in manifest embedded in the libraries.) When you copy them to Computer ...
4,578,474
4,578,516
Question on function references and threads
I was randomly testing std::thread in my virtual linux machine (GCC 4.4.5-Debian) with this test program: #include <algorithm> #include <thread> #include <iostream> #include <vector> #include <functional> using namespace std; static int i=0; void f( vector<int> &test) { ++i; cout << "Push back called" << endl;...
Looks to me like a threading problem. While I'm not 100% sure, it should be noted that all 1000 threads: do ++i on the same int value (it's not an atomic operation- you may encounter problems here, you can use __sync_fetch_and_add(&i,1) instead (note that it's a gcc extension not standard C++); do push_back simultaneo...
4,578,543
4,578,614
Argument type deduction, references and rvalues
Consider the situation where a function template needs to forward an argument while keeping it's lvalue-ness in case it's a non-const lvalue, but is itself agnostic to what the argument actually is, as in: template <typename T> void target(T&) { cout << "non-const lvalue"; } template <typename T> void target(const...
This is a known problem and the purpose of rvalue references in C++0x. The problem has no generic solution in C++03. There is some archaic historical reason why this occurs that is very pointless. I remember asking once and the answer depressed me greatly.
4,578,967
4,579,069
Cube sphere intersection test?
What's the easiest way of doing this? I fail at math, and i found pretty complicate formulaes over the internet... im hoping if theres some simpler one? I just need to know if a sphere is overlapping a cube, i dont care about which point it does that etc. I'm also hoping it would take advantage of the fact that both sh...
Looking at half-spaces is not enough, you have to consider also the point of closest approach: Borrowing Adam's notation: Assuming an axis-aligned cube and letting C1 and C2 be opposing corners, S the center of the sphere, and R the radius of the sphere, and that both objects are solid: inline float squared(float v) { ...
4,579,043
4,580,889
Base class -> Derived class and vice-versa conversions in C++
I have the following example code: #include <iostream> #include <string> using namespace std; class Event { public: string type; string source; }; class KeyEvent : public Event { public: string key; string modifier; }; class MouseEvent : public Event { public: string button; int x; int y...
Your function generateEvent does the following: creates a KeyEvent converts (upcasts) the object into an Event by copying and slicing returns that Event object You then try to take that Event object copy and put it into a KeyEvent again. You are trying to use polymorphism but are actually just slicing. Consider (with...
4,579,148
4,579,329
D3D device in vgasave
Is it possible to create device/directx application when pc uses vgasave mode? This is my init function: d3d = Direct3DCreate9(D3D_SDK_VERSION); // create the Direct3D interface D3DPRESENT_PARAMETERS d3dpp; // create a struct to hold various device information ZeroMemory(&d3dpp, sizeof(d3dpp)); //...
You've filled out way too few parameters in the D3DPRESENT_PARAMETERS. You've alomst certainly got bad settings for the back buffer and that kind of thing. If CreateDevice returns D3DERR_NOTAVAILABLE, then the d3ddev pointer is NULL, resulting in the access violation when you try to clear the back buffer- since there i...
4,579,215
4,579,312
Cross-platform iteration of Unicode string (counting Graphemes using ICU)
I want to iterate each character of a Unicode string, treating each surrogate pair and combining character sequence as a single unit (one grapheme). Example The text "नमस्ते" is comprised of the code points: U+0928, U+092E, U+0938, U+094D, U+0924, U+0947, of which, U+0938 and U+0947 are combining marks. static void Mai...
You should be able to use the ICU BreakIterator for this (the character instance assuming it is feature-equivalent to the Java version).
4,579,421
4,579,443
Looking For Realtime Facial Feature Detection/Extraction Library
Possible Duplicate: Where can I find facial detection software, algorithms, etc? Does anyone have any pointers to a C/C++ library for detecting/extracting key facial features in realtime? Typical scenario: a subject recites some lines from a play or sings a song and the software - in realtime - records the features....
This is a relatively cutting edge technology. When done for movie production, it requires lots of advance setup, multiple cameras, custom software, and serious processing power. You will not find a stock-library to do this.
4,579,640
4,579,696
DLL Mutex - an example
Possible Duplicate: DLL thread safety Hi Im writting a DLL file in MS VS C++ express, which is loaded in multiple client applications at the same time, it uses shared memory with the other instances of the loaded DLL. Let us assume the DLL looks something like this: #include stdafx.h #pragma data_seg (".TEST") /...
The code of every process: // At the start of every process HANDLE sharedMemoryMutex = CreateMutex(NULL, FALSE, "My shared memory mutex"); // When you want to access shared memory: DWORD dwWaitResult = WaitForSingleObject(sharedMemoryMutex, INFINITE); if (dwWaitResult == WAIT_OBJECT_0 || dwWaitResult == WAIT_ABANDONE...
4,579,794
4,579,808
Defining private static class member
class B { /* ... */ }; class A { public: A() { obj = NULL; } private: static B* obj; }; However this produces huge mass of linker errors that symbol obj is unresolved. What's the "correct" way to have such private static class member without these linker errors?
You need to define like this : this is in the header : class B { ... } class A { public: A() { obj = NULL; } private: static B* obj; } this is in the source B* A::obj = NULL;
4,579,924
4,579,977
No warning on assignment of int to short (gcc)
I often use assignment of "longer" typed variables to "shorter" ones, for example int to short or uint32_t to uint8_t. One day i decided to find all such cases in my code using gcc, but found to my amazement that gcc didn't output any warnings! int long_value; short short_value; std::cin >> long_value; // Example input...
This feature was added in gcc 4.3 version. Previously this was not available. I hope you are using gcc version 4.2 or below. http://gcc.gnu.org/wiki/NewWconversion confirms this. This bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=2707 also talks about it.
4,580,018
4,580,074
C++ filtering debug events
Is there a built-in way in C++/Windows to filter events that WaitForDebugEvent captures? that WaitForDebugEvent will just ignore?
No, I don't think you can filter any debug event. The application calling WaitForDebugEvent will get all the events. You can, however ignore any particular event after receiving it in your application.