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,786,946
2,786,963
C++ invoke explicit template constructor
Can you tell me how to invoke template constructor explicitly (in initializer list)? for example: struct T { template<class> T(); }; struct U { U() : t<void>() {} //does not work T t; }; thanks
It's not possible. The Standard also has a note on this at 14.8.1/7 [Note: because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an e...
2,786,995
2,787,059
Is it compulsory to learn about Data Structures if you want to be a Java/C++ programmer?
So do I really need to learn about them ? Isn't there an interesting way to learn about stacks, linked lists, heaps, etc ? I found it a boring subject. **While posting this question it showed some warning. Am I not allowed to post such a question ? Admins please clarify and I will delete it :/ Warning :: The question y...
It's compulsory to learn about data structures if you want to be a programmer. Data structures are your bread-and-butter - if you don't understand things like the behavior, uses, and run-time complexity ('big-O') of at least the basic structures (arrays, linked lists, stacks, queues, trees (binary / n-ary, self-balanci...
2,787,002
2,787,164
Is there kind of runtime C++ assembler library around?
For my small hobby project I need to emit machine code from C++ program in runtime. I have base address 0xDEADBEEF and want to write something like this: Assembler a((void*)0xDEADBEEF); a.Emit() << Push(Reg::Eax) << Push(Reg::Ebx) << Jmp(0xFEFEFEFE); Inline assembler isn't my choice because generated machine co...
You could use Nicolas Capen's softwire. Its really not supported any more as he now works on a similar product at Transgaming called SoftAsm. Still it kinda does what you want. Edit June 2014: - It appears the sourceforge link above has been removed but it appears to be available under an LGPL license here.
2,787,156
2,787,292
std::map operator[] and automatically created new objects
I'm a little bit scared about something like this: std::map<DWORD, DWORD> tmap; tmap[0]+=1; tmap[0]+=1; tmap[0]+=1; Since DWORD's are not automatically initialized, I'm always afraid of tmap[0] being a random number that is incremented. How does the map know hot to initialize a DWORD if the runtime does not know...
The new object, when inserted into the map by [] operator, is value-initialized. It is ensured by the map implementation, i.e. it is done "automatically" in that sense. For objects of type DWORD (assuming it is a scalar type), value-initialization means zero-initialization. By definition given in 23.3.1.2, operator [] ...
2,787,188
2,787,646
CListView Control has limited length for column text
When I set the column text for CListView more than 271 characters, the rest of my buffer is not present. I set it through LV_COLUMN structure. Is this a known issue for MFC 4.21?
Here's yet another answer you won't like. It has nothing to do with your ancient version of MFC, it is a documented limitation for the list view control. From the SDK docs for the LVITEM structure's pszText member: If the structure receives item attributes, pszText is a pointer to a buffer that receives the item...
2,787,511
2,789,517
boost::bind and << operator in C++
I would like to bind the << stream operator: for_each(begin, end, boost::bind(&operator<<, stream, _1)); Unfortunately it does not work: Error 1 error C2780: 'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type> boost::bind(M T::* ,A1)' : expects 2 arguments - 3 provide...
Instead you might try boost.lambda: //using namespace boost::lambda; for_each(begin, end, stream << _1)); The reason of your problem is most probably: how on earth can you expect the compiler / bind to know what you are taking the address of if you say &operator<<? (I get a different error simply saying that this is n...
2,787,569
2,787,594
copy constructor with default arguments
As far as I know, the copy constructor must be of the form T(const T&) or T(T&). What if I wanted to add default arguments to the signature? T(const T&, double f = 1.0); Would that be standards compliant?
Yes. §[class.copy]/2: A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments [ Example: X::X(const X&) and X::X(X&,int=1) are copy constr...
2,787,638
2,788,531
Problem with inner classes of the same name in Visual C++
I have a problem with Visual C++ 2005, where apparently inner classes with the same name but in different outer classes are confused. The problem occurs for two layers, where each layer has a listener interface as an inner class. B is a listener of A, and has its own listener in a third layer above it (not shown). The ...
the code you posted produced the same compiler error you described on my machine. I'm not so sure myself what the problem exactly is, but I have a feeling that inherting from a pure virtual class and declaring a pure virtual class within the descendant might not be a good idea. I managed to compile a modified version, ...
2,787,717
2,787,743
Copy Constructor in C++
I have this code #include <iostream> using namespace std; class Test{ public: int a; Test(int i=0):a(i){} ~Test(){ cout << a << endl; } Test(const Test &){ cout << "copy" << endl; } void operator=(const Test &){ cout << "=" << endl; } ...
This is a special case called Return Value Optimization in which the compiler is allowed to optimize away temporaries.
2,787,756
2,787,772
Call virtual method from base class on object of derived type
class Base { public: virtual void foo() const { std::cout << "Base"; } }; class Derived : public Base { public: virtual void foo() const { std::cout << "Derived"; } }; Derived d; // call Base::foo on this object Tried casting and function pointers but I couldn't do it. Is it p...
To explicitly call the function foo() defined in Base, use: d.Base::foo();
2,788,040
2,788,066
using win32 api in linux?
I have heard of WINE but I don't like it because it's slow on the computers I have tested and almost always crashes. It also has some unpleasant looking gui. I am wondering if there is a "win32" library in c/c++ for linux that produces native linux code so that if I have my source code for windows, I can just recompile...
You're looking for Winelib.
2,788,134
2,788,168
Should I Put Critical Section While Getting Connection from OCCI Environment
I'm writing a multi-threaded application. My worker threads get connection from an environment object as follows:. //EnterCriticalSection(&cs); conn = env->createConnection(username, password, connStr); //LeaveCriticalSection(&cs); For concurrency, should the connection be created in a critical section or not? Does t...
If createConnection is thread-safe then you don't need it. If createConnection isn't thread-safe then you do need the critical section. Consult your documentation to see whether it's thread-safe or not. If it doesn't explicitly say it's thread-safe, them play it safe and wrap it in a critical section. Edit: Of cours...
2,788,185
2,788,267
POST request with QWebView
How can I issue a POST request over a QWebView instance?
I think the information below will help you: 1). Standard Qt example project, called "previewer", which comes with Qt SDK, may help you. For me, the absolute path is: C:\Qt\4.6.2\examples\webkit\previewer QWebView class, as I could test it, supports "post method", i.e. you can free open URL with POST page, and tap on ...
2,788,194
2,791,197
Count Similar iTems in Array
I need to count the similar elements in an array. For example, if i have an array, array[0,0,0,1,2,3,3].The number of 0's are 3 , no. of 1's are 1 , no. of 2's are 1 , no. of 3's are 2 in this array . I am sorry if this message has been posted before. Help is appreciated. Thanks in advance. Regards, THM P.S : Language ...
I can think of a few options: Copy the array into a std::multiset<> and then use the count() or equal_range() member functions to return the counts Create a std::map<T,unsigned>. The map key (of your array entry type T, which will be an integral type from your example) is the array entry, the value is the count. Incre...
2,788,352
2,788,381
Problems with first argument being string when overloading the + operator in C++
I have an selfmade Stringclass: //String.h String & operator = (const String &); String & operator = (char*); const String operator+ (String& s); const String operator+ (char* sA); . . //in main: String s1("hi"); String s2("hello"); str2 = str1 + "ok";//this is ok to do str2 = "ok" + str1;//but not this way //Shoul...
The + operator should not be a member function, but a free function, so that conversions can be performed on either of its operands. The easiest way to do this is to write operator += as a member and then use it to implement the free function for operator +. Something like: String operator +( const String & s1, const S...
2,788,388
2,788,535
When is #include <new> library required in C++?
According to this reference for operator new: Global dynamic storage operator functions are special in the standard library: All three versions of operator new are declared in the global namespace, not in the std namespace. The first and second versions are implicitly declared in every translation unit of a C++ progr...
Nothing in C++ prevents standard headers from including other standard headers. So if you include any standard header you might conceivably indirectly include all of them. However, this behaviour is totally implementation dependent, and if you need the features of a specific header you should always explicitly include ...
2,788,518
5,005,699
Calling activateWindow on QDialog sends window to background
I am debugging certain application written with C++/Qt4. On Linux it has problems that with certain window managers (gnome-wm/metacity), the main window (based on QDialog) is created in the background (it's not raised). I managed to re-create the scenario using PyQt4 and following code: from PyQt4.QtCore import * from ...
The problem was most probably caused by a bug in Qt. I can't reproduce the same behaviour in recent Qt versions. Originally reproduced on Fedora 13, Fedora 14 works OK.
2,788,765
2,789,206
std::make_shared as a default argument does not compile
In Visual C++ (2008 and 2010), the following code does not compile with the following error: #include <memory> void Foo( std::shared_ptr< int > test = ::std::make_shared< int >( 5 ) ) { } class P { void Foo( std::shared_ptr< int > test = ::std::make_shared< int >( 5 ) ) { } }; error C2039: 'make_s...
It looks like a bug in the compiler. Here is the minimal code required to reproduce the problem: namespace ns { template <typename T> class test { }; template <typename T> test<T> func() { return test<T>(); } } // Works: void f(ns::test<int> = ns::func<int>()) { } class test2...
2,788,945
2,789,053
algorithms that destruct and copy_construct
I am currently building my own toy vector for fun, and I was wondering if there is something like the following in the current or next standard or in Boost? template<class T> void destruct(T* begin, T* end) { while (begin != end) { begin -> ~T(); ++begin; } } template<class T> T* copy_const...
std::vector, if I'm not mistaken, applies its allocator's construct and destruct functions on individual items, so you could also use binders (like std::tr1::bind) to let std::transform and/or std::for_each do those. But for the copying loop, there also appears to be std::uninitialized_copy.
2,788,958
2,789,040
Drawing and loading a GL_DEPTH_COMPONENT texture
I'm trying to load a depthbuffer from a file and copy it to the depth buffer instead of clearing it every frame. anyway, i'm a bit new to opengl, so i just tried to load my texture like this: glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, DepthData); and i tr...
You are indeed drawing a textured quad that is not updating the color buffer and is still updating the depth buffer. However, the values you are writing are the actual depth values of the polygons, and not the values found in the texture! That's why everything ends up being z-culled. The easiest way to accomplish what ...
2,789,017
2,789,070
How to get information about a Windows executable (.exe) using C++
I have to create a software that will scan several directories and extracts information about the executables found. I need to do two things: Determine if a given file is an executable (.exe, .dll, and so on) - Checking the extension is probably not good enough. Get the information about this executable (the company n...
You can verify as much of the PE File Format as you want. If you want to, you can also check for a PE file signature. You can then use the File Version API to retrieve the company name, product name, version numbers, etc.
2,789,079
2,789,847
C++ snippet support in visual studio?
I'm writing code in native C++ (not C++/CLR). I know that there is no built-in support for C++ with regards to the snippet manager and snipper picker interfaces, however I found a utility called "snippy" which supposedly can generate C++ snippets. Here is a c++ snippet that the program generated: <?xml version="1.0" en...
Visual Assist has a snippets feature that is not quite the same as the IDE Snippets feature. It has its pros and cons, but does work in C++.
2,789,096
2,789,159
.NET consumer of ActiveX throwing TargetParameterCountException
I have a .NET (3.5 w/ Dev Studio 2008) app that hosts a visual Active X (written in C++ w/ Dev Studio 2003). Have access to all sources, but can't easily move the Active X control up to 2008. This as worked fine in the past. Made some changes to the Active X control and now, when calling one method on the Active X, I'm...
The HRESULT is DISP_E_BADPARAMCOUNT (better for googling than "0x8002000e"). Seems other people have bumped into this problem: http://www.codeguru.com/forum/showthread.php?t=96353 http://forums.devx.com/showthread.php?t=85215
2,789,315
2,794,648
good/full Boot Spirit examples using version 2 syntax
Almost all of the examples I've gone and looked at so far from: http://boost-spirit.com/repository/applications/show_contents.php use the old syntax. I've read and re-read the actual documentation at http://www.boost.org/doc/libs/1_42_0/libs/spirit/doc/html/index.html and the examples therein. I know Joel is starting...
Well, there is always the examples directory in Boost SVN: $BOOST_ROOT/libs/spirit/example containing a couple of more sophisticated things to look at. The tests directory adjacent to this contains a huge amount of small tests scrutinizing each and every technique we know of as well. In addition, Joel and I will have ...
2,789,390
2,789,413
How to determine at runtime when your C++ application has the visual studio debugger attached?
How do you determine at runtime whether the visual studio debugger is attached to your process. I've seen instructions for how to do this in .NET, but my process is a native C++ process. Support for detecting Just-in-time debugging would be nice but not a strict requirement.
The Win32 call IsDebuggerPresent() sounds like it ought to work.
2,789,481
2,789,509
Problem calling std::max
I compiled my bison-generated files in Visual Studio and got these errors: ...\position.hh(83): error C2589: '(' : illegal token on right side of '::' ...\position.hh(83): error C2059: syntax error : '::' ...\position.hh(83): error C2589: '(' : illegal token on right side of '::' ...\position.hh(83): error C2059...
You are probably including windows.h somewhere, which defines macros named max and min. You can #define NOMINMAX before including windows.h to prevent it from defining those macros, or you can prevent macro invocation by using an extra set of parentheses: column = (std::max)(1u, column + count);
2,789,545
2,789,941
Texture mapping an NGon?
I'm not sure how to go about figuring out how to map texture coordinates for a 2D NGon (N sided polygon) How can this be done? The effect I'm trying to achieve is for the texture to fit on the polygon and stretch out accordingly so the whole texture fits on it.
Remember that when rendering an ngon in OpenGL, it's just a whole bunch of triangles. Also, you're taking some shape and trying to map it to a rectangle, so you have to be extremely critical of how you wish to do this as there many different mappings going from any shape to a rectangular texture. For example, if I h...
2,789,735
2,789,777
memset on array of structures in C++
I have another memset question. It appears as if the code I am editing may have some issues (or it's not done the same way in different files) A::LRM las[9]; //A and LRM are both structures with BOOLS and INTS memset(&las, 0, sizeof(las)); typedef Sec SecArray[16]; SecArray rad_array; memset(rad_array, 0, sizeof(SecAr...
Both calls to memset are correct. Both sizeof(las) (or just sizeof las) and sizeof(SecArray) will return the size of the entire array. If you are worried about the first argument, then again, both will work. The pointer to the entire array (&las) or the pointer to the first element (rad_array in this context) will work...
2,789,852
2,789,880
Passing data structures to different threads
I have an application that will be spawning multiple threads. However, I feel there might be an issue with threads accessing data that they shouldn't be. Here is the structure of the threaded application (sorry for the crudeness): MainThread / \ / ...
I would have each thread create it's own copy of the datastructure, e.g. you pass the structure in the constructor and then explicitly create a local copy. Then you are guaranteed that the threads have distinct copies. (You say that it's passsed by reference, and that this invokes the copy constructor. I think you mean...
2,790,412
3,911,532
2-byte (UCS-2) wide strings under GCC
when porting my Visual C++ project to GCC, I found out that the wchar_t datatype is 4-byte UTF-32 by default. I could override that with a compiler option, but then the whole wcs* (wcslen, wcscmp, etc.) part of RTL is rendered unusable, since it assumes 4-byte wide strings. For now, I've reimplemented 5-6 of these func...
Reimplemented 5-6 of more common wcs* functions, #defined my implementations in.
2,790,611
2,819,123
Using custom dll in Qt Application
First, my compiler and OS: Qt Creator 1.3 Qt 4.6 (32 bit) Windows 7 Ultimate I want to learn how to create and import a dll in Qt. I've created a *.dll file using Qt Creator, called Shared1.dll which contains nothing but an empty class named Shared1. Now I'd like to use Shared1 class in another Qt project. How can I ...
Use your Pro file to include your header files and libraries.. For Header Files: INCLUDEPATH += "C:\Source\HeaderFiles" For libraries: LIBS += "C:\Source\Libraries\MyLib.lib" Include those header files while using the functions from the libraries. This works for me... Try it..
2,790,632
2,790,657
error of integer overflow
This the part of my OpenGL code, I am getting an error for : struct Ball { float x; float y; float rot; float dir; bool rmv; Ball* next; }; Ball* curBall; void addBall() { if (balls==NULL) { balls=new Ball; balls->next=NULL; curBall=balls; } else { curBal...
Try converting RAND_MAX to a float before adding to it. curBall->x=((float)rand()/( ((float)RAND_MAX) +1))*(ww-1) +1; et cetera. RAND_MAX is often equal to INT_MAX, the largest value an integer could hold, thus adding 1 to it while it's still considered an integer pushes it over the integer limit.
2,790,969
2,791,128
How to program a connection pool?
Is there a known algorithm for implementing a connection pool? If not what are the known algorithms and what are their trade-offs? What design patterns are common when designing and programming a connection pool? Are there any code examples implement a connection pool using boost.asio? Is it a good idea to use a connec...
If you are looking for a pure thread-pooling policy (may be a connection or any resource) there are two simple approaches viz:- Half Sync/Half Async Model (usually using using message queues to pass information). Leaders/Followers Model (usually using request queues to pass information). The first approach goes like ...
2,791,169
2,791,353
Practise Questions for Templates,Functors,CallBack functions in c++?
I have been reading templates,functors,callback function for the past week and have referred some good books and articles. I however feel that, unless I can get good practice - programming in templates and use functors-callbacks there is no way I can really understand all the concepts or fluently use them while coding...
A good exercise is to replace named functions with anonymous functors. For example, instead of using a predicate such as bool is_overdrawn(const Account& account) { return !account.is_balanced(); } , you can synthesize a functor via std::not1(std::mem_fun_ref(&Account::is_balanced)).
2,791,470
2,791,589
How to get forkpty/execvp() to properly handle redirection and other bash-isms?
I've got a GUI C++ program that takes a shell command from the user, calls forkpty() and execvp() to execute that command in a child process, while the parent (GUI) process reads the child process's stdout/stderr output and displays it in the GUI. This all works nicely (under Linux and MacOS/X). For example, if the us...
If you want the shell to do the I/O redirection, you need to invoke the shell so it does the I/O redirection. char *args[4]; args[0] = "bash"; args[1] = "-c"; args[2] = ...string containing command line with I/O redirection...; args[4] = 0; execv("/bin/bash", args); Note the change from execvp() to execv(); you know ...
2,791,477
2,791,607
Random numbers from binomial distribution
I need to generate quickly lots of random numbers from binomial distributions for dramatically different trial sizes (most, however, will be small). I was hoping not to have to code an algorithm by hand (see, e.g., this related discussion from November), because I'm a novice programmer and don't like reinventing wheels...
Boost 1.43 appears to support binomial distributions. You can use boost::variate_generator to connect your source of randomness to the type of distribution you want to sample from. So your code might look something like this (Disclaimer: not tested!): boost::mt19937 rng; // produces randomness out of th...
2,791,540
2,791,550
C++ Memory allocation question involving vectors
vector< int > vect; int *int_ptr = new int(10); vect.push_back( *int_ptr ); I under stand that every "new" needs to be followed by a "delete" at some point but does the clear() method clean this memory? What about this method of doing the same thing: vector< int > vect; int int_var = 10; vect.push_back( int_var ); Fr...
The first method leaks because the vector never takes ownership of the allocated pointer. In fact, it doesn't contain a pointer at all, only a copy of the value. The second method does not leak, as no memory is dynamically allocated (except internally in the vector -- it will handle that memory itself).
2,791,546
2,791,560
How do you delete a pointer without deleting the data the pointer points to?
I have a pointer that points to an array and another pointer referencing the same array. How do i delete any one of those pointers without killing the array such that the second undeleted pointer still works? for example: int* pointer1 = new int [1000]; int* pointer2; pointer2 = pointer1; Now i want to get rid of poin...
Those pointers are on the stack; you don't have to delete them. Just ignore pointer1 and it will go away at the end of the block.
2,791,653
2,791,876
Passing C++ object to C++ code through Python?
I have written some physics simulation code in C++ and parsing the input text files is a bottleneck of it. As one of the input parameters, the user has to specify a math function which will be evaluated many times at run-time. The C++ code has some pre-defined function classes for this (they are actually quite complex ...
I do things similar to this all the time. The simplest solution, and the one I usually pick because, if nothing else, I'm lazy, is to flatten your API to a C-like API and then just pass pointers to and from Python (or your other language of choice). First create your classes class MyFunctionClass { public: MyFun...
2,791,739
2,906,921
C++ packing a typedef enum
typedef enum BeNeLux { BELGIUM, NETHERLANDS, LUXEMBURG } _ASSOCIATIONS_ BeNeLux; When I try to compile this with C++ Compiler, I am getting errors, but it seems to work fine with a C compiler. So here's the question. Is it possible to pack an enum in C++, or can someone see why I would get the error? The erro...
UPDATE: For C++11 and later, you can specify the underlying type of enums. For example: enum BeNeLux : uint8_t { BELGIUM, NETHERLANDS, LUXEMBURG }; But this only applies if the code will be C++ only. If the code needs to be compatible with both C and C++, I believe my original answer still applies. I don't t...
2,791,852
2,791,908
C++ exam on string class implementation
I just took an exam where I was asked the following: Write the function body of each of the methods GenStrLen, InsertChar and StrReverse for the given code below. You must take into consideration the following; How strings are constructed in C++ The string must not overflow Insertion of character increases its length...
First, the trivial }; question is just a matter of style. I do that too when I put function bodies inside class declarations. In that case the ; is just an empty statement and doesn't change the meaning of the program. It can be left out of the end of the functions (but not the end of the class). Here's some major prob...
2,791,870
2,791,887
Why can't I access a const vector with iterator?
My example is as below. I found out the problem is with "const" in function void test's parameter. I don't know why the compiler does not allow. Could anybody tell me? Thanks. vector<int> p; void test(const vector<int> &blah) { vector<int>::iterator it; for (it=blah.begin(); it!=blah.end(); it++) { cout...
An iterator is defined as returning a reference to the contained object. This would break the const-ness of the vector if it was allowed. Use const_iterator instead.
2,792,028
2,792,103
initializer_list not working in VC10
i wrote this program in VC++ 2010: class class1 { public: class1 (initializer_list<int> a){}; int foo; float Bar; }; void main() { class1 c = {2,3}; getchar(); } but i get this errors when i compile project: Error 1 error C2552: 'c' : non-aggregates cannot be initialized with initializer list c:\users\pswi...
It shouldn't be supported at all: [...] the C++0x Core Language feature of initializer lists and the associated Standard Library changes weren't implemented in VC10. The error message refers to the pre-C++0x feature of aggregate initialization, which allows the initialization of certain user-defined types by using cu...
2,792,238
2,803,318
variable scope when adding a value to a vector in class constructor
I have a level class and a Enemy_control class that is based off an vector that takes in Enemys as values. in my level constructor I have: Enemy tmp( 1200 ); enemys.Add_enemy( tmp ); // this adds tmp to the vector in Enemy_control enemys being a variable of type Enemy_control. My program crashes after these statements...
As alread pointed out the description of your problem is not really precise. One of the things which strikes me as odd is why the destructor of any of your classes gets called. Looking at your code it becomes clear that Enemy tmp is a local instance which gets cleaned up after leaving the Level constructor. The Add_Ene...
2,792,443
2,792,459
Finding the centroid of a polygon?
To get the center, I have tried, for each vertex, to add to the total, divide by the number of vertices. I've also tried to find the topmost, bottommost -> get midpoint... find leftmost, rightmost, find the midpoint. Both of these did not return the perfect center because I'm relying on the center to scale a polygon. I...
The formula is given here for vertices sorted by their occurance along the polygon's perimeter. For those having difficulty understanding the sigma notation in those formulas, here is some C++ code showing how to do the computation: #include <iostream> struct Point2D { double x; double y; }; Point2D compute2D...
2,792,520
2,834,241
use qt and django to create desktop apps
I had this idea of creating desktop apps using django. The principe being: - Write the django app, and use something like cherrypy to serve it. - Write a Qt app in C++ to access it and this by using QtWebview (webkit) I'd like to "bundle" this in a single app. The lighter, the better :) So here are my questions and if ...
Look at http://www.python-camelot.com/ It says "A python GUI framework on top of Sqlalchemy and PyQt, inspired by the Django admin interface."
2,792,604
2,792,666
Compiling a Windows C++ program in g++
I'm trying to compile a Windows C++ program in g++. This is what I get. /usr/include/c++/4.4/backward/backward_warning.h:28:2: warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equiv...
From the linked page: // the main function is just some code to test the b-tree. it inserts 100,000 elements, // then searches for each of them, then deletes them in reverse order (also tested in // forward order) and searches for all 100,000 elements after each deletion to ensure that // all remaining elemen...
2,792,704
2,792,735
How to use gdb to find a floating point exception in g++ code
I have a g++ program that runs without user input. Somewhere the program is interrupted and it says "Floating point exception." Can gdb help me find what's causing this in my code? How?
You can get help on GDB here and at Gnu's site here. But the basics are this: $ gdb ./your_program // start gdb on the program > run // run the program > run argv1 argv2 // or run it with command line arguments (floating point exception) // let it run until e...
2,792,770
2,792,786
Accessing a webpage in C++
Is there a good, simple library which allows C++ to load a webpage? I just want to grab the source as text. I'm not using any IDE or significant library, just straight command line. Tangentially, is there something fundamental I'm missing about programming in C++? I would think any language in common use today would ha...
Sure, for example libcurl is powerful and popular. Internet-related libraries for C++ are extremely abundant -- they're just not part of the C++ standard, partly because the current version of that standard is so old, though I'm sure that's not the only reason. But turn to the world of open sources and you'll find mor...
2,793,425
2,793,429
Seeking to a line in a file in g++
Is there a way that I can seek to a certain line in a file to read or write data? Let's say I want to write some data starting on the 10th line in a text file. There might be some data already in the first few lines, or the file could even be empty. Is there a way I can seek directly to the line I want without having...
You can seek to a position in a file, but that position must be a character offset from the start, end or current position - see for example fseek(). There is no way of seeking to a particular line, unless all the lines are exactly the same length.
2,793,588
2,793,614
two classes contain objects of each other
i hope there's a simple answer to this. without getting too complicated i have two classes. an "Animal" and a "Cell" Cell contains an Animal as a member. Animal has methods that accept Cells in their parameters. i'm just confused as to how i #include each class the others header? i've only ever had to go up a chain of ...
You can use forward declarations to overcome the problem of circular references. Example: //animal.h #include "cell.h" class Animal { public: void foo (Cell cell); } // cell.h class Animal; // forward declaration class Cell { private: Animal * m_animal; // pointer to Animal object }
2,793,694
2,793,731
Dynamic allocating of const member structures
I've got class which is using plain-only-data struct with const variables and I'm not sure, if I'm allocating these structures in a proper way. It looks more or less like: #include <cstdlib> #include <iostream> using std::cout; using std::endl; struct some_const_struct { const int arg1; const int arg2; }; ...
m_const_member(new some_const_struct((const some_const_struct){a, b})) Such syntax is not allowed by standard C++ and is only supported by your compiler as an extension. I think the only standard-compiliant way with the current standard1 would be to use copy-construction and a helper function to initialize the struct ...
2,793,774
2,793,782
Error: Declaration terminated incorrectly
I get the error in this part of the code: void baklanges(list<MataIn> lista); { int n = text.length(); for (int i = 0; i < n/2; i++) { char temp = text.at(i); text.at(i) = text.at(n-1-i); text.at(n-1-i)= temp; } cout<<"Texten baklanges:\n"<<text<<endl; } I don't see any problem in the code,does any of you?
Remove this semicolon. void baklanges(list<MataIn> lista); ^
2,794,054
2,794,219
Documenting functions in C++ with Doxygen
I've got a project that I'm using Doxygen to generate documentation for. The documentation of the classes is fine, but I've also got some non-member functions that I use to create objects etc. I'd also like to have these documented, but no matter what I try, Doxygen will not generate documentation from the comments tha...
Use \fn where you otherwise use \class in your \\*! *\ block http://www.doxygen.nl/manual/docblocks.html look for "Documentation at other places" http://www.doxygen.nl/manual/commands.html#cmdfn It works similar as documenting member functions
2,794,079
2,794,105
C++: Define simple constant for use?
In C++ I wanted to define a constant that I can use in another function, A short answer on how to do this will be fine.. Lets say at the beginning of my code I want to define this constant: //After #includes bool OS = 1; //1 = linux if (OS) { const ??? = "clear"; } else { const ??? = "cls"; } I don't know what ty...
char* isn't quite a char. char* is basically a string (it's what strings were before C++ came along). For illustration: int array[N]; // An array of N ints. char str[N]; // An array of N chars, which is also (loosely) called a string. char[] degrades to char*, so you'll often see functions take a char*. To convert...
2,794,369
2,794,481
template class: ctor against function -> new C++ standard
in this question: template; Point<2, double>; Point<3, double> Dennis and Michael noticed the unreasonable foolishly implemented constructor. They were right, I didn't consider this at that moment. But I found out that a constructor does not help very much for a template class like this one, instead a function is here ...
Yes, as Michael pointed out in his answer to your previous question, in C++0x you'll be able to use an initializer list to pass an arbitrary number of arguments to your ctor. In your case, the code would look something like: template <int dims, class T> class point { T X[dims]; public: point(std::initializer_l...
2,794,385
2,794,400
Is the "==" operator required to be defined to use std::find
Let's say I have: class myClass std::list<myClass> myList where myClass does not define the == operator and only consists of public fields. In both VS2010 and VS2005 the following does not compile: myClass myClassVal = myList.front(); std::find( myList.begin(), myList.end(), myClassVal ) complaining about lack of == ...
The compiler does not automatically generate a default operator==(), so if you don't write one yourself, objects of your class can't be compared for equality. If you want memberwise comparison on the public members you have to implement that yourself as operator==() (or "manually" use a separate function/functor to do ...
2,794,492
2,795,603
How to tell what optimizations bjam is using to build boost
I'm building the boost libraries with bjam for both the intel compiler and vs2008, and I can't tell what optimizations are being passed to the compiler from bjam. For one of the compiler's gcc, I can see some optimizations in one of the bjam files, but I can't find the optimization flags for the compilers I care about....
If you are interested in looking at the entire set of options that are passed to invoke the compiler when building you can run bjam with the -n -a options and the rest of the building options to give you the complete set of commands invoked, and any response files generated (see Boost Jam Options). Also you can look at...
2,794,596
2,794,844
Sequential File Access, load multiple text files in project directory using C++
Is it possible to load multiple files from a project directory. For example, loading FileA.txt, FileB.txt, and FileC.txt from a folder (raw/assets) within the project folder? Any help would be much appreciated.
Since your comment says you're targetting Windows, take a look at this API function: http://msdn.microsoft.com/en-us/library/aa364418%28VS.85%29.aspx Find files matching your pattern and deal with them http://www.cplusplus.com/doc/tutorial/files/
2,794,637
2,794,658
How to easily substitute a Base class
I have the following hierarchy of classes class classOne { virtual void abstractMethod() = 0; }; class classTwo : public classOne { }; class classThree : public classTwo { }; All classOne, classTwo and classThree are abstract classes, and I have another class that is defining the pure virtual methods class cla...
template<class Base> struct Concrete : Base { void abstractMethod(); void doIt() { // example of accessing inherited members: int n = Base::data_member; // or this->data_member n = Base::method(); // non-virtual dispatch n = this->method(); // virtual dispatch // since Base is a template param...
2,794,825
2,794,889
boost::lambda bind expressions can't get bind to string's empty() to work
I am trying to get the below code snippet to compile. But it fails with: error C2665: 'boost::lambda::function_adaptor::apply' : none of the 8 overloads could convert all the argument types. Specifying the return type when calling bind does not help. Any idea what I am doing wrong? #include <boost/lambda/lambda.hpp> #...
minor changes to make it compile with g++ (time for better compiler :-) ?) 1 #include <boost/lambda/lambda.hpp> 2 #include <boost/lambda/bind.hpp> 3 #include <algorithm> 4 #include <iostream> 5 #include <string> 6 #include <map> 7 8 int main() 9 { 10 11 namespace bl = boost::lambda; 12 typedef std::map...
2,794,916
2,794,919
Pre-compile .h files
I have a really short program written in boost::xpressive #include <iostream> #include <boost/xpressive/xpressive.hpp> using namespace boost::xpressive; int main() { std::string hello( "hello world!" ); sregex rex = sregex::compile( "(\\w+) (\\w+)!" ); smatch what; if( regex_match( hello, what, rex...
You can use precompiled headers if your compiler supports them; both g++ and Visual C++ support precompiled headers, as do most other modern C++ compilers, I suspect.
2,794,956
2,794,962
C++ Namespaces & templates
I have some functions that can be grouped together, but don't belong to some object / entity and therefore can't be treated as methods. So, basically in this situation I would create a new namespace and put the definitions in a header file, the implementation in cpp file. Also (if needed) I would create an anonymous n...
That's a pretty common solution. Boost does it, and I do it as well, but with the detail namespace instead. Just make it a rule: "don't look inside detail!" File-wise, I recommend giving details their own file, and tucking it away in a detail folder. That is, my code would be akin to: // v #include "detail/Re...
2,795,023
2,795,024
C++ template typedef
I have a class template<size_t N, size_t M> class Matrix { // .... }; I want to make a typedef which creates a Vector (column vector) which is equivalent to a Matrix with sizes N and 1. Something like that: typedef Matrix<N,1> Vector<N>; Which produces compile error. The following creates something similar, but n...
C++11 added alias declarations, which are generalization of typedef, allowing templates: template <size_t N> using Vector = Matrix<N, 1>; The type Vector<3> is equivalent to Matrix<3, 1>. In C++03, the closest approximation was: template <size_t N> struct Vector { typedef Matrix<N, 1> type; }; Here, the type Vec...
2,795,237
2,795,292
it takes 2 seconds to compile a hello world C++ project in netbeans (windows)
I used code:blocks as the C++ IDE on Windows. I switched to netbeans 6.8 (with C/C++ plugin, MinGW, MSYS) recently, because netbeas have the nice feature of "checking syntax errors when typing" (same as working on Java or PHP projects). But the painful thing is that, it takes 2 seconds to compile a simple hello world p...
MinGW uses G++ 3.x, which is very very old. It's a limitation of the compiler itself -- old versions of G++ are simply slow. There are some "unofficial" G++ ports to windows that borrow from the MinGW project that use more recent (4.x) versions of G++, and it's possible your Code::Blocks IDE was using one of those. I s...
2,795,243
2,795,273
Error in function prototype
Why does this code result in error? class CommonRuntine { public: struct TProcess; TProcess GetProcessByName(LPCSTR ProcessName); }; It says "E2293 ) Expected" on the "};" bit PS : LPCSTR is a type
#include <windows.h> Had to include the file defining that type
2,795,309
2,877,835
How do you parse the XDG/gnome/kde menu/desktop item structure in c++?
I would like to parse the menu structure for Gnome Panels (the standard Gnome Desktop application launcher) and it's KDE equivalent using c/c++ function calls. That is, I'd like a list of what the base menu categories and submenu are installed in a given machine. I would like to do with using fairly simple c/c++ functi...
After much painful research... it seems the most stable approach is to take the gnome menu parsing code, rip it of the tar ball and use it locally. The version I used is here: http://download.gnome.org/sources/gnome-menus/2.28/gnome-menus-2.28.0.1.tar.gz This code loudly proclaims that it shouldn't treated as any kind...
2,795,395
2,803,171
controling individual pins on a serial port
I know that serial ports work by sending a single stream of bits in serial. I can write programs to send and receive data from that one pin. However, there are a lot more other pins on the serial port connection that normal aren't used but from documentation all seem to have some sort of function for signalling as oppo...
Based of the suggestion of Hans Passant , I'd like to suggest that you use an Arduino instead of an USB-to-serial converter. The "Duemilanove" is an Arduino-based board that provides 6 PWM outputs (as well as 8 other digitial I/Os and 6 analog). Some more specialized boards might be even cheaper (Arduino Pro Mini, $15 ...
2,795,443
2,795,469
What's the difference between the terms "source file" and "translation unit"?
What's the difference between source file and translation unit?
From the C++ Standard: A source file together with all the headers and source files included via the preprocessing directive #include less any source line skipped by any of the conditional inclusion preprocessing directives is called a translation unit.
2,795,466
2,795,476
Converting a time_t to string
I have a time_t variable containing a timestamp which I'd like to store in a database, so I need it as a string. How would I convert it? Also, on the subject, how would I convert a timestamp string into a time_t variable? Thanks, Wyatt
Look at ctime, it takes a time_t and returns a string. To make a timestamp from a string, look at mktime. Populate the fields of a struct tm and call mktime. It should return a time_t.
2,795,482
2,795,510
Is there a cross-platform header in the standard library that provides access to the current time?
Probably a stupid question, but I couldn't find anything searching... Is there a standard header that allows me to fetch the current time? Otherwise is there some cross-platform alternative?
time.h, and the time function.
2,795,528
2,812,701
Bluetooth service problem
I need to create a custom bluetooth service and I have to develop it using c++. I read a lot of examples but I didn't success in publishing a new service with a custom UUID. I need to specify a UUID in order to be able to connect to the service from an android app. This is what i wrote: GUID service_UUID = { /* 0000000...
You have to create the SDP record and publish it with WSASetService before bind and wait for connections. Follow this tutorial, and you'll be able to receive connections.
2,795,575
2,795,596
How does dereferencing of a function pointer happen?
Why and how does dereferencing a function pointer just "do nothing"? This is what I am talking about: #include<stdio.h> void hello() { printf("hello"); } int main(void) { (*****hello)(); } From a comment over here: function pointers dereference just fine, but the resulting function designator will be imm...
It's not quite the right question. For C, at least, the right question is What happens to a function value in an rvalue context? (An rvalue context is anywhere a name or other reference appears where it should be used as a value, rather than a location — basically anywhere except on the left-hand side of an assignme...
2,795,609
2,795,611
How does #error in C/C++ work?
I am guessing from # that it is only a compile-time utility. How can it be used in C/C++ programs? Did not find much about it on the internet. Any links would be helpful.
It causes the compiler (or preprocessor) to output the error message. In C++, it also renders the translation unit ill-formed (i.e., it causes compilation to fail). If you have several macros that could be defined and you want to be sure that only certain combinations of them are defined, you can use #error to cause c...
2,795,943
2,795,955
How to iterate properly across a const set?
I'm working on a program that's supposed to represent a graph. My issue is in my printAdjacencyList function. Basically, I have a Graph ADT that has a member variable "nodes", which is a map of the nodes of that graph. Each Node has a set of Edge* to the edges it is connected to. I'm trying to iterate across each node ...
Try changing sit to a const_iterator. Change mit to a const_iterator too while you're at it. Also, getEdges() and getEndpoints() should be const functions. Lastly, because operator->() has a higher precedence than the unary operator*(), you probably want to say edgeNodes = (*sit)->getEndPoints() inside the inner-loop. ...
2,795,964
2,795,999
Getting a unix timestamp as a string in C++
I'm using the function time() in order to get a timestamp in C++, but, after doing so, I need to convert it to a string. I can't use ctime, as I need the timestamp itself (in its 10 character format). Trouble is, I have no idea what form a time_t variable takes, so I don't know what I'm converting it from. cout handles...
time_t is some kind of integer. If cout handles it in the way you want, you can use a std::stringstream to convert it to a string: std::string timestr(time_t t) { std::stringstream strm; strm << t; return strm.str(); }
2,796,016
2,796,340
Specify an inline callback function as an argument
Let me first explain what I'm trying to achieve using some pseudo-code (JavaScript). // Declare our function that takes a callback as as an argument, and calls the callback with true. B(func) { func(true); } // Call the function B(function(bool success) { /* code that uses success */ }); I hope this says it all. If n...
If your compiler is a fairly recent release (such as Visual Studio 2010 or GCC 4.5), you can use some new features from the new C++ standard, which is currently in ratification and should be published soon. I don't know what you need to do to enable this in Visual Studio, but it should be well-documented either on MSDN...
2,796,223
2,796,235
Copying from istream never stops
This bit of code runs infinitely: copy(istream_iterator<char>(cin), istream_iterator<char>(), back_inserter(buff)); The behavior I was expecting is that it will stop when I press enter. However it doesn't. buff is a vector of chars.
I assume you are typing stuff in at the keyboard. The enter key doesn't signify the end of the stream. It's just another character from cin's perspective. You need to submit EOF to achieve this (Ctrl+Z, Enter on Windows and Ctrl+D on Unix/Mac). Incidentally, this isn't the usual way to read characters from the console....
2,796,413
2,796,504
Binary search to find the rotation point in a rotated sorted list
I have a sorted list which is rotated and would like to do a binary search on that list to find the minimum element. Lets suppose initial list is {1,2,3,4,5,6,7,8} rotated list can be like {5,6,7,8,1,2,3,4} Normal binary search doesn't work in this case. Any idea how to do this. -- Edit I have one another condition. Wh...
A slight modification on the binary search algorithm is all you need; here's the solution in complete runnable Java (see Serg's answer for Delphi implementation, and tkr's answer for visual explanation of the algorithm). import java.util.*; public class BinarySearch { static int findMinimum(Integer[] arr) { ...
2,796,726
2,796,735
copying a substring from a string given end index in string
How can I copy a substring from a given string with start and end index or giving the start index and length of the string are given.
From a std::string, std::string::substr will create a new std::string from an existing one given a start index and a length. It should be trivial to determine the necessary length given the end index. (If the end index is inclusive instead of exclusive, some extra care should be taken to ensure that it is a valid inde...
2,796,966
2,797,808
`.' cannot appear in a constant-expression
I'm getting the following error: `.' cannot appear in a constant-expression for this function (line 4): bool Covers(const Region<C,V,D>& other) const { const Region& me = *this; for (unsigned d = 0; d < D; d++) { if (me[d].min > other[d].min || me[d].max < other[d].max) { ...
Trying out your code tells me, that the compiler has a problem with the me[d].max < other[d].max part. So the problem with the dot was bogus. Instead the compiler has a problem with the comparison operator. Just reverting the comparison made the compiler error magically disappear: if (me[i].min > other[i].min || other[...
2,797,014
2,797,022
Why can't I reserve 1,000,000,000 in my vector?
When I type in the foll. code, I get the output as 1073741823. #include <iostream> #include <vector> using namespace std; int main() { vector <int> v; cout<<v.max_size(); return 0; } However when I try to resize the vector to 1,000,000,000, by v.resize(1000000000); the program stops executing. How can I enable t...
A 32-bit process can only address 4GB address space at a single time. Usually, plenty of this 4GB address space is used to map other stuff. Your vector is going to take too much contiguous address space (4 billion bytes) which is not likely to be available. You should memory map the file. See mmap.
2,797,208
2,797,233
How union is used to define a class
I have two doubts, please help me on this: Is it possible to define a class inside union Is it possible to define a class without class name
1 - yes with restriction that class has no constructor or destructor 2 - yes Following code aggregates both as an example: union MyUnion { class { public: int a; int b; } anonym_access; double align; }; int main() { MyUnion u; //instance checks if it is compileable }
2,797,366
2,839,111
Win32 Thread Exits Unexpectedly
I'm writing a C++ application. I realized that one of my worker threads may terminate unexpectedly. The (VS 2005) debug log says: The thread 'Win32 Thread' (0x5d98) has exited with code -858993460 (0xcccccccc). I surrounded all the worker thread code with a try/catch block. So, if the reason was an exception, I w...
I found an important clue. When you close a handle with CloseHandle function, the thread exits with code 0xCCCCCCCC. With the help of this clue, I realized that in a very rare situation, I close my thread's handle even though the thread's working. Why does it exit exactly while getting connection? That also has an expl...
2,797,390
2,797,638
C callback functions defined in an unnamed namespace?
I have a C++ project that uses a C bison parser. The C parser uses a struct of function pointers to call functions that create proper AST nodes when productions are reduced by bison: typedef void Node; struct Actions { Node *(*newIntLit)(int val); Node *(*newAsgnExpr)(Node *left, Node *right); /* ... */ }; Now, ...
I don't get the problem. The extern keyword does not affect the calling convention, merely the name presented to the linker. A function written in C++ that is not an instance method is still __cdecl, with or without extern "C". Furthermore, as long as you keep createActions() in the same source code file, these func...
2,797,391
2,797,439
Singleton with inheritance, Derived class is not able to get instantiated in parent?
Below code instantiates a derived singleton object based on environment variable. The compiler errors saying error C2512: 'Dotted' : no appropriate default constructor. I don't understand what the compiler is complaining about. EDIT: Fixed issues with implementing the get instance method which requires definition of bo...
There are several problems with your code: You mean to return type Singleton& or const Singleton&. You are currently returning by value, which is attempting to invoke a copy constructor, and no such constructor exists. Your default constructor in Dotted probably is not available in Singleton. I suggest you make Single...
2,797,451
2,797,537
GDI+ not clearing my window on repaint for vista
on WM_PAINT i do the following: //RectF mNameRect; //WCHAR* mName; //HWND mWin; // this is the window handle { PAINTSTRUCT ps; HDC hdc = BeginPaint(mWin, &ps); Graphics g(hdc); g.Clear(Color::White); StringFormat stringForm; stringForm.SetLineAlignment(StringAlignmentCenter); stringForm.SetAlignment(StringAlignmentCe...
You are explicitly calling your paint() function when the window is resized. However, your window is not invalidated, so it could be that the system is restricting your painting efforts to the region marked "dirty". Instead of calling paint() directly, it is better to use InvalidateRgn to trigger a repaint. This will c...
2,797,468
2,797,482
capture the last WM_SIZE
When I resize my window I want to tell another part of my program that my window has changed size. I read on MSDN that: WM SIZE Message The WM SIZE message is sent to a window after its size has changed. However, I receive the WM_SIZE even when dragging. I noticed that there is also a WM_SIZING message that is sent whe...
When you start dragging a window, the system enters a modal move/resize loop; it does not return to your own message loop until the drag action has finished. You are still getting WM_SIZE because it is sent directly to the window procedure, but it does not flow through your own message loop. At the beginning of such a ...
2,797,533
2,797,727
Undefined template methods trick?
A colleague of mine told me about a little piece of design he has used with his team that sent my mind boiling. It's a kind of traits class that they can specialize in an extremely decoupled way. I've had a hard time understanding how it could possibly work, and I am still unsure of the idea I have, so I thought I woul...
Like @Steward suspected, it's not valid. Formally it's effectively causing undefined behavior, because the Standard rules that for a violation no diagnostic is required, which means the implementation can silently do anything it wants. At 14.7.3/6 If a template, a member template or the member of a class template is e...
2,797,538
2,797,555
question about ? and : in c++
Why this statement : int a = 7, b = 8, c = 0; c = b>a?a>b?a++:b++:a++?b++:a--; cout << c; is not equal to : int a = 7, b = 8, c = 0; c = (b>a?(a>b?a++:b++):a++)?b++:a--; cout << c; and is equal to : int a = 7, b = 8, c = 0; c = b>a?(a>b?a++:b++):(a++?b++:a--); cout << c; Please give me some reason. Why ?
Because ? : is right-to-left associative. It's defined like that in the language.
2,797,813
2,797,823
How to convert a command-line argument to int?
I need to get an argument and convert it to an int. Here is my code so far: #include <iostream> using namespace std; int main(int argc,int argvx[]) { int i=1; int answer = 23; int temp; // decode arguments if(argc < 2) { printf("You must provide at least one argument\n"); exit(0);...
Since this answer was somehow accepted and thus will appear at the top, although it's not the best, I've improved it based on the other answers and the comments. The C way; simplest, but will treat any invalid number as 0: #include <cstdlib> int x = atoi(argv[1]); The C way with input checking: #include <cstdlib> er...
2,798,071
3,802,332
Pure/const functions in C++
I'm thinking of using pure/const functions more heavily in my C++ code. (pure/const attribute in GCC) However, I am curious how strict I should be about it and what could possibly break. The most obvious case are debug outputs (in whatever form, could be on cout, in some file or in some custom debug class). I probably ...
I would expect the output: I would expect the input: int bar(int x) { return foo(x) * 100; } Your code actually looks strange for me. As a maintainer I would think that either foo actually has side effects or more likely rewrite it immediately to the above function. How does it work out in practice? If I mark su...
2,798,188
2,798,511
pure/const function attributes in different compilers
pure is a function attribute which says that a function does not modify any global memory. const is a function attribute which says that a function does not read/modify any global memory. Given that information, the compiler can do some additional optimisations. Example for GCC: float sigmoid(float x) __attribute__ ((c...
GCC: pure/const function attributes llvm-gcc: supports the GCC pure/const attributes Clang: seems to support it (I tried on a simple example with the GCC style attributes and it worked.) ICC: seems to adopt the GCC attributes (Sorry, only a forum post.) MSVC: Seems not to support it. (discussion) In general, it seems...
2,798,236
2,798,244
template; operator (int)
regarding my Point struct already mentioned here: template class: ctor against function -> new C++ standard is there a chance to replace the function toint() with a cast-operator (int)? namespace point { template < unsigned int dims, typename T > struct Point { T X[ dims ]; //umm??? template < typename U >...
The correct syntax is operator int() const { ... There's no need to have that extra return type when you overload the cast operator. And when you say (int)x, the compiler really expects to get an int, not a Point<dims, int>. Probably you want a constructor instead. template <typename U> Point(const Point<dims,...
2,798,322
2,839,320
How to overlay direct3d in directshow
I am looking for a tutorial or documentation on how to overlay direct3d on top of a video (webcam) feed in directshow. I want to provide a virtual web cam (a virtual device that looks like a web cam to the system (ie. so that it be used where ever a normal webcam could be used like IM video chats) I want to capture a...
Use the Video Mixing Renderer Filter to render the video to a texture, then render it to the scene as a full screen quad. After that you can render the rest of the 3D stuff on top and then present the scene.
2,798,608
2,798,624
C++: Declare a global class and access it from other classes?
I have a class which should be declared globally from main() and accessed from other declared classes in the program, how do I do that? class A{ int i; int value(){ return i;} }; class B{ global A a; //or extern?? int calc(){ return a.value()+10; } } main(){ global A a; B b; cout<...
You probably really do not want to do this, but if you must - in the file that contains main: #include "A.h" A a; int main() { ... } and then in the files that need to access the global: #include "A.h" extern A a; You will need to put the declaration of A in the A.h header file in order for this to work.
2,798,644
2,798,652
Selecting size of vector of vectors
I have a class called Grid that declares a vector of vectors like this: typedef vector<int> row; typedef vector<row> myMatrix; myMatrix sudoku_; The constructor looks like this: grid::grid() : sudoku_(9,9) { } As you can see, the constructor is initializing it to be a 9x9 grid. How can I make it work so that the us...
vector has a constructor that allows you to initialize it to a certain size with copies of a given value: grid::grid(size_t w, size_t h) : sudoku_(w, row(h)) {}
2,798,708
2,798,767
Difference between C++ Keyboard keycode and JAVA KeyEvent keycode
I noticed a difference between the keycodes that vkCode in C++ gives and the ones that Java's KeyEvent gives us. (Ofcourse the normal characters have the same code (0 => 48 just like the ASCII) but they differ in the other keys). Is there a way to 'translate' them from one to the other (What's the logic behind each one...
or am I supposed to use loads of switches and IFs You can probably just put them in a lookup table, that is, put the Java KeyCodes in a large array, so you just need to do javaKeyCode = keyLut[cppScanCode]. One list of scan codes can be found here, and the VK_KEYCODES can of course be found in the API docs for KeyEve...
2,798,832
2,799,346
QApplication In Non-Main Thread
I need to exec() a QApplication in a thread that is not main (my GUIs must be plugins that can be dynamically loaded and unloaded at runtime, so I have no access to the main thread). Does anyone know of a (relatively) painless way to hack around Qt's restriction against starting QApplication outside of main? I'm devel...
If you are using QThread then you already have normal Qt event loop and can just run exec() inside QThread::run() function. While you can't work with GUI objects outside of the main thread you still can interact with them through queued signal/slot connections. Maybe you can try to store pointer to the main thread QThr...
2,798,959
2,798,987
It is good programming practice to always check for null pointers before using an object in C++?
This seems like a lot of work; to check for null each time an object is used. I have been advised that it is a good idea to check for null pointers so you don't have to spend time looking for where segmentation faults occur. Just wondering what the community here thinks?
Use references whenever you can, because they can't be null, therefore you don't have to check if they are null. It's good practice to check for null in function parameters and other places you may be dealing with pointers someone else is passing you. However, in your own code, you might have pointers you know will al...