question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,615,916
1,615,930
Most natural blinking visualization?
What is the ideal method for blinking information on a display to draw attention to an error condition in some data in a natural fashion. Should the blink be all on / all off, or should there be an aspect of fast ramp up and down of brightness instead of instant on / off transitions? Should the blink be equally on and...
I've always found the highlight effect present in various javascript libraries pleasing. It basically flashes the background of the object a bright-ish yellow immediately, then fades back to the original background color.
1,616,086
1,616,621
Shifting elements in an array C++
I've developed a method called "rotate" to my stack object class. What I did was that if the stack contains elements: {0,2,3,4,5,6,7} I would needed to rotate the elements forwards and backwards. Where if i need to rotate forwards by 2 elements, then we would have, {3,4,5,6,7,0,2} in the array. And if I need to rotate ...
The function rotate below is based on reminders (do you mean this under the 'mod' operation?) It is also quite efficient. // Helper function. // Finds GCD. // See http://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);} // Number of assignments of ele...
1,616,093
1,682,309
does presence of mutex help getting rid of volatile key word ?
I have a multi-R/W lock class that keeps the read, write and pending read , pending write counters. A mutex guards them from multiple threads. My question is Do we still need the counters to be declared as volatile so that the compiler won't screw it up while doing the optimization. Or does the compiler takes into acc...
There are 2 basically unrelated items here, that are always confused. volatile threads, locks, memory barriers, etc. volatile is used to tell the compiler to produce code to read the variable from memory, not from a register. And to not reorder the code around. In general, not to optimize or take 'short-cuts'. memo...
1,616,571
1,616,642
c++ send data to multiple UDP sockets
I got a c++ non-blocking server socket, with all the clients stored in a std::map structure. I can call the send() method for each clientObject to send something to the connected client and that works pretty good already. But for sending a message to all (broadcast?) i wanna know: there is something better than do a fo...
Multicast is only an option if you're communicating over a LAN. It won't work over the Internet. What you may want to do here is to demultiplex the sockets using asynchronous I/O. This allows you to send data to multiple sockets at the same time, and use asynchronous event handlers to deal with each transmission. I w...
1,616,827
1,616,960
Problem with Pointers in C++
char *str = NULL; str = Operation(argv[1]); cout << Cal(str); Operation function return a pointer, but I really don't know why str in Cal is null. in line 2, it still has content. What am I missing? char* Operation(char* name) { fstream file(name,ios::in); char c; char stack[256]; int count_stack = -1; ...
Well, firstly, in your Operation function you're returning a pointer to a temporary stack array. In Operation you declare char result[256] as a temporary stack variable. The 256 bytes you allocate here are ONLY valid for the duration of the Operation function. So using the pointer to result after Operation returns w...
1,616,855
1,618,134
Boost::Xpressive compile puzzle under MinGW
Switching to GCC for the first time, and I'm getting a bit confused by what the compiler is telling me here. Essentially, it's behaving like boost::xpressive::wsregex is not defined (I believe). Here is the relevant code: #include "criterion.h" #include <string> #include <boost/xpressive/xpressive.hpp> //More lines of...
cygwin and mingw do not support wide characters, so xpressive can't either. See the following from xpressive_fwd.hpp: #if defined(BOOST_NO_CWCHAR) | \ defined(BOOST_NO_CWCTYPE) | \ defined(BOOST_NO_STD_WSTRING) # ifndef BOOST_XPRESSIVE_NO_WREGEX # define BOOST_XPRESSIVE_NO_WREGEX # endif #endif The macros BOO...
1,616,886
1,616,891
How to make class not derivable at all. is there any way?
Hi any one let me know How to make class not derivable at all. is there any way? please let me know. regards Hara
See this explanation on how do to it, and why it might not be a good idea, by Bjarne Stroustrup (creator of C++ himself).
1,617,055
1,617,073
function implementation in : file.h vs in file.cxx
My question is very simple: I am working on a old legacy code where most of function are implemented in header file only. As per my knowledge, Compiler convert function implemented in header into inline functions. I wanted to know if i move these implementation into .cxx file , What will be benefits?
To the compiler there is no difference between input that come from a .cxx file or a .h file, this text gets compiled into the same unit of translation. The main reason why we typically do not put code inside header files, is to avoid duplicate objects, which then conflict at the level of the linker, when a given heade...
1,617,204
1,617,214
undecorate function names with visual studio sdk
To undecorate mangled C++ names that Visual Studio generates, you can use undname.exe. But what if you want to avoid the overhead of creating a full-blown process every time you need undecoration? Is there any equivalent functionality in the Visual Studio SDK (should be supported in VS2005)?
You're looking for UnDecorateSymbolName function provided by dbghelp.
1,617,286
1,671,205
Easy check for unresolved symbols in shared libraries?
I am writing a fairly large C++ shared-object library, and have run into a small issue that makes debugging a pain: If I define a function/method in a header file, and forget to create a stub for it (during development), since I am building as a shared object library rather than an executable, no errors appear at compi...
Check out the linker option -z defs / --no-undefined. When creating a shared object, it will cause the link to fail if there are unresolved symbols. If you are using gcc to invoke the linker, you'll use the compiler -Wl option to pass the option to the linker: gcc -shared ... -Wl,-z,defs As an example, consider the f...
1,617,370
1,617,395
How to use alpha transparency in OpenGL?
Here's my code: void display(void); int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGBA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable( GL_BLEND ); glutInitWindowSize(600,600); glutInitWindowPosition(200,50); glutCreateWindow("gl...
Just a guess, but could it be that you dont have a background color ? So, when your rendering the second vertex which has alpha 0.1, there is no background to compute the proper color ? Just a guess, been years since i used opengl.
1,617,375
1,617,407
Member function overriding accross class hierarchy
I have defined a class A and derived a new class B from A . I have overloaded SetData() function in class B. When I tried to access SetData function of class B using object of B, compiler doesn't permit it. Why is it so ? class A{ public : void SetData(); }; class B : public A { public: void SetD...
OMG, no error message. -1 for you. But let us use telepathy and guess your error message. You're getting something like "symbol not found" because you try to call a function B::SetData() which doesn't have a body. And it must have a body even if it does nothing and even if it's declared in parent class! Try adding ...
1,617,699
1,618,041
How to obtain all subsequence combinations of a String (in Java, or C++ etc)
Let's say I've a string "12345" I should obtain all subsequence combinations of this string such as: --> 1 2 3 4 5 --> 12 13 14 15 23 24 25 34 35 45 --> 123 124 125 234 235 345 --> 1234 1235 1245 1345 2345 --> 12345 Please note that I grouped them in different number of chars but not changed their order. I need a met...
You want a powerset. Here are all the questions on StackOverflow that mention powersets or power sets. Here is a basic implementation in python: def powerset(s): n = len(s) masks = [1<<j for j in xrange(n)] for i in xrange(2**n): yield [s[j] for j in range(n) if (masks[j] & i)] if __name__ == '__m...
1,617,746
1,617,828
QDesktopServices::openUrl with Ressource
How do I open a ressource file (qressource) using the command QDesktopServices::openUrl ? I tried several ways, but none seemed to work (for instance QDesktopServices::openUrl(QUrl(tr(":ressource.pdf")));) Thank you.
Unfortunately you can't do it directly, save it to a file first. I check the Qt source. This is because the url is passed to the browser or other application (depending on the protocol) directly. These applications will not see your resource because thay are in a different process. Here is the related source: qdes...
1,617,856
1,657,397
Choosing between WPF, wxWidgets, Win32 API and MFC
Imagine you are on Windows 7 and you have to write a GUI for a GRAPHIC application, (like a terrain editor, mesh viewer ..) which involves a great use of DirectX and OpenGL (so written in native C++). If your goal is a multi-platform software then you should go for wxWidgets, but imagine you're doing a Windows' only ap...
RAD Studio can also make the job Enhanced in 2010! VCL (Visual Component Library) for rapidly building Microsoft Windows applications now includes seamless Windows 7 support, and graceful fallback compatibility with Windows Vista, XP, and 2000 Enhanced in 2010! Windows Vista and Windows 7 API headers to fully exploit ...
1,617,896
1,617,904
Case insensitive search in Unicode in C++ on Windows
I asked a similar question yesterday, but recognize that i need to rephase it in a different way. In short: In C++ on Windows, how do I do a case-insensitive search for a string (inside another string) when the strings are in unicode format (wide char, wchar_t), and I don't know the language of the strings. I just want...
Boost String Algorithms has an icontains() function template which may do what you need.
1,617,984
1,618,520
Error: Compiling simple PjSIP program under ubuntu
I am trying to compile simple PjSIP program under ubuntu. I am getting error as /usr/bin/ld: cannot find -lpjsua-i686-pc-linux-gnu What does it mean? Here is the ouput:- root@mypc-desktop:/home/mypc/pjsip# make gcc -o myapp myapp.cpp -DPJ_AUTOCONF=1 -O2 -I/home/mypc/pjproject-1.4.5/pjlib/include -I/home/mypc/pjproj...
It seems that the pj* can't build the neccessary libaries - for a simple fix try to locate the line in /home/mypc/pjproject-1.4.5/build.mak where -Werror is added to $(APP_CFLAGS) and remove it (the -Werror, not the whole line if other flags are added :). Alternatively apply the fix suggested by gcc on line 230 in src/...
1,618,050
1,618,067
C++ as first language for Windows game programming?
I'm a hobbyist programmer with a fair grasp of Python and I'm currently learning C. Recently I was talking to a colleague who also wants to learn to program. In his case, he wants to learn C++ as a path to Windows game programming using DirectX. Personally, I feel diving straight into C++ as your first language is a bi...
C++ should be fine. I think he is best off learning about memory management, pointers, etc. BEFORE jumping up to C# as he will understand how the program is working better. Otherwise, he will just see memory as being magic and the garbage collector will have no real meaning. It's always good to have a solid understa...
1,618,196
1,618,290
where should I put my test code for my class?
So I've written a class and I have the code to test it, but where should I put that code? I could make a static method Test() for the class, but that doesn't need to be there during production and clutters up the class declaration. A bit of searching told me to put the test code in a separate project, but what exactly ...
Whether you are using a test framework (I highly recommend doing so) or not, the best place for the unit tests is in a separate assembly (C/C++/C#) or package (Java). You will only have access to public and protected classes and methods, however unit testing usually only tests public APIs. I recommend you add a separat...
1,618,240
1,618,259
How to support both IPv4 and IPv6 connections
I'm currently working on a UDP socket application and I need to build in support so that IPV4 and IPV6 connections can send packets to a server. I was hoping that someone could help me out and point me in the right direction; the majority of the documentation that I found was not complete. It'd also be helpful if you ...
The best approach is to create an IPv6 server socket that can also accept IPv4 connections. To do so, create a regular IPv6 socket, turn off the socket option IPV6_V6ONLY, bind it to the "any" address, and start receiving. IPv4 addresses will be presented as IPv6 addresses, in the IPv4-mapped format. The major differen...
1,618,280
1,618,297
Where can I set path to make.exe on Windows?
When I try run make from cmd-console on Windows, it runs Turbo Delphi's make.exe but I need MSYS's make.exe. There is no mention about Turbo Delphi in %path% variable, maybe I can change it to MSYS in registry?
The path is in the registry but usually you edit through this interface: Go to Control Panel -> System -> System settings -> Environment Variables. Scroll down in system variables until you find PATH. Click edit and change accordingly. BE SURE to include a semicolon at the end of the previous as that is the delimiter,...
1,618,524
1,618,595
Overload bracket access and assignment C++
I'm writing a hash table for my data structs class, and I'd like to add a little syntactic sugar to my implementation. template <typename HashedObj, typename Object> Object & Dictionary<HashedObj, Object>::operator[](HashedObj & key) { return items.lookup(key); } That works fine when I do something like cout << dic...
It is not clear what exactly you are asking here. The code that you presented already supports assignment. Just do it and at will work (or at least it should compile). It makes absolutely no difference which side of the assignment operator your overloaded [] is used on. It will work in exactly the same way on left-hand...
1,618,551
1,618,555
Compiler error when using nested operator overloading in C++
I have a URL class that overloads the ==, <, >, and != operators for simple comparison. The URL class has a string data member and some functions to act on the string. The operators work fine when tested with the URL class. I also have a Page class that has a URL data member. I am trying to overload the same operators...
It should have been: bool URL::operator ==(const URL & u) const { //url is the string instance variable return url == u.GetURL(); } And analogously for the other operators. If you still get compiler errors, perhaps you haven't made GetURL() const as well: std:string URL::GetURL() const { // whatever... }
1,618,591
1,618,621
How to delta encode a C/C++ struct for transmission via sockets
I need to send a C struct over the wire (using UDP sockets, and possibly XDR at some point) at a fairly high update rate, which potentially causes lots of redundant and unnecessary traffic at several khz. This is because, some of the data in the struct may not have changed at times, so I thought that delta-encoding the...
UDP does not guarantee that a given packet was actually received, so encoding whatever you transmit as a "difference from last time" is problematic -- you can't know that your counterpart has the same idea as you about what the "last time" was. Essentially you'd have to build some overhead on top of UDP to check what ...
1,618,798
1,618,815
Why is there a different string class in every C++ platform out there?
While I like programming in C++, I hate the idea of: std::basic_string vs QString vs wxString vs ............. Doesn't the standard string class satisfy the needs for these frameworks? I mean what is wrong with the standard string class?! Just to emphasize, that below is the important question: Do you learn "the" strin...
The reason for multiple string classes is that the C++ standard was finalized fairly late (in 1998); it then took some time until all systems actually provided a correct C++ library. By that time, all these competing string classes where already written. In addition, in some cases, people want to inherit from a single ...
1,618,811
1,619,215
Do all Standard C++ features work in C++/CLI?
If I just include existing Standard C++ class in C++/CLI program, will it work? In my tests everything worked pretty good, but is it true for every program?
That is what Microsoft promises, yes. (I watched this video yesterday, in which they explicitly mentioned this -- specifically because the addition of nullptr in C++0x would compromise it) So yeah, if you take a native C++ program and compile it as C++/CLI, with no code changes, then yes, it will still work. And of cou...
1,618,828
1,622,693
WCF (WCF-Binding) in/with C/C++
Is thare any like WCF libs (OpenSourse) written in C\C++? Or at least some kined of special WCF C++ services (NOT ON Basic HTTP Binding)?
Sounds like what you're looking for is a C++-based library for exposing and consuming web-services supporting the WS-* protocols (i.e. like WS-Security). In that case, you could probably give Axis2/C a try. It's the C version of the normal Java-based Axis2 from Apache. (There's also Axis/CPP, but not sure how up-to-dat...
1,618,917
1,618,990
Receiving packets in UDP
Let's say my program sends a 1000 bytes over the network (UDP). Does it guaranteed that the receiver will receive the 1000 bytes in one "batch"? Or perhaps he will need to perform sevral "reads" until he'll receive the entire message? if the later is true, how can i ensure that the order of the packets for the same mes...
You will get it all or nothing. But there is no particular guarantee that you will receive packets exactly once in the order they were transmitted; packet loss, reordering and (less often) duplication are all possible. There is a maximum frame size (of 65,507 bytes), send()ing packets of larger sizes will return an err...
1,619,263
1,619,264
Networking in C/C++?
I am a begginer C++ programmer. In C#, I used the System.Net.Sockets.Socket class, which represents a networking socket, to create/connect a server. How can I do the same thing in C/C++? Are there any classes like this?
In windows theres a library called winsock.dll. In Unix, you can use unix sockets Then, theres boost sockets beej guide to internet sockets windows sockets boost networking
1,619,392
1,619,473
Game programming structure
I've been programming in c++ for a bit now and Im very familiar with the syntax. I'm trying to use Allegro to make a card game. I understand everything I need to do for the game logic and what not. What puzzles me is how to drive the game. I'm sort of new to loop based applications. I got used to event based programmin...
Most gaming frameworks provide two methods you need to implement (both of them are called in a loop): Update Draw The Update is where you should put all that stuff, which should check for User input, state changes, intervalled actions etc. Examples would be Physics, ButtonPressed, etc. Nothing prevents you from work...
1,619,522
1,619,738
How to get text indent (tabs) from some text input?
For example, suppose I'm editing following text (\t is for tabs, it's not text) '\t\t\tSome text...' and my input keyboard position is right before 'S' (there is no selected text) and I want to get number of tabs before 'S' (in this case it's 3) So how to get that number of tabs using Win32 API? p.s. Maybe some functio...
For some applications such as the standard Windows Notepad, it may be possible to do this from another application. Notepad itself is little more than big Win32 "Edit" control inside a resizeable window, so all the regular Win32 Edit control messages can be used to get the actual text and the caret position and so on. ...
1,619,604
1,619,620
Reading through file using ifstream
I am trying to read from file: The file is multiline and basically i need to go over each "word". Word being anything non space. Sample input file would be: Sample file: test 2d word 3.5 input { test 13.5 12.3 another { testing 145.4 } } So I tried someth...
You open a file 'inFile' but are reading from the 'std::cin' any particular reason? /* * Open the file. */ std::ifstream inFile(fajl.c_str()); // use input file stream don't. // Then you don't need explicitly specify // that input fla...
1,619,631
1,619,685
c++ hex number format
I'm trying to output the hex value of a char and format it in a nice way. Required: 0x01 : value 0x1 All I can get is: 00x1 : value 0x1 // or 0x1 if i don't use iomanip Here's the code i have, 'ch' was declared to be a unsigned char. Is there any other way to do it other than checking the value and m...
std::cout << "0x" << std::noshowbase << std::hex << std::setw(2) << std::setfill('0') << (int)ch; Since setw pads out to the left of the overall printed number (after showbase is applied), showbase isn't usable in your case. Instead, manually print out the base as shown above.
1,619,643
1,619,646
XCode will not take input from a file
For some reason, Xcode will not take input from a file, while Visual C++ will. When I run this program in xcode, the variables numberRows and numberCols stay 0 (they are initialized to 0 in the main function). When I run it in Visual C++ they become 30 and 30 (the top line of maze.txt is "30 30" without the quotes)....
There is something else wrong. Unfortunately it is hard to tell. Try flushing the output to make sure you get the error message: void readIn(int &numberRows, int &numberCols, char maze[][100]) { ifstream inData("maze.txt"); if (!inData) // Check for all errors. { cerr << "Could not open file. Abor...
1,619,653
1,619,660
Can I mix C++ and C in a single project in Visual Studio?
I have a a Win32 DLL project in VS2008, it is written in a handful of C modules. Because I also want to be able to build outside VS2008, with no dependency on VS2008, I have produced a custom makefile, that does all the build and link steps. All this is set up just fine. Now I'd like to add a couple C++ modules to thi...
First of all, you shouldn't even need /Tc if you're building it yourself - cl.exe uses file extension to determine the type, so .c files will be compiled as C by default, and .cpp and .cxx files as C++. For VS projects, it works in exact same way, except that you can't override this behavior (or at least I do not know ...
1,619,732
1,629,341
How to assign a value to an enum based on input from a file in C++?
I have a file with values like: START and STOP. I also have the following enum declared: enum Type { START, STOP }; I'm trying to set the enum equal to the first value in the file with something like this: enum Type foo; ifstream ifile; ifile.open("input.txt"); ifile >> foo; I'm getting the error: no match ...
I've found for my particular situation that the following code is the best solution: template <class T> T a2e(string c, const string a[], const int size) { for (int i=0; i < size; i++) { if (c == a[i]) { return static_cast<T>(i); } } } And would be used as follows: enum StateType {S...
1,619,748
1,619,820
Enumerate the VCL controls in a external application
is possible via the Windows API's to enumerate and iterate the VCL controls on a form (TForm) belonging to a external Win32 application written in C ++ Builder or Delphi. Bye.
No. First of all, consider that the Windows API has no idea what the "VCL" is. It doesn't know "TButton" or "TStringGrid," and it certainly doesn't know "TImage" or "TLabel," which don't even have window handles. You could use EnumChildWindows to get handles to the windowed controls. You could look at their class names...
1,619,754
1,619,761
Is DbgHelp.dll built-in to Windows? Can I rely on it being there?
I use Jochen Kalmbach's StackWalker class from CodeProject, to produce a stacktrace when an exception occurs in my DLL. It relies on DbgHelp.dll Is DbgHelp.dll built-in to Windows Vista, WS2008, Windows 7? I know about The Debugging Tools for Windows from Microsoft, and I'm aware that DbgHelp.dll ships in that packag...
Microsoft says: "The DbgHelp library is implemented by DbgHelp.dll. This DLL is included in the operating system." Note that the version currently included with Debugging Tools for Windows may not be the same version that is included with the operating system.
1,619,769
1,619,779
Is there a way to call an object's base class method that's overriden? (C++)
I know some languages allow this. Is it possible in C++?
Yes: #include <iostream> class X { public: void T() { std::cout << "1\n"; } }; class Y: public X { public: void T() { std::cout << "2\n"; X::T(); // Call base class. } }; int main() { Y y; y.T(); }
1,619,797
1,619,808
C++ HashTable Question
If I use an array of linked list to implement a hash table, the "remove" function might require traversing through a "chain." Is this also true for "deleting"?
Sure, it applies to anything you try to do with the hash table. Remove, delete (which sound like the same thing to me), insert, search, you name it.
1,619,831
1,619,837
Can you chain methods by returning a pointer to their object?
My goal is to allow chaining of methods such as: class Foo; Foo f; f.setX(12).setY(90); Is it possible for Foo's methods to return a pointer to their instance, allowing such chaining?
For that specific syntax you'd have to return a reference class Foo { public: Foo& SetX(int x) { /* whatever */ return *this; } Foo& SetY(int y) { /* whatever */ return *this; } }; P.S. Or you can return a copy (Foo instead of Foo&). There's no way to say what you need without more details,...
1,619,989
1,716,923
Visual Studio 2008 c++ conditional template inheritance bug?
I'm in the process of porting a C++/WTL project from Visual Studio 2005 to VS 2008. One of the project configurations is a unit-testing build, which defines the preprocessor symbol UNIT_TEST. In order to get my WTL classes into my test harness, I made a CFakeWindow class that stubs all the CWindow methods. Then in my s...
This might be a clearer way of handling it: #ifdef UNIT_TEST #include "fakewindow.h" #define TWindow CFakeWindow #else #define TWindow CWindow #endif Perhaps there's a case where the redefine is not getting through the precompiled headers. If so, this will catch any such problem.
1,619,993
1,620,012
Template specialization for enum
Is it possible to specialize a templatized method for enums? Something like (the invalid code below): template <typename T> void f(T value); template <> void f<enum T>(T value); In the case it's not possible, then supposing I have specializations for a number of types, like int, unsigned int, long long, unsigned long...
You can use std::enable_if with std::is_enum from <type_traits> to accomplish this. In an answer to one of my questions, litb posted a very detailed and well-written explanation of how this can be done with the Boost equivalents.
1,620,079
1,620,381
Passing around a nested functor (C++)
Is there a way to pass foo_ around outside of main? I saw something about Boost in another question regarding functors. That looks like it may work. Here's the answer mentioning Boost in that question. If I can, I would like to avoid Boost. #include <iostream> int main() { class foo { public: void ...
No, currently local types aren't allowed to go into templates (otherwise you could've used boost or std::tr1::function). However, you could maybe do it OOP, where Foo inherits something (that has a virtual opeator() func that your foo implemen ts) and you pass a ptr to Foo around instead.
1,620,218
1,620,449
Free tools that automatically reformat whole C/C++ source files in VS2008 on save?
I'm looking for a tool (macro, extension) for Visual Studio 2008 that would reformat the source code (C/C++) when you save the file.
AStyle was my first hit on Google. Looks reasonable. You can tie that to a keyboard event under 'External Tools' in Visual Studio. (I suspect writing/recording a small macro that formats and saves the file is easy, as is rebinding that to Ctrl-S) See also https://stackoverflow.com/questions/841075/best-c-code-formatter...
1,620,854
1,620,871
C++ library for making GUIs
I am looking for a simple C++ library for making GUIs. I tried wxWidgets and GTK, but I think both are complex. I want your opinion on what to use. Should I learn wxWidgets or you know a better one? Thanks.
Try Nokia's QT. It's free, awesome and cross platform. If you only need to support Windows, then you can check MFC or even better IMHO Windows Forms (with Managed C++).
1,621,077
1,686,247
Strange behaviour of edit control background color when using WinXp common controls
I am having a strange problem ( well, at least i find it strange =) ). I am writing my own GUI library, which is a wrapper around windows api (and yes, i am aware of WTL and frameworks like MFC =) ). At the current stage i have incapsulated common controls in such manner: for example, Edit class consists of a simple wi...
Well, everything is much easier, than i thought. I was just too inattentive =( When one don't use styling, one cane use ::SetBkColor(...) to change background colour, and return a brush from WM_CTLCOLOR* to change a border colour. Things become different after enabling styling. Now ::SetBkColor(...) correspond to focus...
1,621,301
1,820,946
Javascript receives ActiveX event only once
I've written an ActiveX control using ATL. I used the wizard to add support for connection points which added public IConnectionPointContainerImpl<CActiveX> and CProxy_IActiveXEvents<CActiveX>, where the CProxy_... is the wizard generated code to fire events. I've defined a dispinterface as follows: [ uuid(4...
If anyone is interested, I found the solution to this problem. I had registered the object in the ROT (running object table), but was not revoking any previously existing registrations. Thus, multiple registrations were appearing. Once I ensured I revoked previous registrations, events fired reliably.
1,621,446
1,621,721
Automate pimpl'ing of C++ classes -- is there an easy way?
Pimpl's are a source of boilerplate in a lot of C++ code. They seem like the kind of thing that a combination of macros, templates, and maybe a little external tool help could solve, but I'm not sure what the easiest way would be. I've seen templates that help do some of the lifting but not much -- you still end up nee...
No, there isn't an easy answer. :-( I would think with nearly every OO expert saying "prefer composition over inheritance", there would be language support for making composition a whole lot easier than inheritance.
1,621,574
1,621,664
Can the arguments of main's signature in C++ have the unsigned and const qualifiers?
The standard explicitly states that main has two valid (i.e., guaranteed to work) signatures; namely: int main(); int main(int, char*[]); My question is simple, would something like the following be legal? int main(const unsigned int, const char* const* argv); My tests say 'yes', but I'm unsure of the answer because ...
The C++98 standard says in section 3.6.1 paragraph 2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both the following definitions of main: int ma...
1,621,612
1,621,666
What is the proper way to compare an element of an std::string with a character?
I am not a very experienced C++ programmer, i get a warning when i do the following: if (myString[i] != 'x') { } what is the appropriate way to compare these? thanks for your help!
possibility 1: the int that identifies the element in the array should not be larger than a regular int. possibility 2: If myString is of type std::wstring the appropriate comparison is myString[i] != L'x' (ty popester!)
1,621,621
1,621,644
Learning C++ on Linux or Windows?
Since you 'should' learn C/C++ and as part of 'learn as much languages as possible', i decided to learn C++ in depth. My OS is Windows and my question is should i re-install Linux as a dual boot to learn C++ on Linux? Do i miss something if I develop in C++ only on the Windows platform? (possible duplicate: https://sta...
Doesn't really matter what platform you write your code on. If you want to verify that your code is portable, you could install cygwin and gcc as well as visual studio. Then you could compile with both compilers without having to dualboot
1,621,629
1,621,645
Threading with .NET and OpenCV?
I am having trouble getting a thread to work with OpenCV. The problem is with the ThreadStart() part of my code. public ref class circles { public: static void circleFind(bool isPhoto, const char * windowName1, const char * windowName2, const char * photoName) {(stuff)} }; int main(int argc, char...
The problem here is that you are trying to use a function for a ThreadStart delegate which has an incompatible signature. ThreadStart is a delegate which has no arguments and returns no value. You are trying to use a method though which takes 4 arguments. This won't work. You'll need to instead pass in a method wh...
1,622,044
1,622,074
Unfixable circular dependency
This code gives error C2504: 'IKeyEvent': base class undefined on line 3. class IKeyEvent; class EventDispatcher : private IKeyEvent { public: enum EEActions { A_FEW_ACTIONS }; private: void OnKey(EventDispatcher::EEActions action, char multiplier); } class IKeyEvent { public: virtual void OnK...
My recommendation: move EEActions into the base class - it is part of the interface, after all: class IKeyEvent { public: enum EEActions { A_FEW_ACTIONS }; virtual void OnKey(EEActions action, char multiplier) = 0; }; class EventDispatcher : public IKeyEvent { private: void OnKey(EventDispatche...
1,622,054
1,622,061
C++ - Pointer to a class method
I have to set up a pointer to a library function (IHTMLDocument2::write) which is a method of the class IHTMLDocument2. (for the curious: i have to hook that function with Detours) I can't do this directly, because of type mismatch, neither can I use a cast (reinterpret_cast<> which is the "right one" afaik doesn't wor...
The pointer to function has the following type: HRESULT (WINAPI IHTMLDocument2::*)(SAFEARRAY*) As you can see, it's qualified with it's class name. It requires an instance of a class to call on (because it is not a static function): typedef HRESULT (WINAPI IHTMLDocument2::*DocumentWriter)(SAFEARRAY*); DocumentWriter ...
1,622,117
1,622,140
Move a bitmap around a window quickly in C++
I'm looking for some C++ code to let me quickly move a bitmap around a window, restoring the background as it moves. At present I capture the Window contents to a bitmap during the app initialization and in the OnPaint() I draw the this bitmap and then I draw my overlayed bitmap. I am double buffering the paint. The ov...
Probably your fastest way would be to store your movable image in one bitmap and then maintain a second temporary bitmap of the same size in memory as well. To draw your movable bitmap over your main image, you would first use the BitBlt API function to copy the region you're about to draw the movable bitmap onto into...
1,622,298
1,622,413
How to generate automatic properties (get, set) for Visual Studio 2008 C++
Having read this question on generating getters and setters in Visual Studio and tried (somewhat) the techniques described, I have failed miserably to graduate beyond the longhand way of writing Getters and Setters. While I recognize the conceptual advantage of encapsulation (private members of a class in this case), ...
Thanks @Dan for pointing out this trick in Microsoft Compiler (non-portable) Here is the way: struct person { std::string m_name; void setName(const std::string& p_name) { m_name = p_name; } const std::string& getName() const { return m_name; } // Here is the name of the ...
1,622,546
1,622,551
Constructor abort constructing
I would like to have the constructor abort object construction whenever it encounters certain error code (e.g. if the following is encountered): CudaObj::CudaObj(InsertionSim *theSim) { // Setup if(cublasInit() == CUBLAS_STATUS_NOT_INITIALIZED) { printf("CUBLAS init error.\n"); return -1; // ab...
I think the idiomatic way is to throw an exception from the constructor to emphasize that the object is not in a valid state.
1,622,592
1,622,623
Atomic delete for large amounts of files
I am trying to delete 10000+ files at once, atomically e.g. either all need to be deleted at once, or all need to stay in place. Of course, the obvious answer is to move all the files into a temporary directory, and delete it recursively on success, but that doubles the amount of I/O required. Compression doesn't work,...
Kibbee is correct: you're looking for a transaction. However, you needn't depend on either databases or special file system features if you don't want to. The essence of a transaction is this: Write out a record to a special file (often called the "log") that lists the files you are going to remove. Once this record ...
1,622,694
1,625,024
Is it possible to have a non-template class subclass a template class?
I have a template class defined like so: template <class T> class Command { public: virtual T HandleSuccess(std::string response) = 0; virtual std::string FullCommand() const = 0; // ... other methods here ... }; Will C++ allow me to create a non-template subclass of a template class? What I mean is can I ...
litb found the solution on ##c++ last night. The issue was I was passing a NoopCommand to a function like this: void SendCommand(Command<T> command); When I should have made the signature this: void SendCommand(Command<T>& command); Making that change allows everything to compile.
1,622,817
1,623,697
Using the mod operator C++
Without using any stls, boosts, and the like I have been trying to rotate the elements in my array. I've been trying to use the mod operator, to be efficient: void stack::rotate(int r) { r = ( r % maxSize + maxSize ) % maxSize; for ( int first_index = 0; first_index < r; ++first_index ) { int mem = items[first_ind...
Tips: Add assertions (r is positive, nonzero?, less than maxsize, maxsize is nonzero, etc.) Write tests for this function, starting from an easy array and going up. Do not throw them away - keep them written and run all of them in a row. Give clear names to variables. Do not reuse r. Your code looks a bit too obscure f...
1,622,936
1,664,866
How to export Visual Studio project to Qt?
I wonder how can I export a Visual Studio C++ project to Qt? I am using openCV and OpenMP so I would like to know about setting these libraries in Qt.
Answer to myself. Visual Studio is capable to export the current project to a make file so. File>Export to make file should work. (I got this info form microsoft msdn site. So, it should work)
1,623,010
1,623,084
Cleaner pointer arithmetic syntax for manipulation with byte offsets
In the following lines of code, I need to adjust the pointer pm by an offset in bytes in one of its fields. Is there an better/easier way to do this, than incessantly casting back and forth from char * and PartitionMap * such that the pointer arithmetic still works out? PartitionMap *pm(reinterpret_cast<PartitionMap *>...
I often use these templates for this: template<typename T> T *add_pointer(T *p, unsigned int n) { return reinterpret_cast<T *>(reinterpret_cast<char *>(p) + n); } template<typename T> const T *add_pointer(const T *p, unsigned int n) { return reinterpret_cast<const T *>(reint...
1,623,103
1,623,112
Questions about C++ memory allocation and delete
I'm getting a bad error. When I call delete on an object at the top of an object hierarchy (hoping to the cause the deletion of its child objects), my progam quits and I get this: *** glibc detected *** /home/mossen/workspace/abbot/Debug/abbot: double free or corruption (out): 0xb7ec2158 *** followed by what looks like...
What happens if load() is never called? Does your class constructor initialise heightmap, or is it uninitialised when it gets to the destructor? Also, you say: ... delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete. However, you haven't taken into co...
1,623,197
1,623,208
Receiving data in TCP
If i send 1000 bytes in TCP, does it guarantee that the receiver will get the entire 1000 bytes "togther"? or perhaps he will first only get 500 bytes, and later he'll receive the other bytes? EDIT: the question comes from the application's point of view. If the 1000 bytes are reassembles into a single buffer before th...
See Transmission Control Protocol: TCP provides reliable, ordered delivery of a stream of bytes from a program on one computer to another program on another computer. A "stream" means that there is no message boundary from the receiver's point of view. You could get one 1000 byte message or one thousand 1 byte messa...
1,623,250
1,623,296
std::regex -- is there some lib that needs to be linked?
I get a linker error with the following code: #include <regex> int main() { std::regex rgx("ello"); return 0; } test.o: In function `basic_regex': /usr/lib/gcc/i586-redhat-linux/4.4.1/../../../../include/c++/4.4.1/tr1_impl/regex:769: undefined reference to `std::basic_regex<char, std::regex_traits<char> >::_M...
From gcc-4.4.1/include/c++/4.4.1/tr1_impl/regex template <...> class basic_regexp { ... private: /** * @brief Compiles a regular expression pattern into a NFA. * @todo Implement this function. */ void _M_compile(); I guess it's not ready yet. UPDATE: current bleeding edge GCC (SVN @...
1,623,378
1,623,418
Trying to create a Math Input Panel in C#
How do I create a Math Input Panel in C#? I have tried to put it into a dll and call it but it just closes right away. #include <stdafx.h> #include <atlbase.h> #include "micaut.h" #include "micaut_i.c" extern "C" __declspec(dllexport) int run() { CComPtr<IMathInputControl> g_spMIC; // Math Input Control HRESULT...
In your C# project, add a reference to the COM library micautLib. Then you can use the following code (in C#): MathInputControl ctrl = new MathInputControlClass(); ctrl.EnableExtendedButtons(true); ctrl.Show(); I'm not sure if this is exactly how you're supposed to do it, but this seems to work cleanly (complete progr...
1,623,427
1,623,484
How to find whether system has the font I needed in MFC?
I want to write the following function bool IsFontExistInSystem(const CString& fontStyle) const { } Is there any API in windows to do this? Many Thanks!
Here's some old code I dug out that will check if a font is installed. It could do with being tidied up but you get the idea: static int CALLBACK CFontHelper::EnumFontFamExProc(ENUMLOGFONTEX* /*lpelfe*/, NEWTEXTMETRICEX* /*lpntme*/, int /*FontType*/, LPARAM lParam) { LPARAM* l = (LPARAM*)lParam; *l = TRUE; ...
1,623,455
1,623,627
sendto fails with a non administrator user with errorcode 10013
I found more source codes which are working like ping. My only problem with them is, that if i run the program with a non administrative user, then i get back errorcode 10013 which means : "An attempt was made to access a socket in a way forbidden by its access permissions." If i run the program with a user which is me...
If you want to implement ping functionality in your application on Windows, then you should have a look at the IcmpSendEcho2 function instead of trying to use raw sockets.
1,623,575
1,623,614
operator= (T *r) in nested templates
I have a problem concerning nested templates and the overriding of the assignment operator. Say i want to have a refcounting class template _reference. This _reference for now simply holds a pointer to the ref-counted object. The problem now is that this all works fine, as long as im doing this with simple classes or...
The base operator= gets hidden by implicit assignment operators, so that it doesn't take part in the overloading anymore. You need to write _ref_vector as template <typename T> class _ref_vector : public _reference<vector<T> > { using _reference<vector<T> >::operator=; }; As there is no compiler-added version of sim...
1,623,687
1,623,739
OS API allocates members in struct. Free just the struct or every member first?
Let's say we have an array of PRINTER_INFO_2 like this: PRINTER_INFO_2* printers = (PRINTER_INFO_2*)malloc(sizeof(PRINTER_INFO_2) * 64); // room for 64 items Then we call EnumPrinters() to get a list of locally installed printers: EnumPrinters( PRINTER_ENUM_LOCAL, NULL, 2, (LPBYTE)printers, ...); ...
IIUC, you need to overallocate the buffer beyond the size of the structure, to accommodate for any output strings as well. EnumPrinters will tell you if the memory block was too small. As you can't know upfront how much memory you will need, you typically call it twice: once to learn the amount of memory needed, and th...
1,623,735
1,623,823
Calculate the first day of a calendar week
I need to calculate the date of the first day in a calendar week, e.g. Week 1 in 2009 -> Mon, 29.12.2008 (!) Week 44 in 2009 -> Mon, 26.10.2009 I have some ugly code for this, but I would prefer a nice C++ lib. Any suggestions?
what about boost::gregorian::date with its algorithms ?
1,623,759
1,623,893
C-DLL from C++ source
I have a C-Wrapper for my C++ Framework. Since this should run on mac and windows I am using scons: env = Environment() env.Append(CPPPATH = ['./']) env.Append(LIBS = 'kernel32.lib') env.Append(LIBPATH = 'C:/Program Files/Microsoft SDKs/Windows/v6.0A/Lib') env.SharedLibrary(target='warpLib', source='warplib.cpp') Sim...
You should only need extern "C" on the declaration. Anyone then including that header will expect to link against it using the C linking standard, rather than the C++ decorated form. The warplib.cpp source file, and subsequent object file will expose the function foo correctly if warplib.h is included. When using MSVC,...
1,623,769
1,623,787
Is there any safe strcmp?
I made a function like this: bool IsSameString(char* p1, char* p2) { return 0 == strcmp(p1, p2); } The problem is that sometimes, by mistake, arguments are passed which are not strings (meaning that p1 or p2 is not terminated with a null character). Then, strcmp continues comparing until it reaches non-accessibl...
No, there's no (standard) way to tell whether a char * actually points to valid memory. In your situation, it is better to use std::string rather than char *s for all your strings, along with the overloaded == operator. If you do this, the compiler would enforce type safety. EDIT: As per the comments below if you find ...
1,623,975
1,624,013
AMD multi-core programming
I want to start to write applications(C++) that will utilize the additional cores to execute portions of the code that have a need to perform lots of calculations and whose computations are independent of each other. I have the following processor : x64 Family 15 Model 104 Stepping 2 Authentic AMD ~1900 Mhz running on...
OpenMP and TBB are both available also for AMD - it is also a compiler question. E.g. see linux TBB on AMD. I think the latest development on this end is to use the graphic card via CUDA or similar APIs- but this depends on the nature of your calculations. If it fits, it is faster than the CPU anyway.
1,624,109
1,624,133
Is type specifier required for const?
Is a type specifier required here? const c = 7; Bjarne Stroustrup's 'The C++ Programming Language' on page 80 says that this is illegal. However, I've been practicing some brainbench tests, and one of the questions states that the type defaults to int. Brainbench is usually correct, so I'm unsure of which reference is...
The default type of int is valid for C, but not for C++. Even in C this style of coding should be avoided. Also note that Bjarne Stroustrup's book is one of the most authoritative reference for standard C++.
1,624,564
1,624,676
Access protected member of a class in a derived class
i have an old codebase here, where they used protected member variables. Whether or not this is a good idea can be discussed. However, the code must have compiled fine with gcc3. I have a derived template class Bar that uses protected member x from class template Foo like so template <class Something> class Foo { pu...
The expression x used in the derived class is, by the rules in the standard, not dependent on any template parameter of the derived class. Because of this, lookup happens in the context of the template definition and not at the point of use/instantiation. Even though the template base class of the template appears to b...
1,624,648
1,624,826
Can I use a C style library built with VC6 directly in VC9 project?
We use an internal library(developed by some other team) built with VC6 compiler. This library mainly contains C Style APIs. We have a plan to migrate to Visual Studio 9 compiler. Should I request for the library to be built with VC9 compiler? A more generic question, On which points ( may be name mangling, optimizati...
Conflict usually occurs in C Runtime library. The main idea is that memory should be deallocated in module where it was allocated. Then it will be safe to use library that was built with different version of compiler. Another problem is packing of structs, but it has no difference if you use only Visual C++ compiler. N...
1,624,762
1,625,184
C++ Win32 -- COM Method: equivalent C declaration
I've been told that every COM method callable from C++ code (take for instance IHTMLDocument2::write) has an equivalent C declaration, usable from C code... How do I find it? Thanks in advance!
This particular interface is documented as being provided by <mshtml.h>. Now, as it happens the second and third line of that file are: // Include the full header file that works for C #include "mshtmlc.h" Looking into that file, we find the declaration /* [id][vararg] */ HRESULT ( STDMETHODCALLTYPE *write )( ...
1,624,803
1,624,815
Does resizing a vector invalidate iterators?
I found that this C++ code: vector<int> a; a.push_back(1); a.push_back(2); vector<int>::iterator it = a.begin(); a.push_back(4); cout << *it; print some big random number; but if you add a.push_back(3) between 3rd and 4th lines, it will print 1. Can you explain it to me?
Edited with more careful wording yes, resizing a vector might invalidate all iterators pointing into the vector. The vector is implemented by internally allocating an array where the data is stored. When the vector grows, that array might run out of space, and when it does, the vector allocates a new, bigger, array, c...
1,624,905
1,656,972
Using Boost Python with Weak Ptrs?
Trying to set up a dependency in C++ with a parent-child relationship. The parent contains the child and the child has a weak pointer to the parent. I would also like to be able to derive from the parent in Python. However, when I do this, I get a weak pointer error connecting up this parent-child relationship. C++ cod...
I played with the code without the python stuff. This reproduced the problem: Parent* p(new Parent); p->initialize(); The problem is nothing is holding on to the shared_ptr object. This fixes it: boost::shared_ptr<Parent> p(new Parent); p->initialize(); Boost.Python FAQ : "When a shared_ptr is converted from Python, ...
1,625,105
1,956,217
How to write `is_complete` template?
After answering this question I was trying to find is_complete template in Boost library and I realized that there is no such template in Boost.TypeTraits. Why there is no such template in Boost library? How it should look like? //! Check whether type complete template<typename T> struct is_complete { static const...
The answer given by Alexey Malistov can be used on MSVC with a minor modification: namespace { template<class T, int discriminator> struct is_complete { static T & getT(); static char (& pass(T))[2]; static char pass(...); static const bool value = sizeof(pass(getT()))==2; ...
1,625,299
1,625,387
Processing huge text files
Problem: I've a huge raw text file (assume of 3gig), I need to go through each word in the file and find out that a word appears how many times in the file. My Proposed Solution: Split the huge file into multiple files and each splitted file will have words in a sorted manner. For example, all the words starting with "...
You need to look at 'The Practice of Programming' by Kernighan and Pike, and specifically chapter 3. In C++, use a map based on the strings and a count (std::map<string,size_t>, IIRC). Read the file (once - it's too big to read more than once), splitting it into words as you go (for some definition of 'word'), and inc...
1,625,362
1,629,183
Will IntelliTrace(tm) (historical debugging) be available for unmanaged c++ in future versions of Visual Studio?
I love the idea of historical debugging in VS 2010. However, I am really disappointed that unmanaged C++ is left out. IntelliTrace supports debugging Visual Basic and C# applications that use .NET version 2.0, 3.0, 3.5, or 4. You can debug most applications, including applications that were created by usi...
According to this MSDN blog post they "hope to fix this limitation in the future."
1,625,422
1,683,286
Where I can find the appWizard that can generate C++ application
I have an project to modify. This project was create with AppWizard many years ago. This generated weird code when I open it with visual studio 8. I would like to modify the interface. Can I find a free AppWizard. Thanks,
After using Visual Studio 6.0 it worked.
1,625,531
1,625,579
C++, WCHAR[] to std::cout and comparision
I need to put WCHAR[] to std::cout ... It is a part of PWLAN_CONNECTION_NOTIFICATION_DATA passed from Native Wifi API callback. I tried simply std::cout << var; but it prints out the numeric address of first char. the comparision (var == L"some text") doesn't work either. The debugger returns the expected value, howev...
Assuming var is a wchar_t *, var == L"some text" does a pointer comparison. In order to compare the string pointed to by var, use a function such as wcscmp.
1,626,036
1,626,053
How do I collapse selected chunks of code in Visual Studio 2008?
In Visual Studio 2008: Is there a way for me to customly collapse bits of code similar to like how I can automatically collapse chunks of comments?
Your piece of code needs to be a block surrounded by, as desired: braces #region and #endregion in C# #pragma region and #pragma endregion in C/C++ If you can't collapse statement blocks, you need to enable this feature : Tools -> Options -> Text Editor -> C/C++ -> Formatting -> check everything in "outlining" (In Vi...
1,626,038
1,626,188
Should an implementor of IShellBrowser::QueryActiveShellView Method call AddRef for the caller?
I am attempting to implement an IShellBrowser. One method of such is: HRESULT STDMETHODCALLTYPE IShellBrowser::QueryActiveShellView(/* [out] */ __RPC__deref_out_opt IShellView **ppshv) This gets the active shell view pointer for the caller (in my case, there is only one shell view at any given time). But it is very u...
Yes, COM has a very detailed contract on this behavior: all [out] parameters must be copied (in the case of value types) or AddRef:ed (in the case of interface pointers). So, you should definitely AddRef.
1,626,116
1,626,174
How to write a class capable of foreach
It's been a while since Visual Studio added support for a foreach extension that works like vector<int> v(3) for each (int i in v) { printf("%d\n",i); } I want to know how to make any class able to use foreach. Do I need to implement some interface?
for each statement in VC++, when used on a non-managed class: for each (T x in xs) { ... } is just syntactic sugar for this: for (auto iter = xs.begin(), end = xs.end(); iter != end; ++iter) { T x = *iter; } Where auto means that type of variable is deduced automatically from type of initializer. In other wo...
1,626,248
1,626,269
Does GCC inline C++ functions without the 'inline' keyword?
Does GCC, when compiling C++ code, ever try to optimize for speed by choosing to inline functions that are not marked with the inline keyword?
Yes. Any compiler is free to inline any function whenever it thinks it is a good idea. GCC does that as well. At -O2 optimization level the inlining is done when the compiler thinks it is worth doing (a heuristic is used) and if it will not increase the size of the code. At -O3 it is done whenever the compiler thinks i...
1,626,673
1,626,723
C++ multiplayer UDP socket API
Can anyone recommend an easy to use, fast and reliable C++ API for sending and receiving data over a UDP socket? Maybe something that is specifcally intended for multiplayer games?
Raknet is amazingly good. So good that is the basis for networking in commercial engines like unity3d. http://www.jenkinssoftware.com
1,626,846
1,626,967
How do I allocate variably-sized structures contiguously in memory?
I'm using C++, and I have the following structures: struct ArrayOfThese { int a; int b; }; struct DataPoint { int a; int b; int c; }; In memory, I want to have 1 or more ArrayOfThese elements at the end of each DataPoint. There are not always the same number of ArrayOfThese elements per DataPoint. Because ...
Since your structs are PODs you might as well do it just as you would in C. The only thing you'll need is a cast. Assuming n is the number of things to allocate: DataPoint *p=static_cast<DataPoint *>(malloc(sizeof(DataPoint)+n*sizeof(ArrayOfThese))); Placement new does come into this sort of thing, if your objects hav...
1,627,152
1,627,845
Can I mix JNI headers implementation with normal C++ classes?
If I try to implement my class on this file I get an error UnsatisfiedLinkError, however if I remove the implementation of the Broker.h Class it goes ok. Why? Broker.h #include "XletTable.h" #ifndef BROKER_H_ #define BROKER_H_ class Broker { private: static Broker* brokerSingleton; static XletTable *table; ...
Probably your library miss reference to some symbol, or another library. Try make some main.cpp with empty main() function, and link it with your library - g++ main.cpp -o main -lInterAppCC. If you miss something, the linker will give you a detailed error message. PS. Since your header file already wraps function proto...
1,627,348
1,627,606
Programmatically move registry keys
Does anyone know how I can programmaically move a registry from HKEY_LOCAL_MCAHINE to HKEY_CURRENT_USER? I wrote a recursive function that uses RegEnumKeyEx and RegEnumValue, but it appears that RegEnumValue returns all of the values under the top level key. For example, if the key is HKEY_LOCAL_MACHINE\SOFTWARE\MyApp\...
Looking through all the registry functions, I found this: SHCopyKey or I can use this: RegCopyTree for Vista and later. Thanks for the help.
1,627,479
1,627,527
Is the use of previously defined members as part of later members in an enum definition legal?
namespace ValueType { enum Enum { Boolean = 0, Float = 1, Double, SInt = 8, SLong, UInt = SInt + (1 <<4), ULong = SLong + (1 << 4) }; }
Yes -- the requirement is that it's an integral constant expression. The C++ standard includes the following example: enum { d, e, f=e+2 };
1,627,866
1,627,870
Instantiating at global level (C++)
I get the following error with the code below. expected constructor, destructor, or type conversion before '=' token -- #include <string> #include <map> class Foo { }; std::map<std::string, Foo> map; map["bar"] = Foo(); int main() { return 0; }
map["bar"] = Foo(); // This line is a statement not a declaration. // You have to put it in main, or any execution context Untill C++0x becomes mainstream, I would suggest using boost. Filling the map becomes piece of cake. Here is an example: std::map<std::string, Foo> mymap; ... int main() { i...
1,628,001
1,628,022
Python, Perl And C/C++ With GUI
I'm now thinking, is it possible to integrate Python, Perl and C/C++ and also doing a GUI application with this very nice mix of languages?
Well, there is Wx, Inline::Python and Inline::C, but the question is why?
1,628,034
1,628,060
GetDlgItemInt( ) problem
Ok, i have 2 edit controls and a button in my main window; in one edit control the user can write a number and when he push the button i read that number and i print it in the other edit control (which is read only). My problem is that when i put a number and i press the button, for some reason that i dont understand i...
The first parameter to GetDlgItemInt should be the handle to the dialog box. Unless the name hwndEdit2 is extremely deceiving, you're currently passing the handle to the edit control itself instead.
1,628,189
1,628,207
Static inline methods?
Okay, Here is what I'm trying to do... Right now it is compiling but failing at linking... LNK2001 I want the methods static because there are no member variables, however I also want them inline for the speedups they provide. What is the best way to do this? Here is what I have in a nutshell: /* foo.h */ class foo ...
If you are calling bar from another cpp file, other than foo.cpp, it needs to be in a header file.
1,628,321
1,628,399
Boost multi-index container with index based on nested values
If I have an object like this: struct Bar { std::string const& property(); }; I can create a multi-index container for it like this: struct tag_prop {}; typedef boost::multi_index_container< Bar, boost::multi_index::indexed_by< boost::multi_index::ordered_non_unique< boost::multi_index:...
I believe you need to create a predicate object that takes two instances of Foo and its operator() can call Foo::bar() on both instances. Something like struct MyPredicate { bool operator() (const Foo& obj1, const Foo& obj2) const { // fill in here } }; and then use ... boost::multi_index::ord...