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
6,868,832
6,877,083
How to create win32 smartpone dll and call by C# DllImport in WinCE
I need to implement a Win32 DLL and need call it by C# DllImport in WinCE. So I create a Win32 Smart Device Project and choice Windows Mobile 5.0 Smartphone SDK, and create a dll project with Export symbols option. Then I add extern "C" key word before function declare: .h #ifdef WINCE2_EXPORTS #define WINCE2_API __dec...
You built this using the Smartphone SDK, which is ARM-based. The CE 5.0 emulator emulated x86, so it's not going to be callable there. If your CE 6.0 device is likewise x86-based, it too is going to have the same problem. Try building it using an x86 SDK.
6,868,993
6,869,067
Dependent variables in C++?
I tried asking before but I wasn't very clear so I'm re-asking it. I want to have a variable that depends on the value of another variable, like b in this example: int main(){ int a; dependent int b=a+1; //I'm just making this up a=3; cout << b; //prints 4 a=4; cout << b; //prints 5 } Of course...
What you need is a closure. If you can use C++ 0x features, you are in luck. Otherwise, you can define one manually: #include <iostream> using namespace std; struct B { const int & a; B(const int & a) : a(a) {} // variable syntax (Sean Farell's idea) operator int () const { return a + 1; } // fun...
6,869,460
6,869,553
OpenGL+GLUT Not filling Topmost-Leftmost Polygon?
I'm encountering a strange OpenGL Bug. OpenGL is pretty new to me, but we're required to use it in my AI class (because the teacher is really a Graphics professor). Either way, this is happening: http://img818.imageshack.us/img818/422/reversiothello.png It happens to only the topmost, leftmost polygon. In other words,...
The only bug worth giving an answer that I can find is that your draw_board function doesn't use properly the glBegin and glEnd statements. You have to use a glEnd statement before calling gl_drawCircle, otherwise you'll get a nasty behavior. Edit: you first circle is drawn using lines because the glBegin is ignored (s...
6,869,780
6,869,869
Template class specialized inside and outside lib
Consider this synthetic example. I have two native C++ projects in my Visual Studio 2010 solution. One is console exe and another is lib. There are two files in lib: // TImage.h template<class T> class TImage { public: TImage() { #ifndef _LIB std::cout << "Created (main), "; #else std::cout << "Created (li...
Template code creates duplicated object code. The compiler copies the template code for the type you provide when you instance the template. So when TImage.cpp is compiled you get object code for two versions of your template, one for char and one for int in TImage.o. Then main.cpp is compiled and you get a new version...
6,869,888
6,869,941
The relationship between auto and decltype
Is auto x = initializer; equivalent to decltype(initializer) x = initializer; or decltype((initializer)) x = initializer; or neither?
decltype also considers whether the expression is rvalue or lvalue . Wikipedia says, The type denoted by decltype can be different from the type deduced by auto. #include <vector> int main() { const std::vector<int> v(1); auto a = v[0]; // a has type int decltype(v[0]) b = 1; // b has type const in...
6,869,940
6,870,040
Shortest conversion from vector to vector of pointer
Is there any shortcut to convert from std::vector<T> to std::vector<T*> or std::vector<T&>? Essentially I want to replace: std::vector<T> source; std::vector<T*> target; for(auto it = source.begin(); it != source.end(); it++) { target.push_back(&(*it)); } with a single line. To provide some context: I have one set o...
Although what you describe sounds strange (without context), using std::transform you could do the actual copying/transformation in one line of code : transform(source.begin(), source.end(), target.begin(), getPointer); given that target has sufficient room for all data (can be achieved with std::vector::resize eg.), ...
6,869,995
6,870,155
Is using a global object as a COM class factory legal?
In an out-proc COM server I need a class factory that I will pass to CoRegisterClassObject(). CreateInstance() will only use new to create object instances and need no stored data. LockServer() will modify shared lock counter not specific to the factory instance. So in fact I don't need to store any distinct data insid...
As long as you control the process lifetime on different mean, this is accepted. delete this in this case is disaster as the object is global not a dynamic one.
6,870,120
6,871,595
Getting to the right stack for an exception
I'm working on an application that has a software watchdog. If some thread locks up, or is in a wait for more than a minute, the watchdog causes an exception in order to pull down the application and restart it. So I'm looking at dumpfiles whose faulting stack is pointing at the watchdog thread. I need to identify th...
In dump files you don't have information you are looking for (cpu usage history), but you can list all threads and examine stack. This will most probably help because the thread that caused the closed should be blocked in wait or something like that
6,870,205
6,870,370
How to get a pointer to a member variable for memcpy
edited for clarification; why wont this work yet compile? class Member{ public: __int32 PublicInt; } Member x; memcpy(&x.PublicInt,&ByteArray,sizeof(__int32)); is this not getting a pointer to the place where int is stored?
Here is a quick sample to help you understand: #include<iostream> #include<cstring> class Myclass { public: char str2[40]; }; int main() { char str1[]="Sample string"; Myclass obj; memcpy(&(obj.str2),str1,strlen(str1)+1); std::cout<<obj.str2; return 0; } Hth :)
6,870,261
6,870,951
Boost.Python: Take possession of argument
If I have a function that takes possession of one of the arguments, are there any call policies that I should use when I expose that function with Boost.Python? void func(MyClass* obj) { // Code that takes possession of `obj` }
I think you can use boost::weak_ptr. using boost::shared_ptr; using boost::weak_ptr; func (weak_ptr<MyClass> wp) { shared_ptr<MyClass> sp = wp.lock (); if (sp) // sp stays alive until it goes out of scope or is reset } Basically, this is the example offered in the documentation of boost::weak_ptr. Here's the ...
6,870,629
6,870,703
Passing/binding arguments when using boost::fusion::for_each
I would like to call a function on all elements of a boost::fusion::vector. The elements are of types like this: class A { ... void print_with_prefix(const char *prefix) { std::cout << prefix << *this; } }; One can call this function on each element in this way: // Call print_with_prefix() on ...
What you did is the right way. C++0x can't help much in that respect because e.g. lambda expressions are not polymorphic, so at the end of the day you'll have to write a template somewhere (which unfortunately must be at namespace scope, even with C++0x), like you did with the operator(). Some libraries like Boost.Phoe...
6,870,635
6,870,810
Cannot link to MySQL libraries for C++
I've been trying to use MySQL and C++ together but can't seem to get started as I cannot seem to gain usage of the relevant libraries. I am on Win7 using MinGW compiler and working in Netbeans. I have the code: #include <cstdlib> #include <iostream> #include <my_global.h> #include <mysql.h> using namespace std; int m...
I'm not sure in Windows, but in Linux you can use the mysql_config tool to get the correct flags to compile a client application: For compiling: $ mysql_config --cflags -I/usr/include/mysql -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX And for linking: $ mysql_config --libs -Wl,-Bsymbolic-functions ...
6,870,649
6,870,812
Are these overloads necessary?
I have to write a library which contains a function that takes two strings parameters: void foo(const std::string& arg1, const std::string& arg2); My library is going to be used by some people that don't like C++ and are only used to const char*. To satisfy their likes, I changed the prototype: void foo(const char* ar...
IMO it's reasonable to have two overloads to handle two different programming styles that co-exist within your organization. Technically it's not just an optimization: the const char* can be extern "C", so might be useful for bindings from other languages, or even from other C++ code across a dll boundary with incompa...
6,870,698
6,870,855
C++ error instantiated from here when using templates
template<class Concept> class OMAbstructContainer { friend class OMIterator<Concept> ; // ... }; template<class Concept> class OMStaticArray : public OMAbstructContainer<Concept> { protected: Concept *theLink; int count; void* AllocateMemory(int size); bool ReleaseMemory(void* ...
There is no visible error from your question. One problematic thing I see is that you are instantiating OMStaticArray<Concept> where Concept = MyVar*; so, Concept *theLink; ==> MyVar **theLink; Now your AllocateMemory() returns void*; Are you sure you want to convert void* into MyVar** ? Due to C-style casting you are...
6,870,765
6,870,804
while(true) vs wait+condition synchronism
Is it a bad practice to put a thread in a while(true) loop and test if a condition is ok to start a treatment? void run() { for(;;) { if(dataReady) { processData(); } } } is it preferable to use wait/condition mechanism : void run() { for(;;) { if(dataRea...
It depends on the amount of time you expect to be waiting. For very short periods a busy-wait can be preferable because it wouldn't involve a context switch as the other technique. The overhead of the context switch may sometimes overweigh the whole busy-wait loop.
6,870,885
6,873,644
How to use extern template
I've been looking through the N3291 working draft of C++0x. And I was curious about extern template. Section 14.7.3 states: Except for inline functions and class template specializations, explicit instantiation declarations have the effect of suppressing the implicit instantiation of the entity to which they refer. F...
It says Except for ...class template specializations So it does not apply to std::vector<int>, but to its members (members that aren't inline member functions and presumably that aren't nested classes. Unfortunately, there isn't a one term that catches both of "class template specialization and specializations of mem...
6,870,890
6,870,996
What is a possible way to bias a random number generator?
I built a word generator, it picks a length and then randomly picks letters of the alphabet to make up words. The program works but 99% of the output is rubbish as it is not observing the constructs of the English language, I am getting as many words with x and z in as I do e. What are my options for biasing the RNG...
The output will still be rubbish because biasing the random number generator is not enough to construct proper English words. But one approach to biasing the rng is: Make a histogram of the occurences of letters in a large English text (the corpus). You'll get something like 500 'e', 3 'x', 1 'q', 450 'a', 200 'b' and...
6,871,537
6,871,969
Share video data between C++ and Python
I have a USB camera (uEye) which has a C++ interface allowing you to configure some features of the camera. The C++ program can read the image data from the camera and store it somewhere in pre-allocated memory. All of this runs under Windows. Python with numpy gives me a simple environment to manipulate images and spe...
There was a recent post on the PyPy blog about real-time video processing. In the example they use mplayer to be grab and display video, which might be preferable to trying to interface with your C++ program (assuming it works with your webcam). If not, thinking along those lines a simple solution is to just connect st...
6,871,739
6,871,801
how to create a dll of my c++ code.
Possible Duplicate: how dll created out of c++ source and how it is used in other sources? I need to call a c++ code, which get the PID/VID of the external device in my java code. I googled and some info. By converting the c++ code to a dll, I can use it in my java code. Any suggestion to how to convert my c++ code ...
What you are looking for is JNI (Java Native Interface). Here is a link for compiling a dll using VC++ - http://www.tidytutorials.com/2009/07/java-native-interface-jni-example-using.html and one using MinGW - http://www.mingw.org/node/41
6,871,836
6,872,449
How does MFC's wWinMain end up in the executable?
In MFC, wWinMain is defined in appmodul.cpp. This file is built into mfc90ud.dll from what I can see. However, when I run my application, the call stack shows MyApplication.exe!wWinMain. How has it taken the wWinMain function that was exported in appmodul.obj and placed it in my application?
Right-click your project in the Solution Explorer window, Properties, Linker, Command Line. Type /verbose in the "Additional Options" box. Rebuild your project. The Output window now shows a trace of where the linker found a symbol. Search it for "winmain" to find this: 1> Searching c:\Program Files (x86)\Micros...
6,871,846
6,872,004
Concatenating a stack string with a heap string gives odd results
I am sure the following has a rational explanation but I am nevertheless a bit baffled. The issue is with a function which creates a _TCHAR[CONSTANT], a _TCHAR*, concatenates them and returns the result. For some reason the call to whatTheHeck() from _tmain() returns gibberish. _TCHAR* whatTheHeck(_TCHAR* name) { ...
There are lots of problems with your code. Let's take it apart, shall we: _TCHAR* whatTheHeck(_TCHAR* name) // We're inside a local scope { _TCHAR Buffer[BUFSIZE]; // "Buffer" has automatic storage _TCHAR* what = new _TCHAR[BUFSIZE]; // "what" points to newly allocated dyn. memory what = _tcsca...
6,871,978
6,872,993
Opencv copy 3 channel IplImage to 4 channel IplImage
When I try to use cvCopy a IplImage consisting of 3 channels to a IplImage with 4 channels (I need the extra channel later) all I get is an error message. Is there another way to increase the channel count of an IplImage without loosing the data that it already holds? Thanks!
Use cvMixChannels, like this: CvMat * src; // your source image CvMat * dst // your destination image CvMat * zeros = cvCreateMat(src->cols, src->rows, CV_8UC1); cvSet(zeros, cvScalar(0, 0, 0, 0)); CvArr * input[] = { src, zeros }; int from_to[] = { 0,0, 1,1, 2,2, 3,3 }; cvMixChannels(input, 2, &dst, 1, from_to, 4); I...
6,872,035
6,872,574
How can I read a password from the console, echoing splats?
here i have written a code to accept a password entered by the user after he have entered his username,i have written a small code using do while statement to print out the star every time when ever user enter any character,& the loop terminates when the user enters a '!'. but it surprised me when i see the password en...
You have defined: char password[15]; And as per your loop, it continues until i is equal to 14 (i.e, 15th character). So there is no space for NULL termination. Let it be like this: char password[16]; Now, just after the loop, add: password[i] = 0; i will be at 15 if user didn't enter '!' and if he did, it will be r...
6,872,347
6,872,387
Overloading operator==
Guys I have some silly struct let's call it X and I also have a fnc (not a member of it) returning a pointer to this struct so it looks like so: struct X { bool operator==(const X* right) { //... } }; X* get(X* another) { //... } I also have line in code which 'tries' to compare pointers to those structs b...
You cannot change the way pointers are compared. You must either change the syntax of the if statement, or change get() to return a reference instead of pointer. Any other solution is going to be quite hacky. If you truly must live with those restrictions, I would suggest changing get() to return some kind of specializ...
6,872,581
6,874,036
XCode: How to create .app package and work with resources?
I'm very new to OS X and XCode, so please don't assume I know all terminology. I've been developing my game in Linux for a year. Now I'm moving to OS X with XCode. I saw that in OS X, all the applications, even games, are only one package (ending with a hidden .app extension if I'm correct). And I want to use that syst...
Question 1: It is a directory. You can examine the contents of a .app bundle via the command line or by using "Show Package Contents" in Finder. Question 1.5: You did not want to pick "Command Line Application." You most likely wanted to pick "Cocoa Application" or maybe "Carbon Application." You can read more about...
6,872,701
6,876,941
Python to C++: From Deriv, to Base, to Deriv again
I'm using Boost.Python to expose my C++ code to Python. I've encountered a difficulty related to having an object passed from one language to the other multiple times. Here's what I want to do: The C++ code class Base { public: void baseTest() { std::cout << "Base::basetest()"; } }; class Deriv :...
Thanks for the comments, I found the solution to this. It's actually quite simple, you just have to wrap the Base object in a shared_ptr instead of passing it by reference, like this: void call(boost::shared_ptr<Base> b, boost::python::object func) { func(b); } But be careful about something. I tried to used std::...
6,873,079
6,873,122
Is it appropriate to declare a non-static constant data member inside a class while coding?
data member inside a class can be const but only if its static. otherwise we need to have a constructor to initialize a constant inside a class. can we declare a const data member inside a class? //this was an interview question It seems to me that we can, but is it appropriate for a programmer to declare a constant i...
Off course you can : struct A { A() : a(5) { } const int a; }; int main() { A a; } This means that the data member a, inside struct A is not going to change.
6,873,120
6,874,792
Problem of displaying image using OpenCV in C++
I wish to display image using c++ OpenCV code. Below are the code fragment: //Load image Mat img = imread("Example1.jpg"); //Display in window namedWindow("Skin"); //display image imshow("Skin",img); //returns the matrix size cout<<img.size()<<endl; // wrong Please help on how to display the size. I have tried man...
//Load image Mat img = imread("Example1.jpg"); //Display in window namedWindow("Skin"); //display image imshow("Skin",img); //returns the matrix size cout << "width= " << img.cols << " height= " << img.rows<< endl; //OR if you wanna use the size() getter. cout << "width= " << img.size().width << " height= " << img....
6,873,138
6,873,234
Calling private method in C++
This is purely a theoretical question, I know that if someone declares a method private, you probably shouldn't call it. I managed to call private virtual methods and change private members for instances, but I can't figure out how to call a private non-virtual method (without using __asm). Is there a way to get the po...
#include the header file, but: #define private public #define class struct Clearly you'll need to get around various inclusion guards etc and do this in an isolated compilation unit. EDIT: Still hackish, but less so: #include <iostream> #define private friend class Hack; private class Foo { public: Foo(int v) : ...
6,873,468
6,873,513
force compiler to generate whole class template
how can I force compiler, to generate whole class template? not just methods I use? I am sure I read it in template complete guide book, but I can not find it. It was one-line statement. I am not able to ask google the right question. Thank you!
You can explicitly instantiate a class template with something like this: template class Foo<Argument1,Argument2>;
6,873,547
6,874,050
Integer number as char* for dummies
Question has been asking before, but I am still a bit at a loss as to the best way. I have an integer and would like to obtain a char* to use as a member of a struct. Similar questions are for example here or here. I'd rather not use stringstream or lexical_cast. Which as far as I can see basically leaves itoa, sprin...
If I request a char str[12], that reserves 12 characters? Yes, this reserves 12 characters (bytes) on the stack. I presume that memory has then been assigned? str now points to the beginning of 12 bytes of contiguous memory that has been allocated on the stack. So how does null termination work? Is that at the end...
6,873,615
6,873,646
C++ Floating point gotcha
Possible Duplicate: Most effective way for float and double comparison I am new to C++. I had a doubt, while reading C++. How to decide two floating point numbers equal to each other or not ? Thanks in advance
Obviously, you should not use operator == to compare them. The important concept here is if the difference of your two floating point number is small enough to the precision requirement of your problem to solve or smaller than your error range, we should consider them as equal. There are some practical methods sugg...
6,873,616
6,873,666
Trigger event on return in C++
I want to execute some function right before the return of another function. The issue is that there are multiple returns and I don't want to copy-paste my call before each of them. Is there a more elegant way of doing this? void f() { //do something if ( blabla ) return; //do something else re...
struct DoSomethingOnReturn { ~DoSomethingOnReturn() { std::cout << "just before return" << std::endl; } }; ... void func() { DoSomethingOnReturn a; if(1 > 2) return; }
6,873,651
6,873,754
C++: Why won't this compile?
I have the following C++ code which I got from google's sparsehash website: #include <iostream> #include <google/dense_hash_map> #include <string.h> using google::dense_hash_map; // namespace where class lives by default using std::cout; using std::endl; using ext::hash; // or __gnu_cxx::hash, or maybe tr1::hash...
Maybe thou shalt try to replace ext::hash by tr1::hash.
6,873,936
6,874,217
How to change a project's name in QtCreator?
Is there a way to change a .pro , .ui and .h names if the project is done? How to do it?
Names for .ui, .h and .cpp files can just be changed inside Qt Creator. The name of the .pro file is a bit more involved. The simplest is probably to copy the project, rename the .pro file, and reopen. Qt Creator also uses its own config file, .pro.user, for changes you do in the project and build settings. You can ju...
6,873,980
6,874,535
Use of TEXTURE_RECTANGLE_ARB affecting TEXTURE_2D
I am using OpenGL 1.3 to do 2D sprite rendering and supporting both POTS (power of two size) textures and NPOTS (non power of two size) textures with TEXTURE_2D and TEXTURE_RECTANGLE_ARB respectively. I had started with POTS textures (using TEXTURE_2D), which worked fine, but now I am adding NPOTS textures (using TEXTU...
Okay, so it turns out that it was a rather silly mistake, that was found in the original TEXTURE_2D code. I had forgotten to end the rendering with the correct glDisable! I.e. the rendering code began with glEnable(targetType), but did not end with glDisable(targetType) [where targetType was the correct choice of GL_TE...
6,874,122
9,736,084
OpenAL AL_ILLEGAL_ENUM after alListener3f(AL_ORIENTATION, 0, 0, -1)
That's pretty much it. I've got a function to set up an OpenAL context and device, and load a WAV file into a buffer and pass that buffer along with data from the file to alBufferData. I then try to call alSourcePlay(source) and no sound comes out. The whole function compiles and runs fine, but through debugging I foun...
I found the answer to this a while ago and I've only just remembered to answer it on here: the AL_ORIENTATION enum is used in the alListenerfv method, not alListener3f. And it takes a vector instead of 3 ints. I'm amazed how long it took to find that out!
6,874,132
7,899,855
How to use SWIG with "using"
I am attempting to use SWIG 2.0.4 on a C++ library, I have the following in my .i file: %module coh %{ #include "coherence/lang.ns" #include "coherence/net/CacheFactory.hpp" #include "coherence/net/NamedCache.hpp" %} %include "coherence/lang.ns" %include "coherence/net/CacheFactory.hpp" %include "coherence/net/NamedCa...
MSDN has this to say: Note the difference between the using directive and the using declaration : the using declaration allows an individual name to be used without qualification, the using directive allows all the names in a namespace to be used without qualification. (I'm guessing that) SWIG supports the "usi...
6,874,346
6,874,391
How do you define a global function in C++?
I would like a function that is not a member of a class and is accessible from any class. I assume I would have to #include the header file where the function is declared, but I don't know where to define such a global function. Are there good reasons against having such a function in the first place?
you need a body (in a cpp file): int foo() { return 1; } and a definition/prototype in a header file, which will be included before any use of the function: #ifndef MY_FOO_HEADER_ #define MY_FOO_HEADER_ int foo(); #endif then using it somewhere else: #include foo.h void do_some_work() { int bar = foo(); }...
6,874,713
6,877,439
Java JNA -> C++ -> .NET Library Must Be In System32
I have Java call a C++/CLR library through JNA. When attached to a C# DLL (using #using<myC#lib.dll>) the C# DLL MUST be in System32, nothing else will do, otherwise the JVM crashes (for obvious reasons). # # A fatal error has been detected by the Java Runtime Environment: # # Internal Error (os_windows_x86.cpp:149), ...
Alright, registering with the GAC fixed it, so I wrote a very simple program that registers DLLs with the GAC (gacutil.exe is not redistributable). I'll include this with the Java application, it can register the libraries at runtime. Edit I am unable to use the GAC (I plug into non-GAC registered libraries from here, ...
6,874,759
6,875,892
Xcode: Referencing C++ project from Objective-C project
I'm beginning to tear my hair out over this, so it's time to post here! I have a C++ project in XCode, built as a Command Line Tool. All .cpp files have been renamed as .mm, there is one .hh and a few .h headers. I've specified 'Compile Sources As -> Objective-C++' in Build Settings. I have another XCode project for an...
Thanks to everyone who gave me suggestions. Having created my projects anew from scratch, I fiddled and logic-ed my way to the solution. Note that - at least in my case - no use of #ifdef __cplusplus was required, nor any other preprocessor directive. Only file suffix changing is essential (as detailed below). Here's t...
6,874,793
6,874,844
Passing a vector to a template function
Here is a small function I'm trying to write to keep track of the dynamic allocations I use in my functions (tired of writing delete [] all the time). template <class T> T* snew(int size, vector<T*> list) { T* pointer = new T[size]; list.push_back(pointer); return pointer; } vector<float*> list; float* myf...
First and foremost, you pass vector<T*> list by value, which means that it gets copied and your global list is left unchanged. Do it like this: template <class T> T* snew(int size, vector<T*>& list) As for the compilation issue, there's a typo, you're applying * one time too much, change the usages to float* myfloat1 ...
6,874,810
6,874,900
cmake, several questions
I'm new to cmake. Are there any good tutorials that go deeper into the matter? Are there any articles about "good practices" with cmake? Are here any good overviews about all cmake commands and what they do? The original cmake docs are rather confusing and messed up in my opinion... Now for something more specific: As ...
You can just glob *.cpp *.h etc, but if your list of files changes CMake won't notice unless you touch your CMakeLists.txt file. The best practice is to constantly adjust your CMake files, though. You'll get consistent behavior if you list the files, which is what is really important. It really isn't that much work ...
6,874,945
6,875,178
C++ app to talk to an FPGA over PCI in userland using mmap
First off i'm new to Linux programming so apologies if this makes no sense or I'm barking up the wrong tree, point me in the correct direction. I'm trying to write a cpp app to talk to a FPGA over a pci bus, in userland. The code I have written so far, enumerates over the directories in /sys/bus/pci/devices checking t...
That's a perfectly acceptable mmap call and should work correctly.
6,875,020
6,875,225
How to refactor this simple code to avoid code duplication?
I am solving the following simple problem(on one of OnlineJugde sites which is in Russian, so I won't give a link here:). It is easier to state the problem via an example than definition. Input: 10 // this is N, the number of the integers to follow 1 1 1 2 2 3 3 1 4 4 Output: 3 times 1. 2 times 2. 2 times 3. 1 times ...
i came up with this. no code duplication, but slightly less readable. Using vector just for convenience of testing EDIT my answer assumes you know the numbers ahead of time and not processing them on the fly vector<int> numbers; numbers.push_back(1); numbers.push_back(1); numbers.push_back(1); numbers.push_back(2); num...
6,875,069
6,875,531
Compilation error with inheritance of templates accessed through pointer of pointers
Template compilation error using pointer of pointer: (What causes the code not to compile ??) template <int DIM> class Interface { }; template <int DIM> class Implementation : public Interface<DIM> { }; template <int DIM> class Modifier { public: void modify(const Interface<DIM>** elem) { } // only one * compiles !!...
The problem is that in C++ it is not legal (or safe) to convert a T** to a const T**. The reason is that if you could do this, you would end up being able to subvert const. For example: const T value; T* mutablePtr; const T** doublePtr = &mutablePtr; // Illegal, you'll see why. *doublePtr = &value; // Legal, both sid...
6,875,277
6,875,362
Passing a class object pointer to a function for initialization C++
Lets say I have a class "A" and this function: void initializationFunction(A* classPointer) { ... ... classPointer = new A(.....); } I write: A* classPointer; Then I pass this pointer to this function: initializationFunction(classPointer); This will not work unless I pass it by reference in the function...
Yeah, that is true. You've to pass the argument by reference (or you can pass A** instead). But the best solution is to write the constructor of A in such way that you wouldn't need this function in the first place. That is, whatever you're doing in this function, you should be doing that in the constructor itself. If,...
6,875,403
6,875,488
Cannot open output file, permission denied
So I keep getting this error when trying to compile C++ code using CodeBlocks. cannot open output file [filename.exe] permission denied It only started today, and it's sporadic and inconsistent. It usually goes away if I shut CodeBlocks down and restart the project, but not always. Sometimes it even goes away when ...
check that "filename.exe" is not running, I guess you are using Microsoft Windows, in that case you can use either Task Manager or Process Explorer : http://technet.microsoft.com/en-us/sysinternals/bb896653 to kill "filename.exe" before trying to generate it.
6,875,474
6,939,808
C++ dynamic (multi-stage) 3D vector instantiation and element assignment
Okay, so I need to create a 3D data-structure at run-time, I decided to use std::vector, the problem is as follows: I know the dimension of the 1st dimension at instantiation time (when I create the object I'm using it in), but I don't know the dimension of the second until run-time, and the size of 3rd dimensions can ...
Okay, so it turns out, that technically everything was correct (albeit inefficient, which I got around by using .resize() for appropriate dimensions in turn), my 'problem' was (as it tends to be) a very stupid mistake, to verify that everything was assigned I used: printf("value assigned: %d", splits[dim1][dim2][dim3])...
6,875,771
6,875,851
mmap(): what happens if underlying file changes (shrinks)?
If you memory map a file using mmap(), but then the underlying file changes to a much smaller size. What happens if you access a memory offset that was shaved off from the file?
IBM says it is undefined http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Fapis%2Fmmap.htm If the size of the mapped file is decreased after mmap(), attempts to reference beyond the end of the file are undefined and may result in an MCH0601 exception. If the size of the file increases after the ...
6,875,783
6,876,955
Size of classes with virtual functions GCC/Xcode
Can anyone explain to me what is going on here? First off, I think most programmers know that a class with a virtual function has a vtbl and thus has 4 extra bytes on the top of it. As far as I know, that's fairly standard. I've tested this and taken advantage of this fact before to do load in place from a binary file ...
Instances of classes A through C contain a vptr, a pointer to the virtual function table for the dynamic type. This pointer occupies 8 bytes on your 64-bit machine (or 4 bytes on a 32-bit machine). Each int member takes up 4 bytes. The minimum value of sizeof(Class) is the sum of sizeof(member) for all members. If it w...
6,875,834
6,875,908
cyclic includes, how can I resolve this without changing class hierarchy
Animal | Mammal / \ TwoLegged - FourLegged / \ Human Lion I have this class hierarchy, each class defined in it's own header. Now when I include both Human.h and Lion.h in the same place, I get a Mammal redefinition error. err...
You need to use include guards. The typical form is: #ifndef NAME_OF_HEADER_H #define NAME_OF_HEADER_H // Rest of header code here. #endif Since #include in C++ just does a copy-paste of the text in the current file if the same header gets included twice that text will result in duplicate class definitions. What the...
6,875,921
6,876,624
Inserting a bitmap image into Rich Edit Control
I am currently working on a project in which I need to use a pin pad device for an electronic signature capture. When the electronic signature is captured, it is saved as a .bmp file. When I take the same .bmp file and insert it into Rich Edit Control, it simply shows a filled in square box, instead of what the signa...
See this Codeguru article: Insert any HBITMAP (Bitmap) in your RichEdit Control
6,876,058
6,876,144
c++ how to expess a mathematical term
i have the following : I only want (for now) to express the (s 1) , (s 2) term . For example ,(s 1)=s , (s 2)= s(s-1)/2! , (s 3)=s(s-1)(s-2)/3!. I created a factorial function : //compute factorial int fact(int x){ if (x==0) return 1; else return fact(x-1)*x; } and i have problem in how to do right the above. ...
The factorial part will be much more efficient using a loop rather than recursion. As for the binomial coefficients, the line: s_term=s*(s-p)/fact(p+1); isn't going to have the desired effect, as you're only setting the first and last terms correctly and missing out the (s-1), (s-2), ..., (s-p+1) terms. It's easier to...
6,876,237
6,876,496
C++: weird error "expected initializer before extern" in library SDL_image.h
I'm currently trying to make a simple game with SDL and Box2D. Unfortunately, the code I added to make the character shoot proyectiles is so buggy I can't even begin to count the errors. To deal with this I added some code to show some debug info in the game. Unfortunately, after dealing with all the errors a weird err...
Have a look at the end of the header files that are included before this one. My guess is that there's a missing ; after a class definition.
6,876,254
6,876,270
Find the sum of all multiples of 3 or 5 up to 1000
I'm doing the problems on Project Euler in C++, but I'm not getting the right answers to the first one. Here's my code: #include <iostream> using namespace std; int main() { int b; int c; for (int a = 0; a <= 1000;) { a = a + 3; b = a + b; } cout << b << "\n"; for (int a...
You are adding all values that are both multiples of 3 and 5 (i.e. multiples of 15) twice. Additionally, you will also include 1002 and 1005, which probably isn't intended.
6,876,291
6,876,412
Visual studio 2005 c++ autoincrement version in resources
Is it possible with some code or another way to increment the last number of the version each project buld? I use a resources.rc and resources.h to store the version.
I successfully used RCStamp in the past. Perhaps something to check out.
6,876,325
6,876,487
Sendto Failed C++ // POSIX.4
So - I'm running an application where two processes are talking over a UNIX domain socket. The vast majority of the messages being passed over the socket are processed correctly, but when the number of bytes in the message excedes a certain limit I start getting the error: sendto failed: Message too long (POSIX.f) I ...
Are you using stream or datagram sockets? If they're stream sockets, you can just perform a second or third write to send the rest of the data. If they're datagram sockets, you're probably stuck (maybe you could switch to stream sockets?) but there may be a setsockopt option that would increase the limit. Still you may...
6,876,751
6,876,833
Differences between unique_ptr and shared_ptr
Possible Duplicates: pimpl: shared_ptr or unique_ptr smart pointers (boost) explained Could someone explain differences between shared_ptr and unique_ptr?
Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource. When using unique_ptr, there can ...
6,877,000
6,877,104
What's the proper way to declare and initialize a (large) two dimensional object array in c++?
I need to create a large two dimensional array of objects. I've read some related questions on this site and others regarding multi_array, matrix, vector, etc, but haven't been able to put it together. If you recommend using one of those, please go ahead and translate the code below. Some considerations: The array is ...
Your first approach allocates everything on stack, which is otherwise fine, but leads to stack overflow when you try to allocate too much stack. The limit is usually around 8 megabytes on modern OSes, so that allocating arrays of 1300 * 1372 elements on stack is not an option. Your second approach allocates 1300 * 1372...
6,877,032
6,877,216
boost::condition_variable.timed_wait return immediately
I'm working on a little threading library and have run into a problem. boost::condition_variable.wait() works perfectly, however boost::condition_variable.timed_wait() returns immediately, it doesn't time out. The documentation says it should only return once the timeout has passed or it's been notified. It's a three s...
Condition variable waits can occasionally result in spurious wakeups. As such, you must use them in a loop: while (someCondition) msg->waitCondition.wait(lock); With timed_wait it's slightly more complex as you must recalculate your timeout to deal with however long it did, in fact, wait. Boost offers a variant with...
6,877,052
6,877,164
Use of the & operator in C++ function signatures
I'm currently reading through Accelerated C++ and I realized I don't really understand how & works in function signatures. int* ptr=&num; means that ptr now holds the address to num, but what does that mean? void DoSomething(string& str) from what I understand that is a pass by reference of a variable (which means ...
A reference is not a pointer, they're different although they serve similar purpose. You can think of a reference as an alias to another variable, i.e. the second variable having the same address. It doesn't contain address itself, it just references the same portion of memory as the variable it's initialized from. So ...
6,877,214
6,877,327
How to address generic types by accessing them via Assembly?
I'm working with a hosted CLR to access a .NET-Assembly. This assembly contains generic types as: MyGenericClass<MyClass> // C# notation Where spAssembly is my hosted and loaded assembly, I need to get this type via string (bstrClassName). spAssembly->GetType_2(bstrClassName, &spType); // C++-Access via hosted Assem...
Generics in .Net work different than C++ templates. You have to get the generic type first and then generate a concrete type from it. So you first have to get MyGenericClass and use MakeGenericType passing MyClass as parameter.
6,877,281
6,877,302
memset structure with std::string contained
I have a massive structure where the entire contents is scalar variables, enumerations, and arrays of scalars (stack-based) with the exception of one std::string variable. Now, here's my question... Can I memset the structure to 0 for its whole size (like I would if it was simply all scalars), or is that not possible w...
No, you cant, it would overwrite the internal state of the string and make bad things happen. You could wrap all the POD stuff in a seperate struct and put that in your current one, that way you could memset that and let the string default construct. Edit: Just to clarify, the string will almost certainly be storing a...
6,877,557
6,877,575
Scoped / Reference Counted Iterator
I'm looking for a way to simulated a "scoped iterator" (for lack of a better phrase). Basically, I want to get an iterator from a collection (map in this case) and wrap it in a "scoped iterator" that would remove the element/iterator from the collection once the last reference was dropped. My current approach is below,...
The easiest thing to do would be to just use a custom deleter for shared_ptr that will remove the element from the map. Also, void main() is Bad.
6,877,587
6,877,942
Exposing Static Constant with Boost
I am using Boost 1.44.0 to cross-compile C++ code for Python. I'm trying to expose a static constant defined in ExposureSinusoid.h like this: static const UINT _min_exp = 20; And in the file extending.cpp, I am trying to expose them like this, according to documentation from the Boost team: .def_readonly("_min_exp", &...
In addition to being declared, static data members must also be defined. // ExposureSinusoid.h class ExposureSinusoid { // ... public: static const UINT _min_exp = 20; // declaration // ... }; // ExposureSinusoid.cpp const UINT ExposureSinusoid::_min_exp; // definition The only scenario where the defini...
6,877,588
6,878,630
How to get PEM encoded X509 certificate as C++ string using openssl?
I have a openssl X509 structure with a self signed certificate. I need to get a PEM formatted C++ string from this structure. What are the openssl APIs that I need to use to achieve this? I tried following the example program at https://www.codeblog.org/gonzui/markup/openssl-0.9.8a/demos/x509/mkcert.c. This program sho...
look at the source of the openssl x509 command and see how it does the operation to read a DER encoded file and writes a PEM one - ie: openssl x509 -in mycert.der -inform DER -out mycert.pem The code of the cli utils is pretty easy to follow
6,877,896
6,877,955
Is it better to roll all work into one loop or break it into several loops?
I am parsing a folder structure that is quite heavy (in terms of the number of folders and files). I have to go through all the folders and parse any files I come across. The files themselves are small (1000-2000 characters although a few are bigger). I have two options: Go through all the folders and files and parse...
How about one thread that creates the list of file names to process, and another thread that reads through that list of files and uses one of a handful of worker threads to do the processing? I don't know how many directories there are, but just guessing that's not the big time sink. I'd say you'd get the best perform...
6,878,004
6,882,678
How to create a generic .NET type in a native c++ application hosting the CLR (not using C++/CLI)?
In .NET programs I can create a generic type by: System::Type::MakeGenericType(...) There must be a way to do that in native C++ for a .NET type (with _TypePtr). I am hosting my own CLR instance and not using C++/CLI. (Here's an example of how that can be done.) My approach for that is: _TypePtr BuildGenericType(_Typ...
Finally i found a workaround myself. At first i need an additional assembly that wraps System::TypeBuilder /// <summary> /// Wrapper for System::TypeBuilder /// </summary> public class TypeBuilder { /// <summary> /// Creates a generic type out of the given arguments. /// </summary> /// <param name="gene...
6,878,338
6,894,438
Boost.Python: Grab 'self' from member function
Class member functions in Python have to explicitly declare a self parameter which represents the class instance. Is there a way to get a hold of self from C++, by using Boost? class FooBar { public: void func() { } }; // A wrapper for the above class struct FooBar_W : public FooBar { void func(boost...
It's doable. The way to do it can be found in the link below; that page documents one way (the old way) to expose pure virtual functions. The example can be adapted to other needs, though. > http://wiki.python.org/moin/boost.python/OverridableVirtualFunctions#Pure_Virtual_Functions
6,878,406
6,878,441
Wait until window closes when message loop is on another thread
In one C++ application I have a window whose message loop runs in a separate thread because the main thread is busy calculating and rendering a simulation. The window acts as a log window for the simulation. When the simulation throws an exception, the simulation closes and the log window displays the details. Now the ...
You have a few options. Run all the UI out of the main thread and get the worker thread to synchronize reporting back to the main thread to display, for example via PostMessage or SendMessage. Don't wait at all and get the worker thread to post a message to the main thread when the worker is done. Use MsgWaitForMultip...
6,878,429
6,878,508
Replacing .at() with [] throughout my code
I'm a C++ user and got some code that uses .at() to get bound checking on the STL vectors. Now I'd like to change them to standard []. Does anyone know of a script that could do this? It doesn't have to be a super general script — most of the cases are .at(i) or perhaps .at(a*i+j) — but there are too many of them to do...
Use this Perl operator: s/\.at\(([^)]+)\)/[$1]/g The s/// operator in Perl is a "substitute" (find/replace). In the first set of //, you specify the regular expression to match. The second // is the text to replace or substitute that match with. In this case, I'm finding any instance of ".at(anything-but-a-close-pare...
6,878,507
6,889,528
Using QSocketNotifier to select on a char device.
I wrote a char device driver and am now writing a QT "wrapper" which part of it is to get a signal to fire when the device becomes readable via the poll mechanism. I had tried to do: QFile file("/dev/testDriver"); if(file.open(QFile::ReadOnly)) { QSocketNotifier sn(file.handle(), , QSocketNotifier::Read); sn.setEn...
Your QSocketNotifer gets destroyed as soon as that if block ends. It doesn't stand a chance of reporting anything. You must keep that socket notifier alive as long as you want that file to be monitored. The simplest way of doing that is probably keeping a QSocketNotifer* member in one of your classes.
6,878,781
6,878,901
'boost::operator ==' : 4 overloads have similar conversions
The code below gives me a compile-time error. Anyone have any ideas on how to fix this or what might be causing it? 'boost::operator ==' : 4 overloads have similar conversions typedef boost::function<void (boost::weak_ptr<std::string>)> Callback; std::list<Callback> callbacks; Callback func; callbacks.remove(func); /...
When you call std::list<T>::remove, it looks for the value to remove by comparing it to the elements in the list. In the case of boost::function objects, this fails because boost::function objects can't be compared. See Why can't I compare boost::function objects with operator== or operator!= in the Boost Function FAQ....
6,879,429
6,879,512
C++ template converting string to number
I have the following template function: template <typename N> inline N findInText(std::string line, std::string keyword) { keyword += " "; int a_pos = line.find(keyword); if (a_pos != std::string::npos) { std::string actual = line.substr(a_pos,line.length()); N x; std::istringstr...
It doesn't work because the string you're reading in can't be converted to a number, so you're returning uninitialized garbage. That's happening because you're reading in the wrong string -- if line is foo bar 345 and keyword is bar, then actual gets set to bar 345, which doesn't convert to an integer. You instead wa...
6,879,482
6,879,527
C++ Question About Return Value Optimization
There are many questions on this site about return value optimization (I suppose it's a fairly confusing topic), but I can't seem to find one that answers my particular question. If I have code that looks like this: returnType function() { stuff....} void someOtherFunction() { returnType var = function(); mor...
I would then expect that temporary value to be copied via assignment (which could be overloaded and in theory could have any kind of functionality!) into var, which would have previously been initialized via the default constructor. Well, for starters, that's quite wrong. int x = 0; int x(0); Those two lines a...
6,879,606
6,879,661
C++ to C#, static_cast into enum
I'm trying to convert a bit of VC 6.0 C++ code to C#. Specifically, I'm parsing through a binary dat file and I've run into a problem converting this bit of code: ar.GetFile()->Read(buf,sizeof(int)); memmove(&x,buf,4); pEBMA->before_after = static_cast<enum EBMA_Reserve>(x); pEBMA->method = static_cast<enum EB...
EDIT: It actually looks like the structure size of EBMA_Data is 17 bytes. struct EBMA_DATA { double reserved; //(8 bytes) double fraction; //(8 bytes) enum EBMA_Method method : 4; //(this is packed to 4 bits, not bytes) enum EMBA_Reserve before_after : 4; //(this too, is packed to 4 bits) } so your read code ...
6,879,626
6,879,719
where is the problem vector find c++ ??
when i compile i has an error and i cannot understand where is the problem? class Edge{ public: int nid; bool operator==(const Edge& edge) const { return nid == edge.nid; } }; and problem here vector<Edge> edges; vector<Edge>::iterator it; it = find (edges.begin(), ed...
find will compare (with ==) the objects of type Edge in the vector with nid. I guess that nid is of type int and that won't work unless you implement operator== between Edge and int. You can try : it = find (edges.begin(), edges.end(), Edge(nid));
6,879,663
6,960,285
Cannot Retrieve Custom Control Pattern After Registration
I'm using the automation API to create custom control patterns. Now that I've created my custom patterns, I don't know how to retrieve the existence of my new patterns. I've tried to use AutomationPattern.LookupById() in the following code: PatternWrapper pattern = new PatternWrapper(); int res = pattern.RegisterRotate...
Ok, so I did some research (a lot of research) and noticed that I did not implement the server-side provider for my unmanaged code. By implementing the server-side provider, I should be able to retrieve a pointer to my custom control. Hopefully that does it, I'm in middle of implementing it at the moment. Thanks for yo...
6,879,749
6,879,765
C++ lvalue required as unary '&' operand
I'm working on a game engine and working on implementing a state design. I have an Engine class which takes care of all the initialization of everything and contains the game loop which calls update, render and handle input functions of the active state. All my different states inherit from State which requires a refer...
Change: GameState *state = new GameState(&this); to: GameState *state = new GameState(*this); This is because you are passing the Engine by reference to the constructor of the State class.
6,879,828
6,882,140
Pushing data to nodeJS from OSX application
I've got an OSX application written in c++ (in particular, built with OpenFrameworks) and a server written using nodejs. The application tracks an object wandering around a room and I want to send information about the object's position to the server on a relatively constant (at least 3 times a second) basis. From what...
From the openFrameworks side you have quite a bunch of possibilities to send data: (Given current OF 007) look at the following examples, if they fit your needs: <OF-folder>/apps/addonsExamples/networkTcpClientExample <OF-folder>/apps/addonsExamples/networkUdpSenderExample <OF-folder>/apps/addonsExamples/oscSenderExamp...
6,879,946
6,880,070
Is this macro statement legal C++ or something else? And if it is legal how does it work
WebKit has a lot of pre-processor lines like this: #if MACRO1(MACRO2) For example: #if PLATFORM(MAC) || (PLATFORM(QT) && USE(QTKIT)) #include "MediaPlayerPrivateQTKit.h" #if USE(AVFOUNDATION) #include "MediaPlayerPrivateAVFoundationObjC.h" #endif ... So my first thought was that they were function-like macros, but I c...
As mentioned in the wiki, in root/trunk/Source/JavaScriptCore/wtf/Platform.h we get a definition for each of these defines. For instance, the PLATFORM macro is defined as: #define PLATFORM(WTF_FEATURE) \ (defined WTF_PLATFORM_##WTF_FEATURE \ && WTF_PLATFORM_##WTF_FEATURE) The value of WTF_FEATURE will ...
6,880,045
6,881,637
How can I work around Visual C++ 2005's "decorated name length exceeded, name was truncated" warning?
For example, say for some reason I had a piece of code that looked like this: mutable std::vector<std::vector<std::vector<std::vector< std::vector<MyNamespace::MyType> > > > > myFreakingLongVectorThing; and I am getting a warning that looks like this: C:\Program Files (x86)\Microsoft Visual Studio 8\VC\include\xstring...
If you don't want to see the warning you either have to disable it or use a newer compiler. The warning is about debug information being limited to 255 characters for the type name. As long as these 255 characters are not identical for two different types, you are ok. And if they are identical, you cannot do much about...
6,880,077
6,880,080
Why does this std::sort predicate fail when the class is inside main()?
This is a much simplified repro which illustrates how class Predicate delcared outside main() works but when the exact code appears inline as class InlinePredicate the compiler can't match std::sort. The strange thing is that you can pass anything as the third argument to std::sort (say, integer 7) and you'll just get...
In C++03, local classes have no linkage and consequently cannot be used as template arguments (§14.3.1/2). In C++0x, this limitation has been removed and your code would compile as-is.
6,880,102
6,885,872
Compiling Allegro 4.2 For MinGW/CodeBlocks
I'm having trouble getting Allegro to Compile. When I begin the fix.bat mingw, it gives me an output which says: Configuring for Windows/Allegro...Stop! Yet, when I try to compile the rest by typing mingw32-make.exe, the following is output: makefile.all:248: ***recipe commences before first target. Stop. I've been ...
First, there's no reason to use Allegro 4.2 as it is past end of life. If you want to use the 4 series, you should be using the 4.4 branch. http://www.allegro.cc/files/?v=4.4 It's possible that the Makefile on it will just work, but you may also need to update your copy of MinGW in case the version you have is buggy. ...
6,880,111
6,880,148
Why mutable lambda with pointer to member function?
I'd like to get my mucky paws on the operator() of a lambda function. The following seems up the task: template <typename F> void bar(F func) { void (F ::*pm)(); pm = &F::operator(); } However, in the following, I need to include the mutable keyword. Why is that? Is it possible to above instead declare a pointer t...
According to 5.1.2 of the N3291 C++0x specification, the lambda's operator() is const unless you explicitly declare it mutable: This function call operator is declared const (9.3.1) if and only if the lambda- expression’s parameter-declaration-clause is not followed by mutable. You may be able to do some template m...
6,880,251
6,880,297
How to compare and check in c++ using loops and array
Here is my new edited code I am having trouble with my final if loop for the X and O's stored inside an array. I am trying to check if there is an X or O already inside the array or not. If there is one it asks the user for another input then start over again however when i run the program this happens: 1 | 2 | 3 4 | 5...
First the second question (the easy one): Return exits from the current function. So, after the return, no further instruction in your function is executed. You should remove the return and put the rest of the code (that should not be executed if the input is not valid) in the else block of that if. First question: Wh...
6,880,350
6,880,362
how to keep a GUI on-screen without moving or resizing it according to camera movement
Hey i'm trying to make a GUI lib with SFML, and everything's done except one problem: Making the Interface stay still even when the camera moves or zooms in. This would be easy to fix if zooming wasn't possible, but zooming out means scaling the contents of the Interface up, which causes it's text/images to become blu...
Stop using the same camera and perspective matrices for your GUI as you do for your scene. In the case of SFML apply a different view, then restore the old one.
6,880,771
16,803,139
g++ ld can't find RInside symbols for x86_64 architecture
I get a linker error saying that symbol(s) cannot be found when I try to compile an RInside sample file with g++. Any assistance would be appreciated. R version 2.13.1 is installed on Mac OS X 10.5. Rcpp and RInside include files have been copied to the usr/include directory. R headers and libraries have been include...
I know this is a very old question, but I am adding this in case it helps someone else. I spent hours and hours looking into this. I have a Mac OS (Mountain Lion 10.7). I downloaded RInside, went over to examples and typed make but kept getting this ld error. New installs of xcode, gcc as mentioned in this thread and ...
6,880,832
6,880,845
Pointer to class member as template parameter
Is it possible to have non-type template parameter which is actually a pointer to a class member? What I'm looking to do is something like the following: struct Person { Dog dog; }; template <?? ptr> struct Strange { // ... }; typedef Strange<&Person::dog> weird; My work so far leads me to believe that nothing o...
From the standard: A non-type template-parameter shall have one of the following (optionally cv-qualified) types: integral or enumeration type, pointer to object or pointer to function, reference to object or reference to function, pointer to member. So it is allowed, and seems to work on g++ like this: template <Do...
6,880,894
6,880,927
Why does the Standard Library for C++ not contain hash table implementations?
I was reading over my text book Data Structures and Algorithms: By Mark Allen Weiss and it says that the standard library does not contain hash table implementations of a set or map, but rather compilers can provide hash_set and hash_map with same member functions of the set and map class. Why not just include hash imp...
What you're looking for are called std::unordered_set/map. These are part of C++11, the next version of the C++ standard (due to be finalized in a few months). They were also made available in Technical Report 1 in 2005, which was a list of additions to the C++ standard library between the first standard and the next o...
6,880,920
6,880,946
How to pass Virtually Anything To A Function In C++ (or C)?
I need to pass something like a pointer that takes anything as a function parameter. You know, something without any predefined type or a type that can take anything like this: void MyFunc( *pointer ); And then use it like: char * x = "YAY!"; MyFunc(x); int y = 10; MyFunc(&y); MyObj *b = new MyObj(); MyFunc(b); ...
In C++, Boost.Any will let you do this in a type-safe way: void func(boost::any const &x) { // any_cast a reference and it // will throw if x is not an int. int i = any_cast<int>(x); // any_cast a pointer and it will // return a null pointer if x is not an int. int const *p = any_cast<int>(&x);...
6,881,006
6,881,066
GoogleTest: How to set a breakpoint?
I'm using Visual Studio 2010 C++ with Google test. I have a post-build event on my test project to run the test project. This works and the google test test results are displayed in the visual studio output window. However, now I'd like to set a debug breakpoint to step through a test. When I set a break point in e...
I guess you have a separate project that builds the test. You should just run it under the debugger.
6,881,167
6,881,197
Confused about Virtual Functions C++
I'm a c++ n00b and I'm not sure if I have looked in the right places but I'm confused about this: include <iostream> using namespace std; class Enemy { public: void sayHere() { cout<<"Here"<<endl; } virtual void attack() { } }; class Monster: public Ene...
This has to do with the fact that you don't access your enemies through pointers: Ninja n; Monster m; Enemy *enemies[2]; enemies[0] = &m; enemies[1] = &n; for (int i = 0; i < 2; i++) { enemies[i]->sayHere(); enemies[i]->attack(); } return 0;
6,881,172
6,881,210
C++ Class Memory Model And Alignment
I have several questions to ask that pertains to data position and alignment in C++. Do classes have the same memory placement and memory alignment format as structs? More specifically, is data loaded into memory based on the order in which it's declared? Do functions affect memory alignment and data position or are t...
Do classes have the same memory placement and memory alignment format as structs? The memory placement/alignment of objects is not contingent on whether its type was declared as a class or a struct. The only difference between a class and a struct in C++ is that a class have private members by default while a struc...
6,881,441
6,881,470
Packing an int into a bitfield in C++
I'm converting some code from ASM to C++, the ASM simply looks like so: mov dword ptr miscStruct, eax the Struct looks like: struct miscStruct_s { uLong brandID : 8, chunks : 8, //etc } miscStruct; Is there an easy one-two line way to fill the struct in C++? So far I am using: miscStruct.brandID ...
The literal translation of the assembler instruction is this: miscStruct=*(miscStruct_s *)&Info[0]; The casts are needed because C++ is a type-safe language, whereas assembler isn't, but the copying semantics are identical.
6,882,097
6,882,774
Boost::Intrusive for HPC
How good is boost::intrusive library for high performance computing? I want to use a container for a non-copyable non-assignable class. I was planning to use normal STL with shared_ptr. I found out that boost::intrusive can also be used for the same purpose. So my question is, are they really that efficient? if given ...
Generally, intrusive collections are the most efficient in terms of memory usage. If your goal is to squeeze every last cpu cycle that is the only way to go. Consider a list of boost shared pointers. When creating a new object what happens is: the object allocated from the heap and initialized constructor of boost sha...
6,882,124
6,882,368
How to Run a cuda code using remote Desktop?
I am connecting to my desktop which has an Nvidia card (CUDA compatible) using remote desktop connection. I am doing this because I currently don't have a monitor! Therefore I am temporary using my laptop to connect to my desktop and run my CUDA code. It seams that remote desktop does not recognize the Nvidia card. cud...
As said, you cannot use remote desktop. Instead, you can use a VNC client such as Splashtop Remote Desktop, it is free.
6,882,142
6,882,188
Changing the rendering mechanism of all windows text-boxes system-wide
I need to write a novel and customized algorithm for handling and rendering right-to-left and left-to-right pieces of strings in a text-box, and then I need to make all text-boxes in windows, to use this algorithm. My question is about the second job, that is, how can I change the rendering mechanism of all the text-bo...
Whatever you do, you will never cover all programs with this! If a program uses its own toolkit, or a toolkit not using Win32 built in widgets, any hacks on the Win32 API will have no effect. Tinkering with the Win32 API is possible by injecting a DLL in every process, that hooks into Win32 API calls through debugging ...
6,882,408
6,888,755
how to inspect variable in vc++ express 2008 , throw all the debug session?
I have some hash table that is losing its values at some point in the debug session. My question is, is there any good way to inspect variable (it's inside singleton) throughout the debugging session, even if i pass its class' scope? I want to see in which point it's losing its value.
You can see a variable by its address. For example: class A { public: A() { n1 = 1; n2 = 2; } int n1; int n2; }; void f1() { static A a; } Set breakpoint in f1 and see a variable address: &a 0x00418160 a {n1=1 n2=2} Now you can add this watch: (A*)(0x00418160) 0x00418160 a {n1=1 n2=2} Th...