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,215,467
6,215,567
cmath header confusion
What is the namespace for math functions? Global or std? Consider cos function. It has 3 overloads. But there is also legacy cos from math.h. C doesn't know anything about function overloading. Therefore cos(x) can't be resolved to cos(float). The solution is to call the single precision version explicitly cosf(x). Did...
You get the same functions by including <math.c> and <cmath> in C++, the only differences is the namespace. I.E. including <math.h> also gives you the overload. In theory, in C++03, using <math.h> gives you the symbols defined in the global namespace and also in the std namespace while using <cmath> gives you the symbo...
6,215,484
6,216,770
how can it do other work except "async_wait" in one single thread using boost.asio.deadline_timer
I rewrite a boost.asio example "Timer.3 - Binding arguments to a handler". I think "worker" can work forever and "print" can be called each second. But "print" only is called once. It is very diffcult for me to think why. If this can't work,how can I do other things except "async_wait" in one single thread. #include <i...
You have an infinite loop void worker() { while(1) { ++num; } } so control never returns the first time print() is invoked.
6,215,507
6,215,593
Temporary macro to store another macro and then reverting back
I want to have more control over macros such as assertions (and some logging macros that are not directly under my control). So I decided to do something like this, expecting it to work (in case somebody is wondering, the reason it does not work is that the last undef of MY_ASSERT_COPY invalidates MY_ASSERT right befor...
Some compilers provide #pragma push_macroand #pragma pop_macro to save and restore macro state. Limited portability though.
6,215,511
6,215,646
How to run multiple threads created by loop simultaneous using boost.thread?
I'm using learning the basic of boost.thread. So far, I can create each thread one by one manually to let them run at the same time. However, when creating by loop, it runs sequentially not concurrency anymore. #include <iostream> #include <boost/thread.hpp> void workerFunc() { boost::posix_time::seconds workTime(3);...
for (int i = 0; i < 2; ++i) { boost::thread z(workerFunc); z.join(); } You are starting your thread and then immediately waiting for it to complete! EDIT One of several alternative hacks besides thread groups. std::vector<boost::thread *> z; for (int i = 0; i < 2; ++i) z.push_back(new bo...
6,215,607
6,215,637
Problem with file dependencies and templates on a C++ program
Possible Duplicates: Templated function being reported as “undefined reference” during compilation Why can templates only be implemented in the header file? Hi, I'm having a problem with dependencies in a c++ program that only originates when I use templates. Apparently the compiler is not able to instantiate the t...
The reason is described in detail here. In short, you need to provide the full definition in the header-file, otherwise the compiler cannot instantiate the template.
6,215,664
6,215,715
what type of windows device driver can modify FindFirstFile and FindNextFile?
i need to add some files to results returned by FindFirstFile and FindNextFile under windows. Is this possible by file system filter driver or what type of drivers? Thank you
You can do this by File System Filter Driver. But you can do this by implementing a system wide API hook. I have not tried it before but you really don't need to take the pains of writing the drivers and making the system unstable in case of spoiling the driver stack. System Wide API Hooking API Hooking Revealed
6,215,782
6,215,800
Do unused functions get optimized out?
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?
It depends on the compiler. Visual C++ 9 can do that - unused static functions are removed at compilation phase (there's even a C4505 warning for that), unused functions with external linkage can be removed at link phase depending on linker settings.
6,215,833
6,216,096
How do I convert an ATL/MFC CString to a QString?
Given the encoding of the project is probably Unicode (but not for sure) what is the best way of converting ATL::CString to QString? What I have thought of is this: CString c(_T("SOME_TEXT")); //... std::basic_string<TCHAR> intermediate((LPCTSTR)c); QString q; #ifdef _UNICODE q = QString::fromStdWString(intermediate...
You don't need the intermediate conversion to a std::string. The CString class can be treated as a simple C-style string; that is, an array of characters. All you have to do is cast it to an LPCTSTR. And once you have that, you just need to create the QString object depending on whether the characters in your CString a...
6,215,853
6,215,960
Need some advice to choose the proper container
I'm trying to design a task scheduler to a game engine. A task could be an animation, a trigger controller, etc. My problem is what container to choose. The idea is: when you insert a new task, the container must reorder and put the task in the proper place. Once executed, task could change and be scheduled again or de...
(source: adrinael.net) (original source: Liam Devine)
6,216,232
6,216,621
C++ nested lambda bug in VS2010 with lambda parameter capture?
I'm using Visual Studio 2010, which apparently has some buggy behavior on lambdas, and have this nested lambda, where the inner lambda returns a second lambda wrapped as a std::function (cf. "Higher-order Lambda Functions" on MSDN): int x = 0; auto lambda = [&]( int n ) { return std::function<void()>( [&...
It is not a bug, since n goes out of scope after lambdas return statement, thus the capture by reference is invalidated by the time you use it. int x = 0; auto lambda = [&]( int n ) { return std::function<void()>( // n is local to "lambda" and is destroyed after return statement, thus when you call the std::funct...
6,216,415
6,217,305
Design Patterns in C++ with Qt 4
I have been looking for tutorials or books about design patterns in qt and so far i have found one book, "Introduction to Design Patterns in C++ with Qt 4".Has anyone read this book?.Also,where can i read about design patterns implemented in qt?.
Introduction to Design Patterns in C++ with Qt 4 uses Qt 4.1 to demonstrate its concepts. So much has changed since Qt 4.1 that I suggest first learning about design patterns, and then learning Qt (separately). Once you understand design patterns, you can browse the Qt source code and be able to recognize the patterns ...
6,216,527
6,216,665
Visual Studio C++: Unit test exe project with google test?
Using Visual Studio 2010 C++. I'm experimenting with unit testing and decided to try Google Test (gtest). I have an existing project which compiles to an MFC executable (I'm also interested in how to test a project that compiles to a DLL). My understanding of the convention for unit testing is that you should create...
Either put the functionality you want to test into a static library which is linked into both your test project and your MFC project, or put your files in both projects. The first is more complicated, but the second will cause you to compile everything twice....
6,216,554
6,218,130
cmake glob include while preserving directory structure
I'm new to cmake and I'm trying to install .hpp files while preserving directory structure. So far I have FILE(GLOB files "${CMAKE_CURRENT_SOURCE_DIR}/include/*.hpp" "${CMAKE_CURRENT_SOURCE_DIR}/include/MyLib/*.hpp" "${CMAKE_CURRENT_SOURCE_DIR}/include/MyLib/detail/*.hpp" install (FILES ${files} DESTINATION inclu...
You can use the DIRECTORY variant of the CMake install command. This command will preserve the structure of the copied directory: install(DIRECTORY include/ DESTINATION include FILES_MATCHING PATTERN "*.hpp") If the directory to be copied contains subdirectories that should not be installed, you'll have to e...
6,216,588
6,216,735
UDF calling external C++ code inside SQL Server
Suposse I have an UDF in SQL Server 2008: Create function dbo.ReadXml (@xmlMatrix xml) returns table as return ( select --SOME C++ CODE ) go Is it possible to add a c++ code or call a c++ function inside the UDF?
Onyl if this C++ function was compiled and installed as an extended stored procedure. But extended stored procedures are deprecated and will be removed soon. So your only reliable option is to write a CLR function. It can be a C# CLR function that calls an external C++ dll, or it might be a managed C++ CLR function tha...
6,216,643
6,216,763
Process same file in two threads using ifstream
I have an input file in my application that contains a vast amount of information. Reading over it sequentially, and at only a single file offset at a time is not sufficient for my application's usage. Ideally, I'd like to have two threads, that have separate and distinct ifstreams reading from two unique file offsets ...
Two std::ifstream instances will probably be the best option here. Modern HDDs are optimized for a large queue of I/O requests, so reading from two std::ifstream instances concurrently should give quite nice performance. If you have a single std::ifstream you'll have to worry about synchronizing access to it, plus it ...
6,216,802
6,216,909
Implementing Real Time frequency spectrum for a beginner
I want to develop an application that would take audio(.wav) as input and display its real time simultaneous frequency spectrum . From what i have looked upon the subject , this requires fourier transform of the waves . Can someone suggest where i should start with ? Possible references and books . I want to learn the ...
There are already many libraries to do FFTs for you. No reason to reinvent the wheel. DirectX has an implementation but it might only be in the most recent version. Here's an open source C library for it. If you want to understand the math behind it, here's a simple explanation and here's a complicated explanation.
6,216,854
6,217,087
OpenGL on Android: Any conflicts when calling OpenGL functions in both Java and C++?
In my application, I'm using a 3rd party custom view that calls OpenGL functions in Java, and I'm also calling OpenGL functions in my native C++ code. Should this be a problem? Is there any risk that they could be called at the same time? What is the threading order of OpenGL calls across java/c++?
This should not be a problem, as long as you know what you're doing. The OpenGL Java bindings in Android basically just call the same c++ function. There's not more logic in those calls. So you can basically think of those calls in the same way as if they were direct c++ code. The problem that you are more likely to ru...
6,217,021
6,217,631
Removing Virtual Inheritance
I am working on an embedded project I am trying to remove a virtual number class that has + / - * implemented. removing this class saves a lot of code space so I have replaced + with the following function, if (BASE(h)->type() == FLOAT && BASE(v)->type() == FLOAT) { res = FLOAT(h)->floatValue() + FLOAT(v)->floatVal...
#define GETFLOAT(arg) (BASE(arg)->type() == INTEGER ? INTEGER(arg)->floatValue() : FLOAT(arg)->floatValue()) switch(BASE(h)->type()) { case INTEGER: if (BASE(v)->type() == INTEGER) { res = INTEGER(h)->intValue() + INTEGER(v)->intValue(); break; } case FLOAT: res ...
6,217,286
6,217,658
Uninstalling pocket PC program programmatically
I want to write a program (create an exe file) to uninstall a program in WM 5.0. I was searching in Google but nothing really show a step by step how to do this. I had a step by step instruction on how to install a cab file programmatically, but I can't find something similar to unistall the program. I have seen som...
Try to read this article. If I understood correctly what you need is to pass configuration xml to ProcessConfiguration method. I hope it helps.
6,217,453
6,217,633
Why does boost::is_same<int const&, boost::add_const<int &>::value equal false?
I'm working through "C++ Template Metaprogramming" by Abrahams & Gurtovoy" This isn't actually in chapter two but is something I tried whilst working on the first exercise (2.10, 2.0) which is confusing me: #include <iostream> #include <boost/type_traits.hpp> std::string display(bool b) { return (b ? "true" : "fals...
If you tried the same thing with pointers, as in boost::is_same<int const *, boost::add_const<int *>::type>::value you'd discover that it is also false, since boost::add_const<int *>::type generates int *const type, which is obviously not the same as int const *. Essentially the same thing happens with references, i.e...
6,217,635
7,280,778
C++ BHO (IE addin) issue
I am creating a BHO using helloworld sample. Building Browser Helper Objects with Visual Studio 2005 the BHO is not getting loaded, and i am not able to hit the breakpoints in SetSite function. Please let me know what additional settings are required to register BHO and subsequently debug it. I am using IE9, VS2008. Th...
This is because the debugger is not attaching to the right IE9 process. To work around this you need to dictate IE9 to use a single process for all tabs. This can be done by setting the registry value: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth = 0 Hope this helps.
6,217,734
6,217,748
C++ Why is it calling the function with reference
say i have the following C++ class. class C { int foo() const; int & foo(); }; and i just call myC.foo(), i can see using the debugger that it calls the one with the reference. why? thanks!
It's likely because myC is a non-const value and hence the compiler is prefering the non-const method. The const method will only be preferred when accessed from a const value. For example C value1; value1.foo(); // int& foo(); const C value2; value2.foo(); // int foo() const; EDIT Also, as Oli pointed out, overlo...
6,217,837
6,218,476
'stringstream' argument order trouble
I'm experiencing a weird problem with stringstream. #include "stdafx.h" #include "iostream" #include "sstream" using namespace std; struct Test { float f; }; wstringstream& operator <<( wstringstream& sstream , const Test& test ) { sstream << test.f; return sstream; } int _tmain(int argc, _TCHAR* argv[]...
Short answer The problem is that ss << L"text" gives you a std::wostream, not a std::wstringstream. You only created an operator<< for std::wstringstream, so the next operation (which you're trying to do on a) fails. Long answer When you write something like ss << L"text" << a << endl; you are not invoking a function ...
6,218,080
6,220,613
Open only one instance of QDialog with show() , and also does the Object is deleted if i close the QDialog
in Qt im opening QDialog windows each time i click some item im doing it with new , i like to be sure im opening only one instance of QDialog for each item im clicking : void foo::treeWidget_itemClicked(QTreeWidgetItem *item,nt column) ..... QString groupID = item...
Yes, you should probably keep some kind of list of your dialogs to keep track of which ones are already open. If your GroupID is your unique ID then you could do something like this: QMap DialogMap; void foo::treeWidget_itemClicked(QTreeWidgetItem *item,nt column) { ..... QString groupID = item->data(0, Qt::Us...
6,218,591
6,218,721
c++ std::vector std::sort infinite loop
I ran across an issue whenever I was trying to sort a vector of objects that was resulting in an infinite loop. I am using a custom compare function that I passed in to the sort function. I was able to fix the issue by returning false when two objects were equal instead of true but I don't fully understand the solut...
The correct answer, as others have pointed out, is to learn what a "strict weak ordering" is. In particular, if comp(x,y) is true, then comp(y,x) has to be false. (Note that this implies that comp(x,x) is false.) That is all you need to know to correct your problem. The sort algorithm makes no promises at all if you...
6,218,651
6,218,849
Best way to alias methods of member object? "Passthrough methods"
Consider the following code: class Rectangle { public: // Constructors Rectangle(){ init(0,0); } Rectangle(int h, int w){ init(h,w); } // Methods void init(int h, int w) { _h = h; _w = w; } // Getters / Setters double get_h(void){ return _h; } double get_w(void)...
The problem, I think, is conceptual. Your design is quite un-object oriented in that the house does not represent an entity, but rather provides a bit of glue around the components. From that standpoint, it would make more sense to provide accessors to the elements, rather than pass-through functions: class House { ...
6,218,667
6,220,526
C style, C++ streams or Win32 API File I/O?
I read C++ Streams vs. C-style IO? (amongst other pages) to try to help me decide which way to implement some file IO in a project I'm working on. Background I'm fairly new to C++ and Windows programming, I've traditionally worked in C and command line applications. Apologies ahead of time for the n00b-ness of this q...
To take a broader look, direct use of Win32 is good if you need a tiny application with no additional dependencies. For anything that C++ iostreams does better, you probably want to look at Boost::Spirit. Seems like it has all the type-safety of iostreams, with much better performance. You really have two problems her...
6,218,793
6,218,840
Externing functions in C++
When externing a function in the cpp file does the compiler treat these differently? extern void foo(char * dataPtr); void foo(char *); extern void foo(char * ); I am wondering because I have see all these in code and not sure what the difference is.
Case by case: extern void foo(char * dataPtr); functions have external linkage by default, so the extern is not necessary - this is equivalent to: void foo(char * dataPtr); Parameter names are not significant in function declarations, so the above is equivalent to: void foo(char * ); Use whichever you feel ha...
6,218,812
6,219,150
Implementing comparison operators via 'tuple' and 'tie', a good idea?
(Note: tuple and tie can be taken from Boost or C++11.) When writing small structs with only two elements, I sometimes tend to choose a std::pair, as all important stuff is already done for that datatype, like operator< for strict-weak-ordering. The downsides though are the pretty much useless variable names. Even if I...
This is certainly going to make it easier to write a correct operator than rolling it yourself. I'd say only consider a different approach if profiling shows the comparison operation to be a time-consuming part of your application. Otherwise the ease of maintaining this should outweigh any possible performance concerns...
6,218,813
6,218,958
How do i get type from pointer in a template?
I know how to write something up but i am sure there is a standard way of passing in something like func<TheType*>() and using template magic to extract TheType for use in your code (maybe TheType::SomeStaticCall). What is the standard way/function to get that type when a ptr is passed in?
I think you want to remove the pointer-ness from the type argument to the function. If so, then here is how you can do this, template<typename T> void func() { typename remove_pointer<T>::type type; //you can use `type` which is free from pointer-ness //if T = int*, then type = int //if T = int****, t...
6,218,912
6,219,054
sending user-defined structure using WM_COPYDATA message
How can i send my structure to other application and recieve it using WM_COPYDATA message?
Most of this is explained by MS at Using Data Copy. Is there anything missing in that example?
6,218,936
6,219,000
Virtual methods whose type is known at compile-time
If I do something like: Dog dog; //class with virtual methods Cat cat; //class from same base as Dog dog.eat(); //call virtual method cat.eat(); //call virtual method Then the eat()s will be normal method calls and will not require the v-table - correct? I can assume that it would run identical to a non-virtual metho...
When you're using object.member - you're not dereferencing a pointer, so there's no effect to the virtual methods. Virtual comes into effect only when you have a pointer which can be polymorphic and dynamic dispatch is used. For example: Cat cat; Animal *cat2 = &cat; cat.eat(); // direct call //... a lot of other code ...
6,219,400
6,219,450
C++ - Initializing a static map as a private class member
Let's say I was quite bored one late evening and after catatonically staring at the computer monitor for a few hours, I decided to implement an aggregate C++ class to manage colors for drawing pixels, because I've obviously gone mad. For starters, we'll just tell the (probably singleton) ColorManager object what color ...
#include <map> #include "Color.h" enum COLOR { RED = 0, BLUE, GREEN, YELLOW, ORANGE, WHITE, BLACK, BRICKS_FROM_A_DISTANCE_ON_AN_UNUSUALLY_SUNNY_AFTERNOON, // etc COLOR_COUNT }; class ColorManager { typedef std::map<COLOR, Color> ColorMap; public: ColorManager(); Color getColor(COLOR color...
6,219,941
6,219,983
What does __declspec(uuid(" ComObjectGUID ")) expand to?
I have a piece of code that uses Microsoft-specific extension to the C++: interface __declspec(uuid("F614FB00-6702-11d4-B0B7-0050BABFC904")) ICalculator : public IUnknown { //... }; What does this sentence expand to? How can I rewrite it with ANSI C++?
It's not a macro so it doesn't "expand" to anything. It merely decorates the type with a given UUID in the object file metadata, which can then be extracted later with the __uuidof operator.
6,219,986
6,220,728
Pthreads dying in the middle of a mutex lock
I was thinking of the following scenario happening while a pthread is running: pthread_mutex_lock(...); ... // <- Thread dies here pthread_mutex_unlock(...); in other words, a pthread starts, at some point it locks a mutex, and for some reason, it dies before it is able to call the matching unlock function, either bec...
Killing threads is never very useful. (unless you can afford to SIGKILL/abort the whole process anyway). Instead unwind the stack with an exception and use RAII. If your process/OS has become so unstable that random thread aborts happen, I think you'll have other worries and the resulting mess is not the process' respo...
6,220,006
6,220,103
Hashing, polygonal shapes relative to to x,y location
I am trying to build a polygonal shape tool and have it calculate against its area to find if a point exists inside or out side the area. These examples work well you you want to calculate on every object every time, but I am looking for a way to "HASH" the shape/area of a polygon relative to a spacial location, then T...
http://en.wikipedia.org/wiki/Geometric_hashing I think this explains everything nicely. Given that it can really only be used to determine if two objects are similar (given that the difference is a simple set of transformations), it can be shown that actual spatial information is lost. Therefore the answer to your ques...
6,220,337
6,220,432
Code duplication and template specialization (when the specialized function has different return types)
I am creating a templated class D<N>, with a method (operator(), in this case) that returns different types, depending on the value of N. I could only make this work by creating two separate class declarations, but this came at the cost of a lot of code duplication. I also tried to create a common base class to throw t...
You can use the Curiously Recurring Template Pattern. template<int N, template<int> typename D> struct d_inner { D<N-1> operator()(int x) { return D<N-1>(static_cast<D<N>*>(this)->yell(x)); } }; template<template<int> typename D> struct d_inner<1, D> { int operator()(int x) { return static_c...
6,220,748
6,221,026
Send message to property page from DirectShow filter
I've written a Directshow filter that derives from CTransInPlace and implements a single property page. Passing data to the filter from the property page and pulling data from the filter to the property page works great (using a defined interface), but I want to send a notification from the filter to the property page...
You can implement a callback function in the filter. Take a look at the samplegrabber filter. There is a simular situation: The samplegrabber filter implements the ISampleGrabber Interface which includes a SetCallback function. The class which needs to receive the callback, needs to implement the ISampleGrabberCB Inte...
6,220,803
6,220,940
C++ - Single local class instance for entire program duration
I'm working on a lil' game engine in C++, and decided to do it all OOPily (heavy use of classes.) It's intended to be (theoretically) cross-platform, so I have an 'Engine' class, an instance of which is created by the 'OS Module', which is WinMain for Windows (the platform I'm developing it for first.) I have three mai...
Game engines are not prime candidates for cross-platform'ness since they usually involve efficient interaction with low-level API's (which are not cross-platofrm). The size of a class depends on the member variables it contains, not the number of functions it implements. Stack space is usually small (http://msdn.micros...
6,220,930
6,220,975
How to load Multidimensional array values into vector?
This is part of the code (header and the main part): #include <iostream> #include <sstream> #include <string> #include <gl\GL.h> #include <gl\GLU.h> #include <glut.h> #include <RassHost.h> #include <api\iomap.h> #include <api\iotrans.h> #include <api\cgeometry.h> #include <vector> using namespace std; int main() { ...
You'll need to create a vector of vectors: vector< vector<OBJECT3D_RCN_TYPE> > _objects; Then just fill it like a normal vector. I'd post more code, but you need to know the dimensions of the array, and I can't see those from the code.
6,220,976
6,237,109
Are both method declarations "pass by reference"?
What is the difference between these two ways of writing a function in C++? Are they both "pass by reference"? By "pass by reference", I mean that the function has the ability to alter the original object (unless there is another definition, but that is my intention). From my understanding, when you call f1, you pass ...
f1 (Object& obj) {} When you call f1, for example f1(o1): obj becomes the other name for o1 (alias), that's it. So o1 is just alias for obj; they have the same address (you can check that &obj==&o1 is true) f2 (Object* obj) {} When you call f2,for example f1(&o1): obj is created and initialized with &o1; that i...
6,221,543
6,221,608
N*(connect + send + close) vs (Nagle disable + connect + N*send + close) , N > 1
I'm new to socket programming (as you already figure out by my silly question), but keeping my shame aside, I'm writing a program using TCP posix. My constrain is the following: The message to be sent from the client to the server,should be read as byte stream and while my application is not high performance, the messa...
In your case, disabling Nagle is exactly what you want to do. Just remember that every call to write() is going to transmit your data immediately. So be sure you are packing your entire message together and then calling write() (or writev()) once when you are ready to send; do not call write() repeatedly with small pa...
6,221,610
6,221,635
std::vector and Constructors
Which constructor does std::vector call when it is making a new instance of the object it's containing? I am under the impression it calls a default constructor but what if one is not defined or is the compiler doing that for me? Particularly in a case as such: class Foo { public: Foo(int size) { ...
At a minimum, for std::vector<T> to compile, T must be copy-constructible, and copy-assignable. If you want to use std::vector<T>::vector(int) (or std::vector<T>::resize()), then T must have be default-constructible. If any of these requirements are not fulfilled, the code will not compile. ... C++03 standard, sectio...
6,221,621
6,221,929
SQL little table allocated in memory
Is there a way to make SQL Server to store a table with 10 attributes and 10 rows like this on memory? a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 ---------------------------------------- 138 498 365 345 500 473 498 125 134 800 448 498 362 348 500 463 498 625 165 700 468 498 625 329 500 435 498 625 345 600 437 701 365...
Don't try to dictate to SQL Server how to handle memory for things like this. It's a declarative language - you tell it what you want and it figures out how to do it. Keeping it in memory only would be an issue for recovery. That being said, once you create the table it will be kept in memory once it's written to dis...
6,221,799
6,221,809
std::string == not working?
When I do: std::string name = targetBone->getName(); if(name == "Pelvis") { return; } I get: Error 1 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion) How do I resolve this error ? Thanks
Have you included string in your cpp file #include <string> This usually happens because the compiler need to see the definition of string class that resides in that included file to verify that it indeed declares an operator that takes a char*
6,221,812
6,221,948
Using in line anonymous structures for organization
In the following code I have placed anonymous structures inside of my class declaration to hopefully improve the readability of it. class example { private: struct barrier { boost::barrier playlist_avaliable; boost::barrier display_sync; barrier( ) : playlist_avaliable( 2...
Ok, some random thoughts: Leave out the 'barrier' after struct. It is redundant. It's barely more than syntactic sugar. It is a nice way to group variables. Whether you should use the struct may be influenced by the question how much transparent the inner struct should be to the class example. For example, do you want...
6,221,840
6,221,865
push_back vector of vector
i got some problem with vector of vector. in my program, i have defined a dynamic memory for vector of vector and did the resize and push_back the elements. vector<vector<double> > *planes = new vector<vector<double> > planes->resize(s_list->size()); // size of another vector that i need to use vector<int>::iterator s_...
Use at instead of push_back planes->at(i).at(0)=lenght; planes->at(i).at(1)=width; push_back() adds new items, therefore you end with with 4 items in each vector. You should use at() to modify the existing entries. Better still is to use a vector< pair<double,double> >, assuming you will always have two items.
6,221,934
6,223,012
How to go back to the beginning of a file after reaching .eof() in C++?
I just tried this, but don't work, maybe because I'm reading character by character? char character; while (!file.eof()) { character = file.get(); cout << character; }
OK, it works. The trick is call file.clear(); file.seekg(0, ios::beg); just after the iteration. Sorry :(
6,221,947
6,222,458
Ensuring that a static method gets called before main()
I have a collection of worker classes, and I need to be able to construct instances of these classes dynamically with a single factory. The reasoning behind this is that new worker classes are written frequently and I'd rather not have to update a factory class per worker type every time I add a new worker class. The w...
This sounds like the linker pulling in only the objects it needs, and not pulling in the one with the global variable. Then the global simply doesn't exist, so initialization order is a moot point. It's a real problem with static libraries, with no universal solution. Armed with the knowledge that the linker grabs an ...
6,221,965
6,222,108
C++ multi dimensional array function parameter
How can I pass a two or multi dimensional array as a parameter of a function without defining its size?? Here is my example code: void test(int *a) { a[0][0] = 100; } int main() { int a[2][2]; test(a); cout<<a[0][0]; }
If you're working exclusively with statically-sized, stack-allocated arrays, then a function template will do exactly what you're asking for: #include <cstddef> #include <ostream> #include <iostream> template<std::size_t N, std::size_t M> void func(int (&arr)[N][M]) { std::cout << "int[" << N << "][" << M << "]\n"...
6,222,086
6,237,325
Scrollbar arrows do not get redrawn while thumbtrack gets redrawn correctly
I have created a custom control by registering a new class for it and instantiating it as a child to a top-level window. The control is basically a list. In order to save some effort, I decided to use the WS_VSCROLL window class in order to add scrollbars to my custom control. My trouble is that when I resize the windo...
You could try sending an extra WM_NCPAINT message to the column in your WM_SIZE handler. But I thought that happens automatically. But I find the solution proposed by BrendanMcK to make use of a default listbox the winner. Pity it's not an answer.
6,222,153
6,225,471
retrieving 'pre windows 2000 logon' name from LDAPMessage object in win32api C++
I've been asked to look at windows service which retrieves data from an Active Directory tree using the win32 LDAP API and outputs JSON data to a text file. It works fine but I need to modify it so that the i get the 'pre windows 2000' login name. The service is written in c++. The service already successfully retrieve...
Be careful, the Domain part of the 'pre windows 2000 domain' can be completly different from the user Principal Name (user@domain) use to logon onto Active-Directory. the DOMAIN is the Primary Domain Controleur name or the Netbios domain name. DOMAIN is created during domain creation, by default it's part of the DNS na...
6,222,205
6,222,236
Passing a 2d vector into a function c++
I have a function (assign) in a class (graph) in a header file. The objective of this function is to print a 2d vector: class Graph { public: void printvec(vector< vector<double> >&PRRMap); }; I call this function from a cpp file such as: Graph G; G.printvec(vector< vector<double> > &PRRmap); I get the following ...
void printvec(vector< vector<double> >&PRRMap); This is a declaration. It includes formal parameters, each of which specifies a type and an optional name. G.printvec(a_map); This is a function call. It includes actual parameters, each of which is an expression, aka value. The type is not named during a function ca...
6,222,383
6,222,416
Convert 1D vector to 2D vector
I got a compiling error when using std::copy to convert a 1D vector to a 2D vector. int main() { std::vector< std::vector<float> > v2D(10, std::vector<float>(10, 0.0)); std::vector<float> v1D(100, 0.0); for (int i = 0; i < 100; ++i) v1D.push_back(i); for (unsigned int j = 0; j < 10; j++) ...
std::back_inserter takes a container, not an iterator. Change std::back_inserter(v2D[j].begin()) to std::back_inserter(v2D[j]). Note that this will be calling .push_back() on the std::vector<float> at v2D[j], so you probably also want to change std::vector< std::vector<float> > v2D(10, std::vector<float>(10, 0.0)); to ...
6,222,385
6,222,439
Binary File Input,Output and Append C++
I'm trying a basic input,output(and append) in C++ here is my code #include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> using namespace std; void escribir(const char *); void leer(const char *); int main () { escribir("example.bin"); leer("example.bin"); system("pause"); re...
The problem doesn't seem to be with writing the file but rather with reading and displaying it, namely here: memblock = new char [size]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); cout<< memblock<<endl; Displaying with cout expects the string to be null terminated. But you only allocated enoug...
6,222,583
6,222,602
How to compare strings
I wanted to compare a string without actually defining one of them as a string, something like this, if (string == "add") Do I have to declare "add" as a string or is it possible to compare in a similar way?
In C++ the std::string class implements the comparison operators, so you can perform the comparison using == just as you would expect: if (string == "add") { ... } When used properly, operator overloading is an excellent C++ feature.
6,222,592
6,222,607
Align Integer using cout in C++
I need C++ to use cout to print: Header 1 2 3 4 5 10 11 12 instead of Header 1 2 3 4 5 10 11 12 How should I format this using cout?
use the IO manipulator setw #include <iostream> #include <iomanip> int main() { std::cout << "Header\n"; for(int i=1; i<13; ++i) std::cout << std::setw(6) << i << '\n'; }
6,222,635
6,222,971
PeekMessage not getting the message?
I've created a custom message type for use in resizing my Window, called WM_NEED_RESIZE. I've defined it in my .h file, and initialized in my .cpp file. I have also registered my WindowProc function to accept messages. Here is the code for these items: const uint32 WindowsGLWindow::WM_NEED_RESIZE = WM_USER + 100; LO...
Dont use std::cout expecting to see that output in your debugger, insted use OutputDebugString(); . You need to pass your class pointer to the last parameter of your call to CreateWindowEx, then retrieve that pointer from the LPCREATESTRUCT passed to you in the LPARAM of WM_CREATE, your class pointer will be in the l...
6,222,648
6,223,554
Using -rpath and $ORIGIN with libtool-based projects?
I am trying to incorporate a libtool-based package into a project of my own, perhaps in a non-standard way. Here is my goal: Build external project: ./configure --prefix=$HOME/blah --etcetera && make && make install Build my own project which depends upon the external project's shared libraries and executables at ru...
Among the options presented here on Rpathissue on the debian Wiki, using chrpath in your 'install' step or some post-processing script sounds like a viable option. (It's available on a bunch of distros via your favorite package manager.) It doesn't require patching libtool which is a plus IMO. Note that it has some lim...
6,222,655
6,223,658
C++: How to pass a generic function name?
I am building a program in c++ where the user can set a function to be called when user defined conditions are reached. I am only a little experienced with c++. I know how to do this in python. You would simply define functions and put the names of said functions into a structure (I always used a dictionary). When y...
Your Python code actually translates to C++ pretty much directly: # Python: # Create a dictionary mapping strings to functions methods = { "foo" : foo, "bar" : bar } // C++: // create a map, mapping strings to functions (function pointers, specifically) std::map<std::string, void(*)()> methods; methods["foo"] = foo; ...
6,222,846
6,230,025
Help with Inverse Kinematics Algorithm
I'm trying to implement CCD Inverse Kinematics in 2D This function is supposed to do 1 iteration of CCD Right now as a test case I start it on a left foot and have it stop at the pelvis. every time this function is called, the skeleton's bones are updated. The way my bones work is: getFrameX,Y,Angle return the absolute...
No, there is nothing obviously wrong in the program listing you have given. You are correctly computing the change of angle rotAng and the new position (endX, endY) of the end-effector. You can compute rotAng more simply as double rotAng = atan2(curToTargetY, curToTargetX) - atan2(curToEndY, curToEndX); which giv...
6,223,355
6,223,371
Static variables in member functions
Can someone please explain how static variables in member functions work in C++. Given the following class: class A { void foo() { static int i; i++; } } If I declare multiple instances of A, does calling foo() on one instance increment the static variable i on all instances? Or only the one it was ...
Since class A is a non-template class and A::foo() is a non-template function. There will be only one copy of static int i inside the program. Any instance of A object will affect the same i and lifetime of i will remain through out the program. To add an example: A o1, o2, o3; o1.foo(); // i = 1 o2.foo(); // i = 2 o3....
6,223,390
6,223,483
How can I use std::hex for my custom uint128 type?
What is the correct syntax to overload (or whatever is actually is) std::hex, so that its functionality can be extended to non standard integers? i wrote this version of uint128_t
std::hex is just a manipulator which set some of the formatting flags on the stream. You can get them using ios_base::flags() and use the result in your operator<<. You probably should also use ios_base::width and ios_base::precision. If you want more settings than what is provided, ios_base::xalloc, ios_base::iword,...
6,223,530
6,223,938
Storing #define macro value in temporary and re-use it
Is there any way to store a macro value into a temporary and reuse it. pseudo Example: #define X 0 #ifdef X #define T X #undef X #define X (T + 1) // now X should be 1 #endif
I don't see a way to achieve what you ask for. Depending on what you want to do with that, the use of __COUNTER__, a common extension, could help you.
6,223,802
6,223,866
API to parse PSD files
I am trying to parse Photoshop PSD files and I want to extract layer information, including text. Is there any API in Objective-C that can help me to extract this information from PSD files?
There is no framework or 3rd party parser available for parsing the PSD file in Objective-C But there is one available in C language, Which you could use with your objective-C code Forum Source: Is there a PSD file parser for Objective-C? I want to replace a layer image and output the result as an NSImage. load layer...
6,223,863
6,223,902
GCC inline assembly error: Cannot take the address of 'this', which is an rvalue expression
I'm still fighting with GCC - compiling the following inline assembly code (with -fasm-blocks, which enables Intel style assembly syntax) nets me a strange error Cannot take the address of 'this', which is an rvalue expression... MyClass::MyFunction() { _asm { //... mov ebx, this // error: Canno...
That's because the compiler might decide on its own to store this in a register (generally ECX) instead of a memory cell, for optimization purposes, or because the calling convention explicitly specifies it should do that. In that case, you cannot take its address, because registers are not addressable memory.
6,223,948
6,224,156
How do you judge the (real world) distance of an object in a picture?
I am building a recognition program in C++ and to make it more robust, I need to be able to find the distance of an object in an image. Say I have an image that was taken 22.3 inches away of an 8.5 x 11 picture. The system correctly identifies that picture in a box with the dimensions 319 pixels by 409 pixels. What ...
I don't know if you changed your question at some point but my first answer it quite complicated for what you want. You probably can do something simpler. 1) Long and complicated solution (more general problems) First you need the know the size of the object. You can to look at computer vision algorithms. If you know t...
6,224,121
6,224,179
Is `new (this) MyClass();` undefined behaviour after directly calling the destructor?
In this question of mine, @DeadMG says that reinitializing a class through the this pointer is undefined behaviour. Is there any mentioning thereof in the standard somewhere? Example: #include <iostream> class X{ int _i; public: X() : _i(0) { std::cout << "X()\n"; } X(int i) : _i(i) { std::cout << "X(int)\n"; ...
That would be okay if it didn't conflict with stack unwinding. You destroy the object, then reconstruct it via the pointer. That's what you would do if you needed to construct and destroy an array of objects that don't have a default constructor. The problem is this is exception unsafe. What if calling the constructor ...
6,224,359
6,226,731
Qt: Can child objects be composed in their parent object?
In Qt, can I embed child widgets in their parent via composition, or do I have to create them with new? class MyWindow : public QMainWindow { ... private: QPushButton myButton; } MyWindow::MyWindow () : mybutton("Do Something", this) { ... } The documentation says that any object derived from QObject will...
The non-static, non-heap member variables are deleted when that particular object's delete sequence starts. Only when all members are deleted, will it go to the destructor of the base class. Hence QPushButton myButton member will be deleted before ~QMainWindow() is called. And from QObject documentation: "If we delete ...
6,224,598
6,224,777
Is there a cleaner way to register Qt custom events?
I need to create several custom event classes for a Qt application. Right now, it looks like I will need to implement the following event type registration code for each event class: class MyEvent : public QEvent { public: MyEvent() : QEvent(registeredType()) { } static QEvent::Type eventType; private...
That's what templates are for. They can be used with constant integral parameters, which need to be known at compile time too: enum EventNames { UpdateEvent,... } template<EventNames E> class MyEvent : public QEvent { public: MyEvent() : QEvent(registeredType()) { } static QEvent::Type eventType; pri...
6,224,791
6,226,331
How to handle events for dynamically created objects in MFC?
I am wondering how I can handle an event for a dynamically created variable, e.g. a list control. CListCtrl* pList = new CListCtrl();<br/> pList->Create(...); How can I handle the event LVN_ITEMCHANGED for pList? OnLvnItemchangedList(NMHDR *pNMHDR, LRESULT *pResult) { //do stuff } Do I have to create an extended C...
LVN_ITEMCHANGED is sent through WM_NOTIFY message from control to its parent so you just need to add LVN_ITEMCHANGE handler function in parent's class (e.g. CMyDlg): In header file: class CMyDlg : public CDialog { ... protected: afx_msg void OnLvnItemChanged(NMHDR *pNMHDR, LRESULT *pResult); ... } In source f...
6,224,970
6,225,203
Solving equation. Counting (x,y)
I'm having a trouble with my math: Assume that we have a function: F(x,y) = P; And my question is: what would be the most efficient way of counting up suitable (x,y) plots for this function ? It means that I don't need the coordinates themself, but I need a number of them. P is in a range: [0 ; 10^14]. "x" and "y" are ...
x*y - ((x+y)/2) + 1 == P is equivalent to (2x-1)(2y-1) == (4P-3). So, you're basically looking for the number of factorizations of 4P-3. How to factor a number in C or C++ is probably a different question, but each factorization yields a solution to the original equation. [Edit: in fact two solutions, since if A*B == C...
6,225,070
6,226,513
Is there an equivalent of gcc's -Wshadow in visual C++
-Wshadow will "Warn whenever a local variable shadows another local variable.". Is there an equivalent in Visual C++ (2008)? I tried /W4 but it didn't pick up on it. I also tried Cppcheck but that didn't see it either. e.g. if I inadvertently do: class A { private: int memberVar; public:...
I am afraid no. You could perhaps try compiling your code with Clang: it has this warning (and a lot of others) it has a compatibility mode for MSVC headers (and can build most of MFC) We use gcc at work, to build our code, but compile with Clang regularly to test the code conformance to the Standard and benefit from...
6,225,375
6,225,874
Idiomatic use of std::rel_ops
What is the preferred method of using std::rel_ops to add the full set of relational operators to a class? This documentation suggests a using namespace std::rel_ops, but this seems to be deeply flawed, as it would mean that including the header for the class implemented in this way would also add full relational opera...
I think that the preferred technique is not to use std::rel_ops at all. The technique used in boost::operator (link) seems to be the usual solution. Example: #include "boost/operators.hpp" class SomeClass : private boost::equivalent<SomeClass>, boost::totally_ordered<SomeClass> { public: bool operator<(const Some...
6,225,464
6,225,557
"Define" Macro Concatenation and _TEXT
is there any way of concatenation #define macros in c++ (ms compiler)? I have existing code like this: #define LOG_FILENAME _TEXT("VendorBlaBlaDriver.log") #define REGISTRY_FILENAME _TEXT("VendorBlaBlaDriver") #define VENDOR_NAME _TEXT("VendorBlaBla") I wanna do the following: #define NAME_PART1 "VenorBlaBla" #define ...
You can't apply the _TEXT macro twice. or on multiple strings, but you can concatenate the results. I.e. #define LOG_FILENAME _TEXT(NAME_PART1) _TEXT(NAME_PART2) _TEXT(".log") However, you really shouldn't bother. The _TEXT macro was used around the turn of the century, when there were still non-Unicode platforms aro...
6,225,469
6,225,950
GCC inline assembly error: block assembly operand not recognized
I've got yet another error trying to compile with Apple GCC 4.2.1 using the -fasm-blocks argument (which enables Intel style assembly syntax) inline assembly code which worked in MSVC: block assembly operand not recognized, label 'LASM$TYPE' used but not defined: typedef struct _MyStruct { int data; //... }MySt...
TYPE is an MSVC-specific asm keyword. Here it just means sizeof. I tried to find some gcc asm-block documentation on the web, but I gave up after ten minutes. Try add edi,sizeof(MyStruct) and variants. I don't have an Apple, so I can't try it out for you. Updated to answer question in comment: Try this: add edi,__offs...
6,225,483
6,226,580
From C ++ to Haskell Classes and States
I have to transform this C++ code class A { public: int x_A; void setX_A (int newx) { x_A = newx; } void printX_A() { printf("x_A is %d", x_A); } }; class B : public A { public: int x_B; void setX_B (int newx) { x_B = newx; } void printX_B() { prin...
I think your problem is that you don't have a nice way to specify which object you are operating on. To solve the matter I propose using a separate program state, enclosing both of the objects: data MainState = MainState { objA :: FieldsA, objB :: FieldsB } Now your main function monad can look like this: type Main t ...
6,225,587
6,225,849
member function pointer and callbacks
Hi I am trying to pass a callback which is a member function. I understand that a function pointer and a member function pointer are different and have tried to create a wrapper and use a static cast and the void pointer. Unfortunately I am missing something as my code produces an error at compile Error 16 error...
The problem is most likely, from what you show, that dSpaceCollide just wants a typedef void (*dNearCallback)(void*,dGeomID,dGeomID) callback, that is, a function with a single void* user-data pointer and the two dGeomIDs as parameters. The void* is whatever data you passed to the dSpaceCollide then. Assuming dSpaceCo...
6,226,210
6,226,238
Writing a double type value to a text file
The below code is writing unreadable characters to the text file: int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { double value = 11.23444556; char *conversion = (char *)&value; strcat (conversion, "\0"); myfile.write (conversion, strlen (conv...
Why don't you simply do this (updated answer after the edit in the question): #include <iomanip> myfile << std::fixed << std::setprecision(8) << value; myfile.close(); Now, you can see the actual number written in the file. See the documentation of std::setprecision. Note: you have to include the <iomanip> header...
6,226,265
6,254,265
Resizing view from cvShowImage
I don't want to resize the entire image structure, but the images I am working with are too large to easily view with cvShowImage. Is there a way to resize their view within the window created by cvShowImage?
No there isn't, you will have to create a new image structure and use cvResize.
6,226,381
6,226,421
Unexpected output of C code
What would be the output of this program ? #include<stdio.h> #include<conio.h> void main() { clrscr(); int x=20,y=30,z=10; int i=x<y<z; printf("%d",i); getch(); } Actually i=20<30<10, so the condition is false and the value of i should be 0 but i equals 1. Why?
This int i=x<y<z; doesn't work the way you intended. The effect is int i=(x<y)<z;, where x<yis evaluated first, and the value true is then compared to z. Pascal points out below that in C the result of the comparison is 1 instead of true. However, the C++ true is implicitly converted to 1 in the next comparison, so t...
6,226,490
6,226,509
C++ multi dimensional array
Possible Duplicate: Multi-dimensional array and pointers in C++? Hi, In 1D I can declare an array like, int *image = new int[W*H]; But in 2D how can I declare an array? int *image = new int[W][H]; -- is it wrong??
int *image = new int[W][H]; -- is it wrong?? It will NOT compile. You should compile your code first, to know the answer of your question. I think you want to do this: //memory allocation int **image = new int*[W]; for(size_t i = 0 ; i < W ; i++ ) image[i] = new int[H]; //use it as for(size_t i = 0 ; i < W ; i++ ...
6,226,626
6,226,667
C++ stl list two structures cross-reference
I have such code with 2 structures: #include <list> using namespace std; struct Connection; struct User; typedef list<Connection> Connections; typedef list<User> Users; struct User { Connections::iterator connection; }; struct Connection { Users::iterator user; }; But when I try to compile it, the com...
You're using incomplete type as type argument to std::list which invokes undefined bevahior according to the C++ Standard. §17​.4.3.6/2 says, In particular, the effects are undefined in the following cases: — if an incomplete type (3.9) is used as a template argument when instantiating a template component. So one...
6,226,899
6,226,926
console program exits
Possible Duplicate: How to stop C++ console application from exiting immediately? I have the following console program: #include <iostream> using namespace std; int main() { int a; int b; cout<<"Enter a"; cin>>a; cout<<"Enter b"; cin>>b; int result = a*b; cout<<"You entered"<<a<<"and you entered"<<b<<"...
What about adding system ("pause"); before return 0; statement?
6,226,907
6,227,394
Given filesystem pathname, how to retrieve corresponding ABSOLUTE ITEMIDLIST?
Looks like it can be done in one call or two, but which functions i have/must/should to use for that? I'm looking for best-practice approach, eg: API specially designed for path -> idl translation.
If it's really a file-system path, call ILCreateFromPath. If you need to handle non-file-system objects as well (like My Computer, or Network Neighborhood), then use SHParseDisplayName.
6,227,256
6,227,506
GCC error: Cannot apply offsetof to member function MyClass::MyFunction
After trying to replace the offset keyword with __offsetof while trying to compile with Apple GCC 4.2.1 using the -fasm-blocks argument (which enables Intel style assembly syntax) inline assembly code which worked in MSVC, I get an error: Cannot apply offsetof to member function MyClass::MyFunction class MyClass { ...
offsetof gets the offset of a member from the start of a structure, but functions are not members in that sense (not even virtual functions). what you are probably after is the offset keyword: class A { int Func1() { return 1; } }; __declspec(naked) int GetAddress() { __asm { mov ea...
6,227,418
6,227,459
Check palindrome in C++/Java
Possible Duplicate: Check string for palindrome Hello experts. I am asked, if it is possible to find whether a string is palidrome of another string in just one line of code in C++/Java. If yes, then how? Can any one answer. Thnx for ur view.
In Java, String does not have a reverse method. StringBuilder has though, so you can still do it in one line: boolean palindrome = str.contentEquals(new StringBuilder(str).reverse()); Ideone.com demo
6,227,617
6,227,673
Overload method/operator with inheritance won't work
I wrote code when one class has only constant access to its content, and that was inherited by other class which provides the same method, but with normal access to its members. When I try to compile it by gcc I get following error code: error: passing ‘const A’ as ‘this’ argument of ‘void A::operator()()’ discards qua...
The const method is not accessible, the base class version is hidden by the derived class version, an annoying problem. You need using ConstA::operator() to bring it into the scope of A. class A : public ConstA{ public: using ConstA::operator(); void operator()(){ printf("non-const\n"); } }; For further rea...
6,227,970
6,228,011
How to see if a key is present in a map?
I hav two stl maps like map<int,int> and i want to compare them.. so here is the code.. map <int, int> a,b; insert into a and b; map<int,int>::iterator i; for(i=a.begin();i!=a.end();i++){ if(what should be here?) then cout << (*i).first << " also present in b" << endl; } I was hoping that something like...
Use map::find as: for(i=a.begin(); i!=a.end(); i++) { if( b.find(i->first) != b.end() ) std::cout << (*i).first << " also present in b" << std::endl; } Note i->first and (*i).first are same.
6,228,309
6,228,331
C++ Problem with a class template
Why won't this template compile? template <class K, class V = Referenced> class Cache { public: Cache(); ... }; template <class K, class V> Cache::Cache() <==== location of compiler error (see below) { ... } ERROR error: 'template<class K, class V> class Cache' used without template parameters
You need to specify the template parameters: template <class K, class V> Cache<K, V>::Cache() { ... }
6,228,426
6,228,479
initialisation list in c++
I barely know c++.Not an expert. I am looking through an already existing code. I could not able to understand this following code. typedef enum { eEvent_MsgOk, eEvent_InvalidMsgId, eEvent_Failure, } eEventType; class Rs232Event { public: Rs232Msg* m_pMsg; eEventTy...
m_pMsg isn't an Rs232Msg class. Rather, its a pointer to an Rs232Msg class. All that is being copied is a pointer to an already-existing instance of that class, so the constructor isn't being invoked here.
6,228,847
6,231,753
Parsing nested data in boost-spirit
I need parse some text-tree : std::string data = "<delimiter>field1a fieald1b fieald1c<delimiter1>subfield11<delimiter1>subfieald12<delimiter1>subfieald13 ... <delimiter>field2a fieald2b fieald2c<delimiter1>subfield21<delimiter1>subfieald22<delimiter1>subfieald23 ..." where <delimiter>,<delimiter1> is part of std::str...
The list parser is you friend: namespace qi = boost::spirit::qi; // tokenize on '<delimiter1>' and return the vector rule<std::string::iterator, qi::space_type, std::vector<std::string>()> fields = *(char_ - "<delimiter1>") % "<delimiter1>"; std::string data("<delimiter>field1a fieald1b ..."); std::vector<std::ve...
6,228,915
6,229,247
proper way to use lock file(s) as locks between multiple processes
I have a situation where 2 different processes(mine C++, other done by other people in JAVA) are a writer and a reader from some shared data file. So I was trying to avoid race condition by writing a class like this(EDIT:this code is broken, it was just an example) class ReadStatus { bool canRead; public: ReadS...
On Unices the traditional way of doing pure filesystem based locking is to use dedicated lockfiles with mkdir() and rmdir(), which can be created and removed atomically via single system calls. You avoid races by never explicitly testing for the existence of the lock --- instead you always try to take the lock. So: loc...
6,228,924
6,229,011
using openmp in windows R, does rtools support openmp?
I got lots of error messages when trying to use openmp in a c++ code for building my R package on windows 7: c:/rtools/mingw/bin/../lib/gcc/mingw32/4.5.0/libgomp.a(parallel.o):(.text+0x19): undefined reference to `_imp__pthread_getspecific' c:/rtools/mingw/bin/../lib/gcc/mingw32/4.5.0/libgomp.a(parallel.o):(.text+...
No, per discussions on the R-devel mailing list. It also came up on the Rcpp-devel list. R itself does not use OpenMP on Windows, so there is not support in Rtools. On other OSs R does of course have OpenMP support.
6,228,935
6,228,994
Processing conditional statements
I'm not looking for an implementation, just pseudo-code, or at least an algorithm to handle this effectively. I need to process statements like these: (a) # if(a) (a,b) # if(a || b) (a+b) # if(a && b) (a+b,c) # same as ((a+b),c) or if((a&&b) || c) (a,b+c) # same as (a,(b|c)) or if(a || (b&&c)) So the + operato...
The shunting-yard algorithm is easily implementable in a relatively short amount of code. It can be used to convert an infix expression like those in your examples into postfix expressions, and evaluation of a postfix expression is Easy-with-a-capital-E (you don't strictly need to complete the infix-to-postfix convers...
6,229,013
6,229,102
specializing on a subset of types in a C++ template
I have a question about template specialization in C++, and I am hoping someone here can help. I have a class that has 3 template parameters: template<class A, class B, class C> class myClass { public: void myFunc(); }; What I want to do is write several versions of myFunc that specialize on, say, type C, but are ...
You can write a function template, and an overload, and delegate the work to it: template<class A, class B, class C> class myClass { //resolver doesn't need to define anything in it! template<class> struct resolver {}; //empty, yet powerful! public: void myFunc() { doFun(resolver<C>()); } //this...
6,229,046
6,229,077
How do I properly overload new?
My code is below. However before main() is run something simple such as a static std::string globalvar; will call new. Before MyPool mypool is initialized. MyPool mypool; void* operator new(size_t s) { return mypool.donew(s); } Is there anyway I can force mypool to be initialized first? I have no idea how overloading...
Make mypool a static variable of your operator new function: void* operator new(size_t s) { static MyPool mypool; return mypool.donew(s); } It will be initialized upon first call of the function (i.e. the operator new). EDIT: As the commenters pointed out, declaring the variable as static in the operator new fun...
6,229,098
6,229,170
How to use a structure in multple functions
I am using a structure such as struct IF_ID { int PC; string instruction; }; and then in the int main() { IF_ID stage1; stage1.PC=0; FETCH(stage1); DECODE(&stage1); return 0; } When I passe stage1 in the FETCH(stage1) function it works fine, the thing is that i need t...
You're passing the struct to FETCH() by value. This means it is COPIED to the function. If you want the actual struct to be passed, you need the method to receive its pointer or reference: By reference: void FETCH(IF_ID& ref_stage); pointer to struct: void FETCH(IF_ID* ref_stage); If you use by reference, the inne...
6,229,633
6,229,829
Writing a GUI to display statistics
I'm working with a hardware simulator for a project. It outputs statistics at the end in a very structured but ugly way. It can be tiresome to read so I would like to write a GUI to help me display it better. Would anybody have an idea of what framework and widgets I could use to quickly and painlessly construct someth...
When I'm just trying to display some information, and I don't really need interaction, I sometimes make the program output a simple html page. It's fast and trivial to do things like tables and images (in virtually any format). If you need graphs, there are web-APIs like Google's chart API.
6,229,866
6,229,949
c++ #include style differences
So the other day, I was looking through some old C++ books and noticed a way of creating a C++ class I had never seen before. Everything I have seen up to that point had always used the #include "header.h" and compiled the implementation files separately. What I saw the author of this book do is actually put an inclu...
Doing this will bring the definition of the class in to every translation unit where the header file is included. This is a very unusual paradigm, and could be hazardous to your coding health. In particular, if you have main.cpp and foo.cpp both of which #include "employee.h", then all the methods on employee will be...