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
2,619,659
2,619,783
How do you make an in-place construction of a struct casted to array compile in Visual C++ 2008?
I'm working with quite a big codebase which compiles fine in linux but vc++ 2008 spits errors. The problem code goes like this: Declaration: typedef float vec_t; typedef vec_t vec2_t[2]; The codebase is littered with in-place construction like this one: (vec2_t){0, divs} Or more complex: (vec2_t){ 1/(float)Vid_GetScree...
You're using a GCC extension that MSVC simply doesn't support, "compound literals", also called "constructor expressions" in older GCC docs. If you want portable code, I think you'll need to change the code to declare the structs normally and initialize them with initializers that have constants expressions or using st...
2,619,812
2,619,816
sqrt(int_value + 0.0) -- Does it have a purpose?
while doing some homework in my very strange C++ book, which I've been told before to throw away, had a very peculiar code segment. I know homework stuff always throws in extra "mystery" to try to confuse you like indenting 2 lines after a single-statement for-loop. But this one I'm confused on because it seems to serv...
Is this the poormans way of doing a static cast to a double? Yes. You can't call sqrt with an int as its parameter, because sqrt takes a float, double, or long double. You have to cast the int to one of those types, otherwise the call is ambiguous.
2,619,814
2,619,835
Deleting a non-owned dynamic array through a pointer
I'm relatively novice when it comes to C++ as I was weened on Java for much of my undergraduate curriculum (tis a shame). Memory management has been a hassle, but I've purchased a number books on ansi C and C++. I've poked around the related questions, but couldn't find one that matched this particular criteria. Maybe ...
I assume you would replace original by cstr, otherwise the code won't compile as cstr is not declared. The error here is that the size of the allocated array is too small. You want char* ncstr = new char[len+1]; to account for the terminating \0. Also, if you delete shaved right after the function returns, there is no ...
2,619,830
2,619,896
Why did this work with Visual C++, but not with gcc?
I've been working on a senior project for the last several months now, and a major sticking point in our team's development process has been dealing wtih rifts between Visual-C++ and gcc. (Yes, I know we all should have had the same development environment.) Things are about finished up at this point, but I ran into a ...
Tokens will be automatically replaced by a null-character by function strtok. That is not what you can do with constant data. To make your code safe and cross-platform consider using boost::tokenizer.
2,619,848
2,619,957
How to check if a position inside a std string exists ?? (c++)
i have a long string variable and i want to search in it for specific words and limit text according to thoses words. Say i have the following text : "This amazing new wearable audio solution features a working speaker embedded into the front of the shirt and can play music or sound effects appropriate for any situatio...
This is an excellent exercise in taking advantage of what the STL has to offer. You simply open a reference and cherry-pick algorithms and classes for your solution! #include <iostream> // algorithm,string,list,cctype,functional,boost/assign.hpp using namespace std; struct remove_from { remove_from(string& text) :...
2,619,853
2,625,331
Emacs - override indentation
I have a multiply nested namespace: namespace first {namespace second {namespace third { // emacs indents three times // I want to intend here } } } so emacs indents to the third position. However I just want a single indentation. Is it possible to accomplish this effect simply?
Use an an absolute indentation column inside namespace: (defconst my-cc-style '("gnu" (c-offsets-alist . ((innamespace . [4]))))) (c-add-style "my-cc-style" my-cc-style) Then use c-set-style to use your own style. Note that this only works in c++-mode, c-mode doesn't know 'innamespace'.
2,619,866
2,619,889
Overwriting a range of bits in an integer in a generic way
Given two integers X and Y, I want to overwrite bits at position P to P+N. Example: int x = 0xAAAA; // 0b1010101010101010 int y = 0x0C30; // 0b0000110000110000 int result = 0xAC3A; // 0b1010110000111010 Does this procedure have a name? If I have masks, the operation is easy enough: int mask_x = 0xF00F; // 0...
A little bit shifting will give you the masks you need. template<typename IntType> IntType OverwriteBits(IntType dst, IntType src, int pos, int len) { IntType mask = (((IntType)1 << len) - 1) << pos; return (dst & ~mask) | (src & mask); }
2,620,031
2,680,988
WinMain not called before main (C/C++ Program Entry Point Issue)
I was under the impression that this code #include <windows.h> #include <stdio.h> int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { printf("WinMain\n"); return 0; } int main() { printf("main\n"); return 0; } would output WinMain, but of course nothin...
Just found this work around and kind of feel dumb. #define main USER_Main This then takes main out of line for being the programs entry point while still hiding the fact that anything was messed with from the user.
2,620,191
2,620,277
What is better, a STL list or a STL Map for 20 entries, considering order of insertion is as important as the search speed
I have the following scenario.The implementation is required for a real time application. 1)I need to store at max 20 entries in a container(STL Map, STL List etc). 2)If a new entry comes and 20 entries are already present i have to overwrite the oldest entry with the new entry. Considering point 2, i feel if the conta...
With only 20 elements, I would not worry much about which container you use. If you determine that the container chosen is in fact a detriment to the performance of your application, it should be relatively easy to swap out the container chosen and replace it with a more-efficient container later. With that being said...
2,620,197
2,620,229
Eclipse CDT: Import source / header files into my new project, without duplicating them
Im sure there is a very simple solution for this. I have a bunch of .cpp / .h files from a project, say in directory ~/files On the other hand, I want to create a c++ project using eclipse to work on those files, so I put my workspace on ~/wherever. Then I create a c++ project: ~/wherever/project, and include the sourc...
You could try: creating the project directly above the ~/files (which is not very clean, given the location of the sources in your home dir) using a linked folder importing existing sources in your project: details all the options (when your sources are also managed by a VCS like CVS, or when your sources are not mana...
2,620,205
2,620,249
Need GDI programming Guideline
I want to change my window design rapidly. I have OnPaint function which I am calling when WM_PAINT message received. The design change only when the event occure. I want that design should automatically update doesn't depend on event kindly guide me how can I make it possible.
All drawing code should be placed in WM_PAINT message handler or called from it. Your current code is OK. When window should be redrawn as result of some event, just call Invalidate() or UpdateWindow(), this is indirect call to WM_PAINT message handler.
2,620,218
2,622,526
Fastest container or algorithm for unique reusable ids in C++
I have a need for unique reusable ids. The user can choose his own ids or he can ask for a free one. The API is basically class IdManager { public: int AllocateId(); // Allocates an id void FreeId(int id); // Frees an id so it can be used again bool MarkAsUsed(int id); // Let's the user register ...
My idea is to use std::set and Boost.interval so IdManager will hold a set of non-overlapping intervals of free IDs. AllocateId() is very simple and very quick and just returns the left boundary of the first free interval. Other two methods are slightly more difficult because it might be necessary to split an existing...
2,620,314
2,620,376
C++ type-checking at compile-time
all. I'm pretty new to C++, and I'm writing a small library (mostly for my own projects) in C++. In the process of designing a type hierarchy, I've run into the problem of defining the assignment operator. I've taken the basic approach that was eventually reached in this article, which is that for every class MyClass i...
You can't perform this assert at compile time for the simple reason that the run-time types won't be known until, well, run time. assert(typeid(rhs) == typeid(*this)); return this->set(static_cast<Base const&>(rhs)); In the non-inline version you had dynamic_cast. I would retain this so that you get a well-defined err...
2,620,324
2,620,361
Allow member to be const while still supporting operator= on the class
I have several members in my class which are const and can therefore only be initialised via the initialiser list like so: class MyItemT { public: MyItemT(const MyPacketT& aMyPacket, const MyInfoT& aMyInfo) : mMyPacket(aMyPacket), mMyInfo(aMyInfo) { } private: const MyPacketT mMyPacke...
You're kind of violating the definition of const if you have an assignment operator that can change them after construction has finished. If you really need to, I think Potatoswatter's placement new method is probably best, but if you have an assignment operator your variables aren't really const, since someone could j...
2,620,357
2,620,426
Can a stack have an exception safe method for returning and removing the top element with move semantics?
In an answer to a question about std::stack::pop() I claimed that the reason pop does not return the value is for exception safety reason (what happens if the copy constructor throws). @Konrad commented that now with move semantics this is no longer relevant. Is this true? AFAIK, move constructors can throw, but perha...
Of course, not every type is move-enabled and C++0x even allows throwing move constructors. As long as constructing the object from an rvalue may throw it cannot be exception-safe. However, move semantics allows you to have many types that are nothrow-constructible given an rvalue source. Conditional support for this c...
2,620,377
2,620,398
Lua - Reflection - Get list of functions/fields on an object?
I'm new to Lua and dealing with Lua as a scripting language in an alpha release of a program. The developer is unresponsive and I need to get a list of functions provided by some C++ objects which are accessible from the Lua code. Is there any easy way to see what fields and functions these objects expose?
In Lua, to view the members of a object, you can use: for key,value in pairs(o) do print("found member " .. key); end Unfortunately I don't know if this will work for objects imported from C++.
2,620,409
2,620,573
Getting HWND of current Process
I have a process in c++ in which I am using window API. I want to get the HWND of own process. Kindly guide me how can I make it possible.
You are (incorrectly) assuming that a process has only a single HWND. This is not generally true, and therefore Windows can't offer an API to get it. A program could create two windows, and have two HWNDs as a result. OTOH, if your program creates only a single window, it can store that HWND in a global variable.
2,620,845
2,620,914
Sudden windows shut down during programming with Borland C++ followed by a blue screen!
This problem has happened to me twice.Both times during programming with Borland C++.when i wanted to run the simple code bellow:(completely what I wrote) int n, total=0, counter=1,average; while ( n ) { cin >> n; total = total + n; average = total / counter; counter++; cout <<average<<endl; }
BSOD is almost always a hardware or driver issue. It could be that a particular sequence of program operations is exercising something that is failing. Best thing to do is look at the memory dump in MS' analyzer to see if that points to a specific software item.
2,620,862
46,128,321
Using custom std::set comparator
I am trying to change the default order of the items in a set of integers to be lexicographic instead of numeric, and I can't get the following to compile with g++: file.cpp: bool lex_compare(const int64_t &a, const int64_t &b) { stringstream s1,s2; s1 << a; s2 << b; return s1.str() < s2.str(); } void...
1. Modern C++20 solution auto cmp = [](int a, int b) { return ... }; std::set<int, decltype(cmp)> s; We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering...
2,621,066
2,621,236
Calling unmanaged dll from C#. Take 2
I have written a c# program that calls a c++ dll that echoes the commandline args to a file When the c++ is called using the rundll32 command it displays the commandline args no problem, however when it is called from within the c# it doesnt. I asked this question to try and solve my problem, but I have modified it my ...
LPCSTR is not unicode, is it? Just use ANSI and you should be fine: CharSet = CharSet.Ansi
2,621,136
2,621,233
Compiling and using NTL c++ library for Windows
I have compiled the NTL inifite precision integer arithmetic library for c++, using Microsoft Visual Studio 2008. I did as explained, on this site, using the Visual Studio interface, rather than from the command prompt. Actually I would rather do it from the command prompt, but I was not sure how to. Anyhow, I got the ...
mpqs.h is definitely being included as the output asks you to refer to it. Seeing as MPQS.h does not appear to be included in the NTL library ... did you write it? If so can you post the code up? Also, shouldn't you included the library file somewhere on your build? Edit: There is no function find_smooth_values so wh...
2,621,436
2,627,183
Accidental Complexity in OpenSSL HMAC functions
SSL Documentation Analaysis This question is pertaining the usage of the HMAC routines in OpenSSL. Since Openssl documentation is a tad on the weak side in certain areas, profiling has revealed that using the: unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len, const unsigned char *d...
The documentation for the HMAC_Init_ex() function in OpenSSL 0.9.8g says: HMAC_Init_ex() initializes or reuses a HMAC_CTX structure to use the function evp_md and key key. Either can be NULL, in which case the existing one will be reused. (Emphasis mine). So this means that you can initialise a HMAC_CTX with...
2,621,460
2,621,476
operators computing direction
I encountered something that I can't understand. I have this code: cout << "f1 * f1 + f2 * f1 - f1 / f2 is: "<< f1 * f1 + f2 * f1 - f1 / f2 << endl; All the "f"s are objects, and all the operators are overloaded. The weird this is that the first computation is of the / operator, then the second * and then the first *;...
This is yet again a question of the order of evaluation of function parameters - C++ does not specify such an order. Your code is equivalent to: (f1 * f1) + (f2 * f1) - (f1 / f2) The three multiply and divide operations can be evaluated in any order. This is perhaps cleraer for named functions: add(f1*f2,f2*f1)).minus...
2,621,548
2,621,596
Program ends abruptly even in debugger - how did that happen?
I am trying to debug a program that unexpectedly shuts down. When I say "shuts down, I mean one moment I am seeing all the windows being displayed, each of which is showing all the right data,then suddenly all the windows disappear. The is no messagebox reporting anything wrong. So I tried running the program in the de...
Marcelo's answer is great. If for some reason you can't break on exit, install a function (takes no arguments, returns void) with atexit and break inside that.
2,621,650
2,621,656
Return reference from class to this
I have the following member of class foo. foo &foo::bar() { return this; } But I am getting compiler errors. What stupid thing am I doing wrong? Compiler error (gcc): error: invalid initialization of non-const reference of type 'foo&' from a temporary of type 'foo* const'
this is a pointer. So it should be return *this;
2,621,845
2,626,947
Void pointers in C++
I have written this qsort: void qsort(void *a[],int low,int high, int (*compare)(void*,void*)); When I call this on char *strarr[5]; It says invalid conversion from char** to void**. Why this is wrong? This is the code: #include<cstdlib> #include<cstdio> #include<iostream> using namespace std; inline void strswap(v...
An implicit conversion from any pointer type to void * is allowed, because void * is a defined to be a pointer type that has a sufficient range that it can represent any value that any other pointer type can. (Technically, only other object pointer types, which excludes pointers to functions). This does not mean that ...
2,621,905
2,621,915
sort array of size n
if an array of size n has only 3 values 0 ,1 and 2 (repeated any number of times) what is the best way to sort them. best indicates complexity. consider space and time complexity both
Count the occurences of each number and afterward fill the array with the correct counts, this is O(n)
2,622,200
2,622,803
Exceptions silently caught by Windows, how to handle manually?
We're having problems with Windows silently eating exceptions and allowing the application to continue running, when the exception is thrown inside the message pump. For example, we created a test MFC MDI application, and overrode OnDraw: void CTestView::OnDraw(CDC* /*pDC*/) { *(int*)0 = 0; // Crash CTestDoc* ...
After browsing similar questions I stumbled across this answer: OpenGL suppresses exceptions in MFC dialog-based application "Ok, I found out some more information about this. In my case it's windows 7 that installs KiUserCallbackExceptionHandler as exception handler, before calling my WndProc and giving me ...
2,622,246
2,622,697
Access to Oracle Database with sqlapi C++
I need to write some data in several database. I choose sqlapi.com I have made it for mysql and mssql. Now I have Problem with Oracle database. I have installed server and client on Ubuntu. In browser it works, but sqlapi says: libnnz10.so: cannot open shared object file: No such file or directory DBMS API Library '...
I think that you need to set the variable LD_LIBRARY_PATH to the file path of the shared lib. e.g. export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/oracle/instantclient/lib set the variable in .profile or .bash_profile. This depends on the shell you are using. Update Due to some new security requirements in ubuntu (see ht...
2,622,441
2,622,459
C++ integer floor function
I want to implement greatest integer function. [The "greatest integer function" is a quite standard name for what is also known as the floor function.] int x = 5/3; My question is with greater numbers could there be a loss of precision as 5/3 would produce a double? EDIT: Greatest integer function is integer less than...
You will lose the fractional portion of the quotient. So yes, with greater numbers you will have more relative precision, such as compared with 5000/3000. However, 5 / 3 will return an integer, not a double. To force it to divide as double, typecast the dividend as static_cast<double>(5) / 3.
2,622,755
2,622,828
Refresh text shown in a GTK+ widget?
Being resonably new to using GTK+, im not fully aware of all its functionality. Basically, I have a GtkTreeView widget that has 4 Columns. I need to update the text displayed in the 4 columns every couple of seconds, but im not aware how to do this in GTK+. I'm aware that I could flush the data using gtk_tree_store_cl...
You need to get a GtkTreeIter to the proper row, then use the appropriate (model-specific) setter to change the data. For instance gtk_list_store_set() for the GtkListStore model. There is no need to clear the entire model if you just want to change some of the data, that is very wasteful and slow. If you really need t...
2,623,165
2,623,552
CreateFileMapping MapViewOfFile
With win32api, I want that the following program creates two process and creates a filemap. (using c++) i don't know what i should write at Handle CreateFileMapping(.... I've tried it with: PROCCESS_INFORMATION hfile. Furthermore the first parameter should be INVALID_HANDLE_VALUE, but then i don't know what to write i...
MapViewOfFile takes the handle returned by CreateFileMapping: HANDLE hFileMapping = CreateFileMapping(...); LPVOID lpBaseAddress = MapViewOfFile(hFileMapping, ...);
2,623,277
2,664,601
What can I access in Androids Native libraries? And How?
I am completely new to the NDK. I have done a couple of the tutorials including the hello from jni one and another one that calculates the sum of two numbers. They involved using cygwin and the ndk to create the library so file and I have a bit of a grasp on how to insert my own libraries into the libraries layer of An...
As others pointed out on the android-ndk group, you probably should just use the SDK. The NDK doesn't give you access to any features beyond those available with the SDK and it reduces the portability of your application. You should only consider it if you have legacy code written C or C++ (that doesn't use exception...
2,623,396
2,626,913
Boost Thread Specific Storage Question (boost/thread/tss.hpp)
The boost threading library has an abstraction for thread specific (local) storage. I have skimmed over the source code and it seems that the TSS functionality can be used in an application with any existing thread regardless of weather it was created from boost::thread --i.e., this implies that certain callbacks are r...
You're right. You can use it for threads not created by boost::thread. If you look in test_tss.cpp you can see they test exactly that, and it should work with both POSIX and Windows threads.
2,623,566
2,623,693
How much effort do you have to put in to get gains from using SSE?
Case One Say you have a little class: class Point3D { private: float x,y,z; public: operator+=() ...etc }; Point3D &Point3D::operator+=(Point3D &other) { this->x += other.x; this->y += other.y; this->z += other.z; } A naive use of SSE would simply replace these function bodies with using a few intrinsi...
In general you will need to take additional steps to get the best out of SSE (or any other SIMD architecture): data needs to be 16 byte aligned (ideally) data needs to be contiguous you need enough data to make the SIMD operation worthwhile you need to coalesce as many operations as you can to mitigate the costs of lo...
2,623,843
2,656,556
Make process crash on large memory allocation
I'm trying to find a significant memory leak (15MB at a time, but doing allocations like this on multiple places). I checked the most obvious places, and then used AQTime, but I still can't pinpoint it. Now I see 2 options left: 1) Use SetProcessWorkingSetSize: I've tried this but my process happily keeps on running wh...
Sorry all, none of the proposed solutions worked. It finally got fixed using AQTime and a lot of debugoutput. The leak got cleaned on shutdown, so it was looking for a needle in a haystack. Still I'm interested in how to efficiently find this though. I tried to put a conditional breakpoint on the new operator, but the ...
2,623,881
2,624,020
Special Characters on Console
I've finished my poker game but now I want to make it look a bit better with displaying Spades, Hearts, Diamonds and Clubs. I tried this answer: C++: Printing ASCII Heart and Diamonds With Platform Independent Maybe stupid but I try: cout << 'U+2662' << endl; I don't know how to write it.
To output a UTF-8 character, you need to encode it as hex bytes. I'll steal this link to fileinfo.com from an answer to the question you linked - if you jump to the UTF-8 representation, it says 0xE2 0x99 0xA5 and you can convert that to "\xE2\x99\xA5" as a string. However I can't guarantee that your console will displ...
2,623,927
2,624,613
ERROR_MORE_DATA ---- Reading from Registry
I am trying to create an offline registry in memory using the offreg.dll provided in the windows ddk 7 package. You can find out more information on the offreg.dll here: MSDN Currently, while attempting to read a value from an open registry hive / key I receive the following error: 234 or ERROR_MORE_DATA Here is the .h...
The attribute on the pcbData argument is wrong, it is ref, not out. You need to initialize it to the Capacity of the StringBuilder you pass for the pvData argument. Right now the API function probably sees a 0 so will return the error code. It ought to look something like this: [DllImport("offreg.dll", CharSet = Char...
2,624,022
2,624,036
What is the different purpose of .H header file and a IDL file?
I am studying COM so there're some basic questions puzzling me... I know that IDL file is used to describe the method definitions (or the so called 'contract' between software modules), and the .H header files contains something like a method prototype, which looks similar to what the IDL is meant for. So, why are the...
Interface description language (IDL) is a small language in itself which provides a programming language independent way to describe an interface. Tools generate .h files from your .idl. If you only had a .h file it would be impossible to tie into it with another programming language. .h files are very specific to ...
2,624,232
2,624,242
How to change a particular element of a C++ STL vector
vector<int> l; for(int i=1;i<=10;i++){ l.push_back(i); } Now, for example, how do I change the 5th element of the vector to -1? I tried l.assign(4, -1); It is not behaving as expected. None of the other vector methods seem to fit. I have used vector as I need random access functionality in my code (using l.at(i)).
at and operator[] both return a reference to the indexed element, so you can simply use: l.at(4) = -1; or l[4] = -1;
2,624,238
2,624,474
c++ undefined references with static library
I'm trying to make a static library from a class but when trying to use it, I always get errors with undefined references on anything. The way I proceeded was creating the object file like g++ -c myClass.cpp -o myClass.o and then packing it with ar rcs myClass.lib myClass.o There is something I'm obviously missing ...
This is probably a link order problem. When the GNU linker sees a library, it discards all symbols that it doesn't need. In this case, your library appears before your .cpp file, so the library is being discarded before the .cpp file is compiled. Do this: g++ -o main.exe main.cpp -L. -lmylib or g++ -o main.exe main...
2,624,257
2,624,279
Percentage calculation around 0.5 (0.4 = -20% and 0.6 = +20%)
I'm in a strange situation where I have a value of 0.5 and I want to convert the values from 0.5 to 1 to be a percentage and from 0.5 to 0 to be a negative percentage. As it says in the title 0.4 should be -20%, 0.3 should be -40% and 0.1 should be -80%. I'm sure this is a simple problem, but my mind is just refusing t...
What we want to do is to scale the range (0; 1) to (-100; 100): percentage = (value - 0.5) * 200; The subtraction transforms the value so that it's in the range (-0.5; 0.5), and the multiplication scales it to the range of (-100; 100).
2,624,387
2,624,411
Fastest possible algorithm to sum numbers up to N
I want a really fast algorithm or code in C to do the following task: sum all numbers from 1 to N for any given integer N, without assuming N is positive. I made a loop summing from 1 to N, but it is too slow.
If N is positive: int sum = N*(N+1)/2; If N is negative: int tempN = -N; int sum = 1 + tempN*(tempN+1)/2 * (-1);.
2,624,442
2,624,466
Coordinating typedefs and structs in std::multiset (C++)
I'm not a professional programmer, so please don't hesitate to state the obvious. My goal is to use a std::multiset container (typedef EventMultiSet) called currentEvents to organize a list of structs, of type Event, and to have members of class Host occasionally add new Event structs to currentEvents. The structs are ...
The compiler errors are simply because your typedef is in the wrong place - only main.cpp knows about it. It looks like you probably want it in Event.h, which both of the others include. I'm not sure exactly what you're asking - but possibly you want to pass by reference not by pointer? I don't see anything wrong with...
2,624,556
2,624,660
Why does the compiler allow a function to return a value that is stored as a reference
Can anybody explain why this code does not generate a compiler error? class Foo { public: int _x; }; Foo getFoo() { Foo myfoo; myfoo._x = 10; return myfoo; } int _tmain() { // shouldn't this line of code be a compiler error? Foo& badfoo = getFoo(); return 0; }
You are probably using VC++ which allows this as an extension. main.cpp:18: warning C4239: nonstandard extension used : 'initializing' : conversion from 'Foo' to 'Foo &'
2,624,628
2,624,947
In a class with no virtual methods or superclass, is it safe to assume (address of first member variable) == this?
I made a private API that assumes that the address of the first member-object in the class will be the same as the class's this-pointer... that way the member-object can trivially derive a pointer to the object that it is a member of, without having to store a pointer explicitly. Given that I am willing to make sure th...
It seems the current standard guarantees this only for POD types. 9.2.17 A pointer to a POD-struct object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [Note: There might therefore be unnamed padding within a POD-s...
2,624,667
2,624,672
What's a very easy C++ profiler (VC++)?
I've used a few profilers in the past and never found them particularly easy. Maybe I picked bad ones, maybe I didn't really know what I was expecting! But I'd like to know if there are any 'standard' profilers which simply drop in and work? I don't believe I need massively fine-detailed reports, just to pick up major ...
VS built in: If you have team edition you can use the Visual Studio profiler. Other options: Otherwise check this thread. Creating your own easily: I personally use an internally built one based on the Win32 API QueryPerformanceCounter. You can make something nice and easy to use within a hundred lines of code or les...
2,624,693
2,624,739
Why is this undefined behavior when I always get the same result?
I recently came across a question about sequence points in C++ at this site, about what this code will output: int c=0; cout << c++ << c; It was answered that the output is undefined and << is not a sequence point, but still I want to know why is it undefined when, even if I compile it 25 times, it still always print...
"Undefined" means that the standard doesn't specify what has to happen in that situation, so anything your compiler does is, by definition, right. If it always prints 01, that's fine. If it prints a different number every time you run, that would be fine too. If it causes monkeys to fly out of your nose (as illustrated...
2,624,880
2,632,886
Static Class Variables in Dynamic Library and Main Program
I am working on a project that has a class 'A' that contains a static stl container class. This class is included in both my main program and a .so file. The class uses the default(implicit, not declared) constructor/destructor. The main program loads the .so file using dlopen() and in its destructor, calls dlclose(...
This question has been resolved in another question I posted. Basically there were indeed two copies of the static variable -- one in the main program and one in the shared library, but the runtime linker was resolving both copies to the main programs copy. See this question for more information: Main Program and Sha...
2,625,304
2,626,249
C++ using cdb_read returns extra characters on some reads
I am using the following function to loop through a couple of open CDB hash tables. Sometimes the value for a given key is returned along with an additional character (specifically a CTRL-P (a DLE character/0x16/0o020)). I have checked the cdb key/value pairs with a couple of different utilities and none of them show ...
First, I am not familiar with CDB and I don't believe you include enough details about your software environment here. But assuming it is like other database libraries I've used... The values probably don't have to be NUL-terminated. That means that casting to char* and printing it will not work. You should add a 0 byt...
2,625,378
2,625,428
gcc compilation without using system defined header locations
I am attempting to compile a c++ class using gcc. Due to the nature of the build, I need to invoke gcc from a non-standard location and include non-system defined headers, only to add a set from a different location. However, when I do this, I run into an issue where I cannot find some base symbols (suprise suprise). S...
Perhaps the --sysroot arg would help, see gcc docs.
2,625,411
2,626,894
How to build a sentence parser using only the c++ standared library?
I am designing a text based game similar to Zork, and I would like it to able to parse a sentance and draw out keywords such TAKE, DROP ect. The thing is, I would like to do this all through the standard c++ library... I have heard of external libraries (such as flex/bison) that effectively accomplish this; however I d...
For a naive implementation using std::string, the std::set container and this tokenization function (Alavoor Vasudevan) you can do this : #include <iostream> #include <set> #include <string> int main() { /*You match the substring find in the while loop (tokenization) to the ones contained in the dic(tionnary) set....
2,625,418
2,626,362
What is the reciprocal of CComboBox.GetItemData?
Instead of associating objects with Combo Box items, I associate long ids representing choices. They come from a database, so it seems natural to do so anyway. Now, I persist the id and not the index of the user's selection, so that the choice is remembered across sessions. If id no longer exists in database - no big d...
You have a function that maps item index to database ID. There is no built-in inverse for that function because the general case doesn't have an inverse. A single data value might map to many different items in the list control; the OS doesn't know your data values are unique. Your technique of searching the control it...
2,625,869
2,625,881
Why is a pointer to pointer needed to allocate memory in this function?
I have a segmentation fault in the code below, but after I changed it to pointer to pointer, it is fine. What is the reason? void memory(int * p, int size) { try { p = (int *) malloc(size*sizeof(int)); } catch(exception& e) { cout << e.what() << endl; } } It does not work in the main functi...
Because you're wanting to get a pointer value back from the operations done in the function. malloc allocates memory and gives you an address for that memory. In your first example, you store that address in the local argument variable p, but since it's just the argument, that doesn't make it back to the main program, ...
2,626,027
2,626,119
What color to use in owner-draw Windows List Control background?
I have an owner-drawn list control in my Windows program. I use CListCtrl::GetBkColor to get the background color, and for a selected item I use GetSysColor(COLOR_HIGHLIGHT). This matches what Windows uses for non owner drawn list controls, except for the case where the control doesn't have focus - then the background ...
COLOR_INACTIVECAPTION (3), I think. Update: Nope, it looks like it's just COLOR_BTNFACE (15).
2,626,150
2,626,174
set static member pointer variables
I'm trying to set a static pointer variable in a class but I'm getting these errors for each variable I try to set. error C4430: missing type specifier - int assumed. Note: C++ does not support default-int error C2040: 'xscroll' : 'int' differs in levels of indirection from 'float *' error C2440: 'initializing' : canno...
I think you're mixing up initialization with assignment. All class static variables have to be defined once, from global scope (i.e. the definition is outside any class or function, can be in a namespace however) and can be initialized at that time. This definition looks just like the definition of any global variabl...
2,626,230
2,632,271
Running multiprocess applications from MATLAB
I've written a multitprocess application in VC++ and tried to execute it with command line arguments with the system command from MATLAB. It runs, but only on one core --- any suggestions? Update:In fact, it doesn't even see the second core. I used OpenMP and used omp_get_max_threads() and omp_get_thread_num() to check...
The question is how Matlab is affecting your app's behavior, since it's a separate process. I suspect Matlab is modifying environment variables in a manner that affects OMP, maybe because it uses OMP internally, and the process you are spawning from Matlab is inheriting this modified environment. Do a "set > plain.txt"...
2,626,653
2,626,749
Is there a safe / standard way to manage unstructured memory in C++?
I'm building a toy VM that requires a block of memory for storing and accessing data elements of different types and of different sizes. I've done this by writing a wrapper class around a uint8_t* data block of the needed size. That class has some template methods to write / read typed data elements to / from arbitra...
Hmm, since you are in C++, it sounds like you are looking for STL allocator and/or placement new.
2,626,748
2,638,838
WinForm-style Invoke() in unmanaged C++
I've been playing with a DataBus-type design for a hobby project, and I ran into an issue. Back-end components need to notify the UI that something has happened. My implementation of the bus delivers the messages synchronously with respect to the sender. In other words, when you call Send(), the method blocks until all...
I have been out of the Win32 game for a long time now, but the way we used to achieve this was by using PostMessage to post a windows message back to the UI thread and then handle the call from there, passing the additional info you need in wParam/lParam. In fact I wouldn't be surprised if that is how .NET handles this...
2,626,808
2,626,822
Referencing a union inside a structure using union tag gives incorrect address
I had a need to declare a union inside a structure as defined below: struct MyStruct { int m_DataType; DWORD m_DataLen; union theData { char m_Buff [_MAX_PATH]; struct MyData m_myData; } m_Data; }; Initially, I tried accessing the union data as follows (before I added the m_D...
You should be writing: char *pBuff = m_myStruct.m_Data.m_Buff; I wish I knew how it was compiling as written.
2,626,885
2,626,901
understanding a Build c++
I think I know what a build is. But I am not sure. My definition of a build is another word for saying compiled application. Can someone please tell me what exactly a build is. And why do people ask for 3 types of builds. Such as Debug Build, Profile Build and a Release Build. What are the differences. [edit] the type...
Have a look at Visual Studio Debug and Release Modes Release Mode When an assembly is built in release mode, the compiler performs all available optimisations to ensure that the outputted executables and libraries execute as efficiently as possible. This mode should be used for completed and tested software that is to ...
2,626,903
2,626,921
Creating a good directory structure
This might be a silly question but I am still learning. I have read several books on creating application and creating a good directory structure. When people talk about creating a directory structure, do they mean the folders you make within the solution explorer (folders you actually find inside of a .sln file) or do...
Visual Studio has a strange way of dealing with "folders" in solutions. A "Solution Folder" is not actually a physical folder, but more of a virtual folder managed by Visual Studio. Your files may end up in the root directoy, but VS will treat them as if they are in a "folder." This is configured and managed in the ...
2,627,013
2,627,211
how to call a dll file in c. I want to transmit a xml file to it
I found many ways, but they are too easy, they always get a return-value from the dll file. dll file: a file with the sufix ".dll"
It's just like any other WINAPI // assuming you are using windows LPCTSTR lpszXml = _T("<xml> </xml>"); TCHAR szResult[1000] = _T(""); HMODULE hModule = LoadLibrary(_T("mylibrary.dll")); int (*DoWorkFunc)(LPCTSTR lpszXmlData, LPTSTR lpszResult, int cchMaxSize); *(FARPROC*)&DoWorkFunc = GetProcAddress(hModule, _T("DoWo...
2,627,114
3,193,724
C++ modularization framework (like OSGi) ?
I found one SOF http://www.codeproject.com/KB/library/SOF_.aspx , Are there anyother stable frameworks for modularization in C++ ?
The OSGi4Cpp tries to implement the OSGi specification in C++.
2,627,134
2,627,156
Passing enums to functions in C++
I have a header file with all the enums listed (#ifndef #define #endif construct has been used to avoid multiple inclusion of the file) that I use in multiple cpp files in my application.One of the enums in the files is enum StatusSubsystem {ENABLED,INCORRECT_FRAME,INVALID_DATA,DISABLED}; There are functions in the a...
You should take the enum by value, rather than by const reference. It's small enough to fit into an int, so there is no performance penalty or anything like it. But, from what you're describing, it sounds like somebody has #defined INCORRECT_FRAME to 0 elsewhere. You should put something like the following in the line ...
2,627,166
2,627,179
What is the difference between a const reference and normal parameter?
void DoWork(int n); void DoWork(const int &n); What's the difference?
The difference is more prominent when you are passing a big struct/class: struct MyData { int a,b,c,d,e,f,g,h; long array[1234]; }; void DoWork(MyData md); void DoWork(const MyData& md); When you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. If...
2,627,192
2,627,207
C++ vector<T>::iterator operator +
Im holding an iterator that points to an element of a vector, and I would like to compare it to the next element of the vector. Here is what I have Class Point{ public: float x,y; } //Somewhere in my code I do this vector<Point> points = line.getPoints(); foo (points.begin(),points.end()); where foo is: void foo (...
current + 1 is valid for random access iterators (which include vector iterators), and it is the iterator after current (i.e., what you think it does). Check (or post!) your comparison code, you're probably doing something wrong in there.
2,627,223
2,627,252
C++ Template Class Constructor with Variable Arguments
Is it possible to create a template function that takes a variable number of arguments, for example, in this Vector< T, C > class constructor: template < typename T, uint C > Vector< T, C >::Vector( T, ... ) { va_list arg_list; va_start( arg_list, C ); for( uint i = 0; i < C; i++ ) { m_data[ i ] = v...
This code looks dangerous and I think your analysis on why it isn't working is spot on, there's no way for the compiler to know that when calling: Vector< double, 3 >( 1, 1, 1 ) the ones should be passed as doubles. I would change the constructor to something like: Vector< T, C >::Vector(const T(&data)[C]) instead, a...
2,627,351
2,627,484
Can I use dll in Turbo C++ program and do we have any dll for lzw compression and decompression
I was trying to create a lzw compression program. But i need to finish it by today itself so i want to use some dll for taking my input as txt file and output to as a text file. I want to do this in TURBO C++ code which are doing my remaining functionalities. Can anyone suggest me some method.
Libzip isn't LZW (it uses an algorithm that's generally better), but it is probably the best standard answer. I don't know if there's a downloadable DLL for it in a standard location, so you might have to compile it from source. Alternatively, a bit of Google-searching (on "lzw compression dll") found this C++ source ...
2,627,416
2,627,430
Are Multiple singleton instances possible in a shared DLL?
I am going to develop a DLL for an MFC Application, and suppose I have a singleton class in this DLL with some synchronization mechanism. And this DLL is used by other processes, namely EXEs. The question is: is this singleton created only once for all sharing processes or every process has its own singleton? And How c...
I suppose you are talking about Windows. In that case every process has its own singleton. You could place it in shared memory and use named synchronization primitives to share singleton between processes.
2,627,540
2,627,562
Why is the destructor of the class called twice?
Apologies if the question sounds silly, I was following experts in SO and trying some examples myself, and this is one of them. I did try the search option but didn't find an answer for this kind. class A { public: A(){cout<<"A Contruction"<<endl;} ~A(){cout<<"A destruction"<<endl;} }; int main() ...
To add the element a copy constructor is invoked on a temporary object. After the push_back() the temporary object is destroyed - that't the first destructor call. Then vector instance goes out of scope and destroys all the elements stored - that's the second destructor call.
2,627,900
2,627,969
What can explain std::cout not to display anything?
For whatever reason, std::cout does not display anything with my application. The description of my development environment follows. I am working on a Qt application using Qt Creator. Since Qt Creator can't be launched from my station (XP64), i am currently developping it with Visual Studio 2008 and the Qt plugin (by i...
Ok, answer found. Simple answer, of course, as always when encountering such problems. Michael Aaron was on the right tracks. Simply changing SubSystem to Console in project configuration (/Configuration properties/Linker/System) makes the whole thing work. The GUI still works, but with a background console. I can deal...
2,628,018
2,628,044
Using an array in embedded x86 assembly?
I have a method (C++) that returns a character and takes an array of characters as its parameters. I'm messing with assembly for the first time and just trying to return the first character of the array in the dl register. Here's what I have so far: char returnFirstChar(char arrayOfLetters[]) { char max; __asm { ...
The line of assembly: mov eax, arrayOfLetters[0] is moving a pointer to the array of characters into eax (note, that's not what arrayOfLetters[0] would do in C, but assembly isn't C). You'll need to add the following right after it to make your little bit of assembly work: mov al, [eax]
2,628,135
2,628,160
Polymorphic functions with parameters from a class hierarchy
Let's say I have the following class hierarchy in C++: class Base; class Derived1 : public Base; class Derived2 : public Base; class ParamType; class DerivedParamType1 : public ParamType; class DerivedParamType2 : public ParamType; And I want a polymorphic function, func(ParamType), defined in Base to take a parame...
You cannot have Base::func take different parameters depending on what class inherits it. You will need to change something. You could make them both take a ParamType and handle an unexpected parameter with whatever mechanism you like (e.g. throw an exception or return an error code instead of void): struct ParamType;...
2,628,143
2,631,448
facebook api over rest getting Incorrect signature <error_code> 104
im trying to send rest api Users.getLoggedInUser i have all the secret session and all the Authenticationi made according to this site : http://wiki.developers.facebook.com/index.php/Authorization_and_Authentication_for_Desktop_Applications here is my code (cpp QT but it can be any thing else ) : QString toAPISignatu...
The big problem is that you need to convert the hashedApiData QByteArray to Hex: QString APIMD5Signature(hashedApiData.toHex()); That may do it for you, but you can still cause problems converting back and forth to strings, which you really don't need to do. Here's how I handle creating the sig and doing the post to ...
2,628,164
2,628,228
Do console apps run faster than GUI apps?
I am relatively new to world of programming. I have a few performance questions: Do console apps run faster than apps with a graphical user interface? Are languages like C and Pascal faster than object oriented languages like C++ and Delphi? I know language speed depends more on compiler than on language itself, but d...
do console apps run faster than windows based app Short answer: No Long answer: In a console based application, there is no GUI thread that needs to repaint the windows and accept user input, so in that sense, a console application may be slightly faster (since it has one fewer thread stealing away CPU cycles). Howev...
2,628,180
2,628,250
Dynamically allocated structure and casting
Let's say I have a first structure like this: typedef struct { int ivalue; char cvalue; } Foo; And a second one: typedef struct { int ivalue; char cvalue; unsigned char some_data_block[0xFF]; } Bar; Now let's say I do the following: Foo *pfoo; Bar *pbar; pbar = new Bar; pfoo = (Foo *)pbar; de...
The whole idea of such code is just undefined behavior. Don't do it. What happens if someone overloads operator new and operator delete for one struct and not for the other? The only legal way to do what you want is to inherit both structs from the comon base with a virtual destructors - then you will have proper defin...
2,628,345
2,628,443
Will a call to std::vector::clear() set std::vector::capacity() to zero?
If I use .reserve(items) on a vector, the vector will allocate enough memory for my guess of the number of items that I'll need. If I later on use .clear(), will that just clear the vector or save my earlier defined reserve? thanks.
It is specified that std::vector<T>::clear() affects the size. It might not affect the capacity. For resetting the capacity, use the swap trick: std::vector<int> v1; // somehow increase capacity std::vector<int>().swap(v1); Note: Since this old answer is still getting upvotes (thus people read it), I fe...
2,628,459
2,628,484
something about C++ unnamed namespace
#include <iostream> namespace { int a=1; } int a=2,b=3; int main(void) { std::cout<<::a<<::b; return 0; } I complie it with my g++,but the output is 23, who can explain it? is that a way to get access to the <unnamed> namespace ::a?
:: in ::a refers to the global namespace. Anonymous namespace should be accessed via just a (or to be more specific, you shouldn't do like this at all)
2,628,677
2,628,706
What does: throw 0 do/mean? Is it "bad"?
Context I came across some code, like this: if( Some_Condition ) throw 0; I googled a bit, and found a few other code snippets using that odd looking throw 0 form. I presume one would catch this as: catch(const int& e) { } Or is this a NULL ptr? to be caught as void* ? Question What does this throw 0 do? Is it spe...
Generally throw can throw any type, any you need to catch it with this type or its base type. So technically it is legal code but... it is bad code: You should always derive your exceptions from std::exception or at least from some class that provides some useful information about error rather then plain number. But de...
2,628,712
2,636,635
Counting texels using a fragment shader
I have two textures generated using a fragment shader. I want to be able to count the number of texels in each texture that are above some colour intensity. How can this be done? My initial thought is to count these texels using the fragment shader before generating the texture. However, this would require some sort of...
Thanks for the ideas, I found a simple way I think is the most efficient. I initially thought occlusion queries could only be used with geometry but they can also be used with textures. Turn on occlusion queries Render the image using a fragment shader and discard texels below required color intensity Retrieve number ...
2,628,714
2,628,794
get const or non-const reference type from trait
I am writing a functor F which takes function of type void (*func)(T) and func's argument arg. template<typename T> void F(void (*func)(T), WhatTypeHere? arg) { func(arg); } Then functor F calls func with arg. I would like F not to copy arg, just to pass it as reference. But then I cannot simply write "void F(void...
template<class T> struct forwarding { typedef T const& type; }; template<class T> struct forwarding<T&> { typedef T& type; }; template<typename T> void F(void (*func)(T), typename forwarding<T>::type arg) { func(arg); } void a(int x) { std::cout << x << std::endl; } int main() { F(&a, 7); } Your mapping was clos...
2,629,346
2,629,369
C++ template and pointers
I have a problem with a template and pointers ( I think ). Below is the part of my code: /* ItemCollection.h */ #ifndef ITEMCOLLECTION_H #define ITEMCOLLECTION_H #include <cstddef> using namespace std; template <class T> class ItemCollection { public: // constructor //destructor void ...
template <class T> typename ItemCollection <T>::Item* ItemCollection<T>::insert( T p, Item* ptr) { // function body }
2,629,674
2,629,735
Are there any pitfalls when calling functions from a C library in a C++ program?
I'm using a library which has both a C interface and a C++ interface in my C++ program. The C++ one is a bit immature and I must stick with the C one. I was wondering, in more general terms, is there anything specific to keep in mind when mixing C-style binary object files with a C++ project?
For C functions to be called from C++, they have to be declared as extern "C". Usually something like this is used in headers: #if defined(__cplusplus) extern "C" { #endif void f(); void g(); #if defined(__cplusplus) } #endif
2,630,024
2,630,397
why BOOST_FOREACH cannot handle const boost::ptr_map?
void main() { typedef boost::ptr_map<int, char> MyMap; //typedef std::map<int, char *> MyMap; // in contrast with std type it works MyMap mymap; mymap[1] = new char('a'); mymap[2] = new char('b'); mymap[3] = new char('c'); BOOST_FOREACH(MyMap::value_type value, mymap) { std::cout << value.firs...
Based on this answer, it looks like you're right. But there's a workaround. Change your second loop to this: BOOST_FOREACH(MyMap::const_iterator::value_type value, const_mymap) { std::cout << value.first << " " << value.second << std::endl; }
2,630,054
2,630,091
Does C++ limit recursion depth?
In Python there is a maximum recursion depth. Seems it is because Python is interpreted rather than compiled. Does C++ have the same concept? Or it is connected only with RAM limit?
The limit in C++ is due to the maximum size of the stack. That's typically less than the size of RAM by quite a few orders of magnitude, but is still pretty large. (Luckily, large things like string contents are typically held not on the stack itself.) The stack limit is typically tunable at the OS level. (See the docs...
2,630,163
2,630,232
How to restrict the range of elements of C++ STL vector?
vector<int> l; for(int i=0;i<10;i++){ l.push_back(i); } I want the vector to only be able to store numbers from a specified range (or set). How can that be done, in general? In particular, I want to restrict the vector to beonly be able to store single digits. So, if I do a l[9]++ (in this case l[9] is 9), it s...
An alternative solution would be to create your own datatype that provides this restrictions. As i read your question I think the restrictions do not really belong to the container itself but to the datatype you want to store. An example (start of) such an implementation can be as follows, possibly such a datatype is a...
2,630,258
2,630,733
texture on cube-side with opengl
hello i want to use a texture on a cube (created by glutsolidcube()), how can i define where the texture is pictured at? (for example on the "frontside" of a cube) glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterMode); glTexParam...
Not possible, since glutSolidCube() only generates vertexes and normals, not texture coordinates. However, there are workarounds.
2,630,406
2,630,684
Will unused destructor be optimized out?
Assuming MyClass uses the default destructor (or no destructor), and this code: MyClass *buffer = new MyClass[i]; // Construct N objects using placement new for(size_t i = 0; i < N; i++){ buffer[i].~MyClass(); } delete[] buffer; Is there any optimizer that would be able to remove this loop? Also, is there any way ...
There are a few things wrong with this code. Firstly, you don't need to be calling the destructor. MyClass buffer* = new MyClass[i]; delete[] buffer; does that just fine. (Note, not the array syntax.) That said, you comment leads me to believe you meant something else, like: // vector, because raw memory allocation is ...
2,630,529
2,630,830
JNI how to access Java Object (Integer)
I have a JNI method to access java method which returns an Integer object. I do not want to return the primitive int type because this code will be modified to handle Generic objects. The following is what I have. I am not able to get the value of the Integer that I pass. The output at C++ side is something like value...
You have to invoke the intValue method on the Integer instance to get its primitive value. Use FindClass instead of GetObjectClass (as in your code) to get a reference to the class java.lang.Integer and then GetMethodID and CallObjectMethod to actually invoke the intValue method.
2,630,695
2,630,918
Dynamic linking in Visual Studio
I have to link dynamically with OpenSSL libeay32.dll. I'm writing native c++ console application using Visual C++ Express 2008. I'm including a header evp.h from OpenSSL distribution. Building and...: error LNK2001: unresolved external symbol _EVP_aes_256_cbc error LNK2001: unresolved external symbol _EVP_DecryptInit ...
In the project properties, configuration properties, linker, input - add the library name under "additional dependencies". [Note, this will actually STATICALLY link with the library. If you truly want to load the library dynamically you will need to call LoadLibrary() on the DLL and then get function pointers for the f...
2,630,806
2,630,873
Maddening Linked List problem
This has been plaguing me for weeks. It's something really simple, I know it. Every time I print a singly linked list, it prints an address at the end of the list. #include <iostream> using namespace std; struct node { int info; node *link; }; node *before(node *head); node *after(node *head); void middle(node *h...
There are two problems here: In your initial loop which creates the list, you don't set the info of the last node. This is what causes the random-looking value to be displayed at the end. This is the relevant code: for(int c1=1;c1<11;c1++) { newnode->info = c1; ptr = newnode; newnode = new node; ptr->link = ne...
2,631,006
2,631,508
How do I render 3d model into directshow virtual camera output
I want to provide a virtual webcam via DirectShow that will use the video feed from an existing camera running some tracking software against it to find the users face and then overlay a 3d model oriented just that it appears to move the users face. I am using a third party api to do the face tracking and thats workin...
you can overlay your graphics by using a VMR filter -- a video renderer with multiple input pins. The VMR-9 filter is based on Direct3D, so you can use Direct3D rendering for your model and feed the output to a secondary pin on the VMR, to be overlaid or alpha-blended with the camera output which is fed to the primary ...
2,631,128
2,631,143
C++ inherited class has member of same name
In C++ you can put a member in a base class and a member with the same name in the inherited class. How can I access a specific one in the inherited class?
In that case you should fully qualify a member name. class A { public: int x; }; class B : public A { public: int x; B() { x = 0; A::x = 1; } };
2,631,452
3,244,399
64bit exceptions in WndProc silently fail
The following code will give a hard fail when run under Windows 7 32bit: void CTestView::OnDraw(CDC* /*pDC*/) { *(int*)0 = 0; // Crash CTestDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; // TODO: add draw code for native data here } However, if I try this on Windows 7 6...
OK, I've received a reply from Microsoft: Hello, Thanks for the report. I've found out that this is a Windows issue, and there is a hot fix available. Please see http://support.microsoft.com/kb/976038 for a fix that you can install if you wish. @Skute: note that the Program Compatibility Assistant will a...
2,631,489
2,640,156
Qt moc failure without an error message
So I'm pretty new to Qt, and I've just inherited a project from someone else who is also new to Qt. He isn't around this week btw. We are using Visual Studio 2008, and have the latest version of Qt installed(4.6.2). The project builds on my coworker's machine fine, and I can get the project from svn and build it dire...
I finally found the answer. my coworker was back in the office today, and I used the build log off his machine to get his full moc command(about 4 lines long). Our moc commands were basically the same except at the very end. His command ended in: -o ".\GeneratedFiles\$(ConfigurationName)\moc_$(InputName).cpp" My c...
2,631,585
2,631,677
C++: How to require that one template type is derived from the other
In a comparison operator: template<class R1, class R2> bool operator==(Manager<R1> m1, Manager<R2> m2) { return m1.internal_field == m2.internal_field; } Is there any way I could enforce that R1 and R2 must have a supertype or subtype relation? That is, I'd like to allow either R1 to be derived from R2, or R2 to ...
A trait you want might look like this: template <typename B, typename D> struct is_base_of // check if B is a base of D { typedef char yes[1]; typedef char no[2]; static yes& test(B*); static no& test(...); static D* get(void); static const bool value = sizeof(test(get()) == sizeof(yes); }; ...
2,631,837
2,631,915
Compatibility between Qt and Boost sockets libraries
In my work, I'm developing a Viewer client for a Offshore simulation server, using sockets to send the simulation data from the Simulator to de Viewer. But, the server uses Boost.asio as it's sockets library. As the client uses Qt for it's GUI, I was wondering if there is any problem in using de Qt Networking library f...
There shouldn't be any "compatibility" problem. You only have to implement the communication protocol agreed with the server side correctly.
2,631,904
2,632,026
How to create a bold and italic label in MFC?
Please do not mark it as a dupe of this question just yet: Bold labels in MFC That question does not help me; for some reason I do not see the rich edit control. Instead I believe I have to do it in code. here is a sample I found: http://www.tech-archive.net/Archive/VC/microsoft.public.vc.mfc/2006-10/msg00245.html My p...
You will want to do the following before the static text control is shown on the parent window. Get a handle to the window: CWnd * pwnd = GetDlgItem(IDC_LABEL); Get the current font for the static text: CFont * pfont = pwnd->GetFont(); Get the characteristics of the font: LOGFONT lf; pfont->GetLogFont(&lf); Change the...
2,631,907
2,632,180
GraphViz: which graph library to use?
I've just started developing a small C++ program using GraphViz's graph library and noticed there are actually three different API's: libgraph, libcgraph and libagraph. WTF? I would like to know what is the difference between them, which one to use and where to look for API documentation. I have looked at the GraphViz ...
Looks like one should use libcgraph, compiling with the flags given by pkg-config libcgraph --cflags --libs and including #include <cgraph.h>.