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 |
|---|---|---|---|---|
5,670,925 | 5,670,931 | Seemingly unable to work with ints in struct | struct stVitals // Entity vitals
{
int str;
int xp;
int batk;
};
int doAttack(stVitals Aggressor, stVitals Defender) // Calculate attack results
{
doHit(getATK(Aggressor), getDEF(Defender), getDDG(Defender), getLVL(Aggressor), getLVL(Defender));
}
int doHit([...] ... | What's missing here is the code in which you call getATK. Presumably, you're incorrectly passing an int argument rather than an stVitals argument when you call that function.
|
5,671,035 | 5,671,078 | random number generator being called when it shouldn't, i think | #include "std_lib_facilities.h"
#include <GL/glut.h>
static float dx=0.0;
static float dz=10;
static float points[2];
static float cx=0.0;
static float cy=0.0;
static float cz=0.0;
static float spin=0.0;
static float rotation=1.0;
int readObject()
{
ifstream inputFile("spikeBall.ogl");
if(!inputFile)
{... | cz+=0.1;
if(cz=20)
{
[random generator code]
}
Two problems here:
First you're assigning (=) 20 to cz instead of comparing (==) - even worse, this evaluates to true and triggers the code inside the brackets all the time. You should perhaps consider switching the compiler to a more verbose warning mode and/or reading... |
5,671,047 | 5,671,193 | Error while accessing dynamically allocated array between classes | UPDATE: Most of my relevant source code is in this pastebin: http://pastebin.com/nhAx1jfG
Can anyone make sense of this error? I'm trying to access a 2d "Tile" array I declare in a different class in the same namespace, it's public, and I do declare an object in the main "rouge.cpp" class.
g++ -Wall -Werror -lncurses ... | You're using a pointer to point to an array that was dynamically allocated as a multidimensional array. After the address of this multidimensional array is stored in World::tiles, the compiler "forgets" that the array was multidimensional. Thus, you can no longer use the double brackets notation (tiles[x][y]) to access... |
5,671,087 | 5,671,120 | boost::thread function execution | How do I use a boost::thread to execute a function with each thread executing in its own memory space. So that when I allocate a new variable with in the function it only lives as an instance in the executing thread.
Just to clarify I want to spawn threads that execute the same method using boost::thread but I do not w... | Anything you allocate inside the thread function is already local to that function, as long as they're not declared as static. Just write your code as normal (avoiding static local variables) and you'll be fine.
|
5,671,241 | 5,671,308 | How does weak_ptr work? | I understand how to use weak_ptr and shared_ptr. I understand how shared_ptr works, by counting the number of references in its object. How does weak_ptr work? I tried reading through the boost source code, and I'm not familiar enough with boost to understand all the things it uses.
Thanks.
| shared_ptr uses an extra "counter" object (aka. "shared count" or "control block") to store the reference count.
(BTW: that "counter" object also stores the deleter.)
Every shared_ptr and weak_ptr contains a pointer to the actual pointee, and a second pointer to the "counter" object.
To implement weak_ptr, the "counter... |
5,671,324 | 5,671,353 | finding the common elements of vectors which are inside another map | dear all,
i have a map, defined as map<int, vector<int> > my_map. So, for example it looks like as follows,
my_map=
0 1 2 6 5 4
1 0 2 3 4 5
2 0 1 4
3 1
4 1 2 0 7 5 6
5 1 0 6 4
6 0 5 4
7 4
vector<int> element_common(map<int, vector<int> > &my_map, int s1, int s2){
vector<int> common2;
vector<int> first_vector... | You got the test exactly backwards:
if(any_in_2nd_vector_iterator==2nd_vector_end){
is true when the element ISN'T FOUND in the second vector. Try !=.
Then, you can avoid needless copying of vectors by using a reference:
const vector<int>& first_vector=my_map[s1];
and if your vectors get much larger, it may be faste... |
5,671,457 | 5,672,329 | Hard sorting problem - what type of algorithm should I be using? | The problem:
N nodes are related to each other by a 'closeness' factor ranging from 0 to 1, where a factor of 1 means that the two nodes have nothing in common and 0 means the two nodes are exactly alike.
If two nodes are both close to another node (i.e. they have a factor close to 0) then this doesn't mean that they w... | Because your 'closeness' metric obeys the triangle inequality, you should be able to use a variant of BK-Trees to organize your elements. Adapting them to real numbers should simply be a matter of choosing an interval to quantize your number on, and otherwise using the standard Bk-Tree procedure. Some experimentation m... |
5,671,479 | 5,674,500 | Variadic Template Template | I am trying to create a base class that is a wrapper around std::array that overloads a bunch of common arithmetic operators. The end result will be sort of like std::valarray, but with static size. I'm doing this because I am creating a whole host of child classes for my library that end up replicating this functiona... | What if, in place of the size_t, you used an std::integral_constant? You would embed the numerical value of the size of your array in it, and you could use it as a type.
EDIT
In order to reduce the verbosity, you could define your own integral constant class, something like:
template <std::size_t N>
struct size_ : std:... |
5,671,726 | 5,672,714 | boost multiple calls to class method | In boost::thread is it possible to call a class method with out making the class callable and implementing the void operator()() as in just call the class method
for(int i=0;i<5;i++)
boost::thread worker(myclass.myfunc,i,param2);
I get an error <unresolved overloaded function type>
Actually I would prefer to kn... | boost::thread doesn't need anything special, it will work exactly as you want (minus syntax errors):
for (int i = 0; i != 5; ++i)
boost::thread worker(&myclass::myfunc, myclassPointer, i, param2);
From the boost.thread docs:
template <class F,class A1,class A2,...>
thread(F f,A1 a1,A2 a2,...);
Effects: As if thre... |
5,671,730 | 5,671,932 | Behavior of global variable varies in different functions | I am writing a program which renames AVI file (add extension - needed for some reason) and then gets frame from it and stores it in BMP file.
Here are the important parts of code:
#include "stdafx.h"
#include "ImageProcessor2.h"
#include <windows.h>
#include <Commdlg.h>
#include <Commctrl.h>
#include <stdio.h>
#include... | Because selectedAVI is a pointer and has no storage of its own, and the thing it's pointing to (which does have the storage) is part of a local variable (the OPENFILENAME structure in OpenDialog), which has gone out of scope and been overwritten by the time you get to IDC_EDIT2.
To fix this, change it to an array of le... |
5,671,733 | 5,674,132 | C++ map iteration with deletion | I couldn't find an instance of how to do this, so I was hoping someone could help me out. I have a map defined in a class as follows:
std::map<std::string, TranslationFinished> translationEvents;
TranslationFinished is a boost::function. I have a method as part of my class that iterates through this map, calling each ... | After reading all other answers, I am at an advantage here... But here it goes.
However it's possible for a function called by it->second(this); to remove an element from the translationEvents map (usually itself)
If this is true, that is, a callback can remove any element from the container, you cannot possibly res... |
5,671,764 | 5,671,928 | how to recognize simple handwriting shapes? | I have a set of simple shapes (see following figure), and I want to recognize handwriting shape and figure out which shape it probably is in the set.
Is there any simple algorithm to do that? Or any open source lib?
BTW, my task is simple, so I don't use too complicated lib like OpenCV.
Thanks, in advance!!
| This is essentially line detection
It works only for shapes with straight lines, and is by no means simple.
Assume that your figure has k line segments in it, use the k-means algorithm to aggregate the points into lines.
First divide randomly the points into clusters.
For each of these clusters compute the line that th... |
5,671,777 | 5,671,879 | Appropriate use of shared_ptr? | With no experience with shared_ptr<> I am wondering whether the following is an appropriate use case and also whether it is a good idea to return shared_ptr<> to the user.
I have a graph like structure with multiple connections between the nodes. During traversal of the graph each node is assigned a value (computed fr... | shared_ptr is primarily useful for times when an object doesn't have a clear-cut owner (or maybe needs to outlive its owner), so there's no obvious place to destroy it. The shared_ptr essentially becomes the owner, and the object is destroyed when the last shared_ptr to it goes out of scope.
When you've got a clear own... |
5,671,861 | 5,671,883 | iterators for vector of pointers | I read another post that answered a question regarding iterators for vectors of pointers. I tried to use the same concept in my code but I receive some compilation errors. The code sample I was basing my code on is:
vector<c*> cvect;
cvect.push_back(new sc);
vector<c*>::iterator citer;
for(citer=cvect.begin(); citer !=... | You forgot to dereference the iterators. Try this instead:
vecOne.push_back(new MyStuff( **vec1_itr ));
Edit 0:
Yes, should be double dereference (fixed above). And it should be the const_terator instead since you are dealing with const containing object:
vector<MyStuff*>::const_iterator vec1_itr;
|
5,672,003 | 5,672,918 | opengl texture mapping | i have got a single texture working in my opengl project
the problem is it only lets me use one texture
i was wondering how i can change this so i can use multiple textures
maybe an array?
when i load in more than one bitmap image i can't seem to get it to work
this is the code i am using to create the texture
glEnable... | Besides calling glGenTextures n times, you can do this :
const GLsizei n = 5;
GLuint textureIDs = new GLuint[ n ];
glGenTextures( n, textureIDs );
|
5,672,086 | 5,672,137 | C++ classes - how to pass vector of custom type to function | I am attempting to develop a class with a function that can take a vector of items as it's argument.
I can get it to work fine if I use a vector of type int, or other primitive, but I can't get it to work with a vector of objects.
eg:
In my header file:
int influenceParticles(vector<Particle> particles);
This is what ... | Maybe you have cyclic includes, ie. if the ParticleAttractor.h also includes the Particle.h. To solve this, you should make a forward declaration of Particle in ParticleAttractor.h:
class Particle;
You should also consider passing the vector by reference to avoid copying:
int influenceParticles(vector<Particle>& parti... |
5,672,104 | 5,672,686 | Strange linking behavior, latest g++ | I have been running into strange linking behavior with g++, however, I'm just a student, and I was wondering if this was normal.
I am trying to link assembly code (machine: fedora 14 gnome 32bits x86 i686 intel i7) with c++ code and to have the assembly code call a method from a fonction instanciated in the c++ file. I... |
For inlined functions the compiler
will only output code where the function is used.
Functions defined
inside the class definition are
inline (usually).
The function isn't
used.
Therefore: no function in the
binary.
|
5,672,109 | 5,682,348 | zi_lib concurrency example | Can anyone explain to me how to use zi_lib concurrency with classes?
| You can look at the examples in
https://github.com/zlateski/zi_lib/tree/master/zi/concurrency/test
note that you don't have to use zi::run_fn, it's a backwards compatibility thing, you can say:
zi::thread t( zi::bind( function_pointer, arg1, arg2, ... ) );
t.start();
t.join();
same thing with the zi::task_manager::simp... |
5,672,484 | 5,672,554 | Free profiling in C++? |
Possible Duplicate:
What's your favorite profiling tool (for C++)
In Java and they have a nice & free profiler that comes with the sdk called jvisualvm. Is there anything like that for C++? I'm on Windows and have Visual Studio 2010. I'm a student/hobbyist, so something free would be nice.
jvisualvm lets you look... |
AMD Code Analyst
Sleepy
A little googling gives a impressive list of freebies(disclaimer: I haven't used these):
Shiny
Google Test
Windows Performance Analysis
Hth.
|
5,672,530 | 6,649,844 | API in Java or C++ to read MRZ Travel Document(passport) code | I am looking around for an API in java or c++ to read the MRZ and decode the MRZ code in travel documents(passports).
More information on MRZ is at http://www.highprogrammer.com/alan/numbers/mrp.html. Has any one done this before with an API?
| Please see the mrz-java Google code project. It is quite new though - it only supports four MRZ formats for now.
|
5,672,882 | 5,672,913 | Can any one tell what is the 4th line in this function doing! | size_t hash(const std::string data) {
size_t h(0);
for (int i=0; i<data.length(); i++){
h = (h << (31-i) ^ (h >> i) ^ data[i]);
}
h = h%hashsize;
return h;
}
| It's a hash function for std::string, ostensibly suitable for TR1 and C++11's std::unordered_map<>, std::unordered_set<>, etc. I.e., it attempts to create an as-unique-as-possible size_t value for the given std::string for use in hash tables.
That being said, it's a poor hash function. Any standard library implementati... |
5,672,960 | 5,673,518 | how can I extract the mantissa of a double | I would like to store in a variable the mantisssa of a double
I have post a code to get the binary representation of a double : click here
What should I change to isolate the mantissa
| In <math.h>
double frexp (double value, int *exp)
decompose VALUE in exponent and mantissa.
double ldexp (double value, int exp)
does the reverse.
To get an integer value, you have to multiply the result of frexp by FLT_RADIX exponent DBL_MANT_DIG (those are availble in <float.h>. To store that in an integer variabl... |
5,673,164 | 5,673,177 | instantiating struct with boost multi_array | I have a struct that extends an abstract class and then I add a boost multi_array inside as variable, I get the following error.
struct myrunnablestruct : zi::runnable{
boost::multi_array<int,3> myArray;
myrunnablestruct(unsigned int dimensions )
: myArray( boost::extents[ dimensions ][ dimensions ][ dim... | The error is unreleated to boost::multi_array<>.
zi::runnable has pure virtual member function(s), which your struct does not implement, and it is impossible to instantiate a type with pure virtual member functions. Presumably the error message tells you exactly which member functions you need to implement, but you did... |
5,673,194 | 5,673,396 | Conversion of UTF-8 char * to CString | How do I convert a string in UTF-8 char* to CString?
| bool Utf8ToCString( CString& cstr, const char* utf8Str )
{
size_t utf8StrLen = strlen(utf8Str);
if( utf8StrLen == 0 )
{
cstr.Empty();
return true;
}
LPTSTR* ptr = cstr.GetBuffer(utf8StrLen+1);
#ifdef UNICODE
// CString is UNICODE string so we decode
int newLen = MultiByteT... |
5,673,201 | 5,673,382 | C++/C#/Java video analysis question | Could someone give references / frameworks, which allow to do something like Microsoft Kinect does, but using only one video stream?
I would like to see algorithm abstracts and papers if there are some (I hope there are).
If somebody had practical experience of using them, please share it :)
| Take a look on this project, it implements simple recognition algorithm of the hands gesture using one video stream.
|
5,673,242 | 5,673,432 | GetWindowPlacement gives the incorrect window position | How to find out whether a window was resized using Aero Snap feature? GetWindowPlacement function gives the latest "restored" window size. I use it as follows:
WINDOWPLACEMENT wp = {};
wp.length = sizeof(WINDOWPLACEMENT);
::GetWindowPlacement( hWnd, &wp );
For instance, it gives wp.rcNormalPosition = {top=208 bottom=5... | AeroSnap is just another type of resize sent to your app by the window manager. As such you don't get to know that it was snap rather than any other type of resize.
The best you can hope for is to detect that opposite edges have been moved in the course of a size event. You'd need to check that height or width changed ... |
5,673,448 | 5,674,201 | can the CImg library draw thick lines | I have been using the CImg library, and have been pleased with how easy it is to integrate and use. However, I now want to draw thick lines (i.e., more than one pixel thick). It is not clear from the API documentation of the draw_line function (here) how this can be done. A second version of the function (just below th... | Apparently, it is not possible 'out-of-the-box', but creating your own routine that calls multiple times the 'draw_line()' routine of CImg, with one or two pixels shifts should give you the result you want, without much work.
|
5,673,694 | 5,673,727 | How to align pointers when dealing with multiple-inheritance? | Say we have a concrete class A, and an abstract class B.
Consider a concrete C, that inherits from both A and B, and implements B:
class C : public A, public B
{
/* implementation of B and specific stuff that belongs to C */
};
Now I define a function which signature is void foo(B* b);
This is my code, I can ass... | void foo(B* b)
{
//A* a = reinterpret_cast<A*>(reinterpret_cast<char*>(b) - sizeof(A)); // undefined behaviour!!!!
A* a = dynamic_cast<A*>(b);
if (a)
{
// now I can use all the stuff from A
}
else
{
// that was something else, not descended from A
}
}
Forgot to say: ... |
5,673,837 | 5,674,389 | How to cross compile from windows g++ cygwin to get linux executable file | I have an updated cygwin-full install ,mingw ,codeblocks on a windows system.
i have a c++ program which performs xml generation based on input.
I understand to build an executable file for unix we use makefiles. makefiles being typical project files .
Hence i used the plugin cbp2make.exe to get the makefile for the ... | You are wrong assuming that you need makefile. Any builder will do. The important point is, that you have to tell the builder to:
Call g++linux instead of g++ (or mingw-g++ or whatever it's calling)
Set proper path to look for includes and libraries. The compiler will know where to look up system libraries that came w... |
5,673,932 | 5,673,979 | where to find a good instruction how to parse a c++ header file? | where to find a good instruction how to parse a c++ header file?
edit: i want to parse it with haskell, there is a parsec libraray but i need some examples.
| Use an existing C++ parser (you're unlikely to ever succeed in writing one yourself that cover all the corner cases of the grammar, it's horrendous).
I can only recommend the Clang libraries.
|
5,674,291 | 5,677,297 | Visual Studio Function Debugging | I am working on VS 2008. I wish to get the following information for all my methods:
1) Time at call entry
2) Time at call exit and the return value.
GDB allows me to set a break point at each function entry and exit and run a script at the breakpoint and then continue debugging. I am tired of looking for solutions to ... | using windbg, you can also set at each function entry and run a script.
For instance the following command will add a breakpoint on all functions of your module, display the name of the function, the current time, run until the function exit, display the time and continue.
bm yourmodule!* "kcL1;.echotime;gu;.echotime;g... |
5,674,394 | 5,675,042 | Is it possible to create a struct type based on file contents? | Is it possible in C++ to create a struct type based on file contents?
STRUCT_NAME
int var1;
int var2;
string v3;
STRUCT NAME *pointer;
The first line would be the name of the struct, the other lines would be the variables
| Whatever @lindydancer @iammilind @james are saying is correct.. You cannot do it in single go. You may get work around (Though thats not professinal way of doing) like this :
1. First read the file in which your structure is define and create new file(Cpp and h files).
2. Now compile new file and provide new exe file ... |
5,674,459 | 5,674,785 | HLSL: Returning an array of float4? | I have the following function in HLSL:
float4[] GetAllTiles(float type) {
float4 tiles[128];
int i=0;
[unroll(32768)] for(int x=0;x<MapWidth;x++) {
[unroll(32768)] for(int y=0;y<MapHeight;y++) {
float2 coordinate = float2(x,y);
float4 entry = tex2D(MapLayoutSampler, coordin... | In short:
You can't return an array of floats defined in the function in HLSL.
HLSL code (on the GPU) is not like C code on the CPU. It is executed concurrently on many GPU cores.
HLSL code gets executed at every vertex (in the vertex shader) or every at pixel (in the pixel shader). So for every vertex you give the GPU... |
5,674,550 | 5,674,644 | Function registered with atexit() not getting called | Is it guaranteed that a function registered with atexit will ALWAYS be called upon normal program termination? (I encounterd a scenario in FreeBSD where a function that I register with atexit never gets called, even when the program terminates normally).
| No. First, the function will not be called if atexit returns a non-0 value. Secondly, it won't be called if a function registered before it doesn't return normally.
|
5,674,633 | 5,675,050 | Which format to create logs in profilers? | In the profiler I am writing, which is in fact a JVMTI agent for Java programs, I need a format to log the events collected. Further these logs have to be send to a socket and read by a GUI somewhere else. So I need a working serialization between two languages.
I already implemented my own protocol in XML and it worke... | I have a design I am working on for all log file in my remit. I record data in JSON but the JSON data is nested in a very simple xml format.
eg
<entry ts="2011-02-23T17:18:19.202" level="trc_1" typ="trace">New Message Received</entry>
<entry ts="2011-02-23T17:18:19.202" level="trace" typ="msg"><data>{"Name":"AgtConf","... |
5,674,788 | 5,674,987 | Why is the Ribbon UI disappearing when I resize my app window horizontally? | I wanted to adopt the Ribbon UI for my new project, I know it might be focusing more on the WoW factor than the true use of a Ribbon which is to replace the toolbar clutter. However when I started playing around with resizing the window, checking out some of the features related to automated scaling. After shrinking th... | Paint and the other built-in Windows applications use the scenic Ribbon API that Microsoft is now including in the OS for all developers to use. Presumably, this is the same one you're using for your project. Microsoft Office uses proprietary ribbon controls, invented by the Office team in-house. That explains the diff... |
5,674,825 | 5,675,267 | global pointers to objects will break program by access violation when accessing object attributes/methods through them | This is code for an OpenGL application i'm making. I have the following code that produces an access violation (notice: i've only posted the code relevant to the problem):
// file: myHeader.h
class MyClass{
int classAttribute;
public:
void myClassFunction();
bool CreateGLWindow();
friend LRESULT CALL... | The constructor seems to create the window and associate the WndProc before p is assigned (the next line of code)
MyClass obj;
p = &obj;
You could set MyClass * p = NULL; and then wrap the use of p in
LRESULT CALLBACK WndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
if(p)
{
if (p->classAttribut... |
5,674,827 | 5,675,089 | How can you Call a method from a diffrent Project, both in C++? | I'm normally working in c# so certain things in c++ keep confusing me alot (they seem so diffrent yet the names almost the same)
I created a Console project in which i want to run a diffrent project for testing purposes. i added the project as a reference to the console app, and then got kinda stuck.
there is no names... | Yeah, C++ doesn't have the notion of assemblies that exists in C# and .NET. It makes tasks like this slightly more difficult, a virtue of the fact that C++ compiles directly to native code.
Instead, you'll generally #include the necessary header files (*.h) at the top of your code file, and instruct the linker to link ... |
5,674,983 | 5,675,096 | Copy Elision and rvalue reference | in the code below, what it is used to avoid copy, elision or rvalue reference and move constructor ?
std::string get(){return "...";}
void foo(std::string var){}
foo( get() ); //<--- here
| std::string get(){
// this is similar to return std::string("..."), which is
// copied/moved into the return value object.
return "...";
}
RVO allows it to construct the temporary string object directly into the return value object of get().
foo( get() );
RVO allows it to directly construct the temporary ... |
5,675,043 | 5,675,075 | How to inherit a templatised Base class? |
I am new to STL. I have written a Template Base class as follows
template <class T>
class Base
{
public:
//Constructor and Destructor ..
Base();
virtual ~Base();
virtual foo() = 0;
};
Now , I want to design my framework such that my inherited classes will be publicly derived ... | The later,
class Derived : public Base
will not work, because Base is not a class, it's a class template. Than it depends on whether Derived should be a template or whether it should inherit particular instance of Base:
Template:
template<typename T>
class Derived : public Base<T>
Non-template:
class Derived : publi... |
5,675,208 | 5,675,215 | Expected initializer before function name | #include <iostream>
#include <string>
using namespace std;
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
}
sotrudnik create(string n,string spec,string raz,int sal) {
sotrudnik temp;
temp.name=n;
temp.speciality=spec;
temp.razread=raz;
temp.zarpl... | You are missing a semicolon at the end of your 'struct' definition.
Also,
*sotrudnik
needs to be
sotrudnik*
|
5,675,358 | 5,675,952 | How to send ostream via boost sockets in C++? | I am facing some issues with my inter-process communication using protobuf. Protobuf allows a set of serialization formats:
SerializeToArray(void * data, int size) : bool
SerializeToCodedStream(google::protobuf::io::CodeOutputStream * output) : bool
SerializeToFileDescriptor(int file_descriptor) : bool
SerializeToOstre... | Boost's asio library integrates with std iostream on the level of streambuffers
So write a request
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET " << argv[2] << " HTTP/1.0\r\n";
request_stream << "Host: " << argv[1] << "\r\n";
request_stream << "Accept: */*\r\n";
request_... |
5,675,767 | 5,677,138 | pdf to txt convertion in qt or c++ | Hi
How can I convert pdf to txt with qt ?
if there isn't way to do this , Is there any library for c++ that convert pdf files to txt files ?
thanks.
My os is windows7 and my ide is visual studio 2008
| Foxit sells their PDF code as a library. I use it, and it's great.
http://www.foxitsoftware.com/pdf/sdk/dll/
You may know them for their very popular free Acrobat Reader alternative.
|
5,675,768 | 5,679,695 | Flushing all asynchronous handlers in boost::asio | I'm running some tests that need asynchronous communication, and the underlying framework is Asio. Sometimes, a handler is kept in the processing loop even if the test has been tore down, for good reasons. But then, it is called after the targets are deleted.
The Test class:
virtual void SetUp()
{
_client = new Cli... | It appears to me you need to re-think your design slightly. io_service::stop is indeed asynchronous, as you've noticed. It causes any invocations of io_service::run() to return as soon as possible. Any outstanding handlers are not invoked with boost::asio::error::operation_aborted until the ~io_service() destructor run... |
5,675,884 | 5,676,018 | Easy way to cross-compile a Qt application using Qt Creator? | I'm very new to this C++ and Qt Creator thing, I'm using Qt Creator in Mac OS X.
Is there an easy way to compile for Windows and Linux platform also?
The current way I'm doing is copying the source file to a Windows machine (with Qt) and compile it, which takes a lot of time.
Is there a command or something that can ge... | It is far from trivial, and Trolltech didn't like the idea (by making it harder than it should be).
There is Cross compiling Qt/Win Apps on Linux on the Internet which will help (only directories might be different for Mac, commands should be the same).
After you have cross-compiled, you'll need to create a shortcut to... |
5,675,922 | 5,675,945 | When convering a transparent png image to bitmap its not retaining the transparency? | I was hoping some one could help me with this problem. I am currently using ImageMagick.NET wrapper to convert transparent png images to bitmap (we are doing this as we need the added image processing functionality that comes with c++ imageMagick). Now everything works great except when I use an image where there is tr... | Bitmaps do not support transparency. Generally you do it the other way around. You have a BMP select a color that means transparent and when converting to a format that supports transparency that color is made transparent.
|
5,676,000 | 5,676,110 | Read number of lines, words, characters from a file | I can read the number of lines easy, using:
ifstream in(file);
string content;
while(getline(in, content))
{
// do stuff
}
Or I can read the number of words and characters easy using something like:
ifstream in(file)
string content;
int numOfCharacters = 0;
int numOfWords = 0;
while(in >> content)
{
++numOfWords... | Read the line and for each line count the words. See stringstream for the second part.
(I'm not giving more information, that looks too much like an homework).
|
5,676,016 | 5,676,145 | C tips and tricks explanation | Can you explain me which is the mechanism behind the next code samples (I think I know but I need second opinion):
1)--------------------------
using namespace std;
int * f(int x) {
return &x;
}
int * g(int x, int y) {
return &y;
}
int * h(int x, int y, int z) {
return &z;
}
int main() {
cout << *f(42) << e... | I would expect those programs to crash or do other weird things when you run them.
Example 1: The functions f, g and h are returning the memory addresses of their arguments. Note that those arguments are stored on the stack, and when the functions return, the stack is unwound and the addresses will not be valid anymore... |
5,676,026 | 5,676,072 | Detecting if a bit is set (at compile time) | How to detect if bit at position n is set in constant variable?
| template<std::uint64_t N, std::uint8_t Bit>
struct is_bit_set
{
static bool const value = !!(N & 1u << Bit);
};
!! is used to succinctly coerce the value into a bool and avoid data truncation compiler warnings.
|
5,676,133 | 5,676,213 | Boost shared_ptr: using unique() to implement copy on write | Could someone explain what boost shared_ptr manual means by this:
If you are using unique() to implement
copy on write, do not rely on a
specific value when the stored pointer
is zero.
Thanks.
| Copy-on-write is a storage scheme where copies of an object with duplicate values are represented by a single object. Only when you try to change one is it copied to a new, unique object.
Boost supports this by telling you whether a given shared_ptr is supporting more than one reference. If it is, then writing to the o... |
5,676,209 | 5,676,286 | std::shared_ptr and double callback | I have some logic where I am using std::shared_ptrs to objects in an inheritance hierarchy. At one point I need to handle these objects depending on their real type, so I am using a double dispatch (i.e. I call a method on the base class, which then in turn calls a method on another object with the real type, see e.g. ... | Derive your class from std::enable_shared_from_this - then you can extract a shared_ptr from your object at any time!
It's not a whole lot different from what you're doing now with the weak_ptr, but it's the clean and accepted idiom to do it.
|
5,676,241 | 42,985,979 | Tell gdb to skip standard files | I'm debugging C++ code with GDB and when it enters a constructor of some object containing standard library objects, it shows me the constructor of these objects (like std::map) and everything that's underneath.
I know about the next operator, but I'd prefer to basically black list any standard library code, which is n... | gdb 7.12 supports file globbing to specify the files to skip in the debugger. The documentation for the same is as below:
https://sourceware.org/gdb/onlinedocs/gdb/Skipping-Over-Functions-and-Files.html
To skip stepping into all library headers in the directory /usr/include/c++/5/bits, add the below lines to ~/.gdbinit... |
5,676,346 | 5,676,997 | How to separate the result of macro expansion into different arguments? | I'm writing some Boost.Preprocessor metaprogram, and I have the following problem. Consider the following macros (this is a simplification to illustrate the problem):
#define ITERATION_IMPL(p1, p2, p3, p4) ((p1),(p2),(p3),(p4))
#define ITERATION(args) ITERATION_IMPL(hello, args(), world)
#define ARGS() a, b
ITERATION(... | I think if ITERATION(ARGS) is encountered, it takes ITERATION_IMPL(hello, args(), world), replaces args with ARGS, and then rescans. ITERATION_IMPL(hello, ARGS(), world) is an invocation of ITERATION_IMPL. Therefor, it takes ((p1),(p2),(p3),(p4)), and replaces p2 by ARGS() (along with the other parameters). It then res... |
5,676,413 | 5,676,749 | Pure Virtual Methods with Different Datatypes | I'm making a base class for my container classes to derive from so I can maintain a consistent interface. It currently looks something like this:
template <typename Datatype>
class BaseClass
{
public:
virtual Datatype Foo() = 0;
virtual Datatype Bar() = 0;
};
template <typename Datatype>
class DerivedClas... | It's NOT possible to return different data types. The only way would have been to make the methods template and that is restricted because virtual methods can not be templates.
|
5,676,502 | 5,680,568 | c++ system call security issue | I develop a c++ CGI app that is used under Windows and Linux.
It has to start another app. Currently I am using a system call:
system("anotherApp.exe -arguments");
For that call I need execute rights for cmd.exe on windows cause the system call starts a shell. This is a security concern since my app is a CGI app and u... | System() launches a Console Window and runs the program in that console window.
popen() runs the program without a console Window, and redirects console output to a pipe.
CreateProcess() just launches the program. You pass a flags argument telling it what to do with consoles. It also allows the program to run with di... |
5,676,746 | 5,857,710 | Developing Musical App for Windows | I have musical app developed for OS X, which has following features,
Play multiple tracks at a time (long audio files and short sounds)
rewind, forward, pause, stop functionality
the app also displays the waveform of the song
Create playlist
I used Apple's Core Audio framework for music playback.
Now I have to develo... | For the IDE I'd suggest CodeBlocks: http://www.codeblocks.org/. Visual C++ (as suggested by D.A. White) you will have to pay for as soon as you sell any of the stuff you programmed with it, if I am not mistaken. I would also prefer OpenAL ( http://www.openal.org) to DirectSound, because OpenAL should also work on the M... |
5,676,776 | 5,677,689 | How to represent basic Mixin behavior in C++ | Consider an existing C++ class hierarchy: one root class, many children classes forming a direct acyclic graph.
I would like to add a method to the root class, and possibly override it in some children. But the problem is that it is forbidden for me to modify these existing classes (3rd party library, project policy, ... | If you cannot alter the original hierarchy, then template meta-programming is unlikely to help. Remember it's based on compile-time information.
Altering the vtable seems like an extremely bad idea, it's obviously non-portable and presume that you somewhat know its physical layout... even if you get it right it will be... |
5,676,926 | 7,623,543 | Is there a PetriNet tool with an IPC interface? | I'm looking for a quality tool to draw PetriNets with that has an interface to connect to my own application. I have a PetriNet abstraction layer, and instantiated a fairly large Net. Now I want to visualize it to ease up the debugging of my software. IPC can be through named pipes, sockets,... I can attach any of that... | I'll take it as a no.
|
5,677,002 | 5,677,083 | How to find the return type of a function? | So __FUNCTION__ tells us the name of the current function. Is there a similar macro for return type of the function?
| Since you already use a Visual-C++ specific __FUNCTION__ macro you could look into __FUNCSIG__ macro - it expands into the full signature which you could then parse and extract the return type. There's no macro that would do that on itself in Visual C++.
|
5,677,115 | 5,677,208 | One Debug-Print function to rule them all | I'm in the situation that i have several different structs around in my code, that i want to print to the console.
Three examples (of a few hundred):
typedef struct ReqCntrlT /* Request control record */
{
int connectionID;
int dbApplID;
char appDescr[MAX_APPDSCR];
int ... | Yes there most certainly is a more elegant way of doing this (... else if (typeid(T) == ...? Yuck!). You could write some operator <<()s for your structs. This makes your debugPrintMe() function nice and generic and also allows you to stream your structs to cout, cerr, a logger, an ostringstream, ...
Here's an example ... |
5,677,160 | 5,679,405 | How compilers treat SSE (or any) intrinsic functions? | A while ago I read somewhere that SSE intrinsic functions compile into efficient machine code because compilers treat them differently from ordinary functions. I am wandering how actually compilers do it and what C programmers can do to facilitate the process. Are there any guidelines on how to use intrinsic functions ... | The intrinsics compile down to the instructions the represent, whether this is efficient or not depends on how they are used.
also, each compiler treats intrinsics a little differently (aka its implementation specific), but GCC is open source, so you can see how they treat the SSE ones, Open Watcom*, LCC, PCC and TCC* ... |
5,677,187 | 5,677,245 | Converting LPTHREAD_START_ROUTINE to int | I'm working with a C++ code base which contains some lines like the following:
CreateThread(NULL, 0, MyThreadMethod, NULL, 0, NULL);
I would like to write the value of MyThreadMethod to debug output. (I suppose it's a hexadecimal address).
MyThreadMethod has the type LPTHREAD_START_ROUTINE. I already have a method ca... | std::basic_ostringstream<TCHAR> ss;
ss << static_cast<void*>(&MyThreadMethod);
::OutputDebugString(ss.str().c_str());
Converting to int is possible on 32-bit platforms, but not 64-bit platforms, so I'd stick with creating a string instead.
|
5,677,221 | 5,677,304 | BSF Opcode is not working | I am using Visual Studio 2010 professional, and I just checked in debug mode that BSF is not working I tried a lot of combinations, none of them worked!
__asm
{
mov ebx, 0ffffffh;
bsf ecx, ebx;
};
the code above at least give me some results but I got 0 on ecx register (I'm using 64-bit win7 and application... | You're getting ecx set to 0 because the least significant (leastmost?) 1-bit in the value 0xffffff is bit 0. The binary number for that is 0000 .... 1111 1111 1111 1111 1111 1111.
In other words, the result you're seeing is correct.
If you were to try it on 0xfc for example (binary 1111 1100), you should get 2. This is... |
5,677,226 | 5,677,343 | Are functions in C/C++ headers a no-go? | I'm working on a very tiny piece of C/C++ source code. The program reads input values from stdin, processes them with an algorithm and writes the results to stdout.
I would just implement all that in a single file, but I also want test cases for the algorithm (not the input/output reading), so I have the following file... | The vast majority of the boost libraries are header-only, so I'd say: Yes, this is an established and accepted practice. Just don't forget to inline.
|
5,677,250 | 5,677,404 | What does SSE instructions optimize in practice, and how does the compiler enables and use them? | SSE and/or 3D now! have vector instructions, but what do they optimize in practice ? Are 8 bits characters treated 4 by 4 instead of 1 by 1 for example ? Are there optimisation for some arithmetical operations ? Does the word size have any effect (16 bits, 32 bits, 64 bits) ?
Does all compilers use them when they are a... | Background: SSE has both vector and scalar instructions. 3DNow! is dead.
It is uncommon for any compiler to extract a meaningful benefit from vectorization without the programmer's help. With programming effort and experimentation, one can often approach the speed of pure assembly, without actually mentioning any speci... |
5,677,305 | 5,677,952 | Storing each element of a container class as an object | Recently, I have seen some Matrix and 1D array classes implemented in C++ where each individual element is wrapped as a class (e.g. Element class). Normally, we like to have containers like Matrix to contain actual elements (e.g. int) consecutive in a memory. Using a custom class for individual elements can give you so... | One drawback is a memory cost for each Element, which could be a performance concern in large collections. It will cost you at least a byte, probably more for the padding. The "sizeof" operator should tell you the cost.
|
5,677,650 | 5,677,686 | Windows C++ Process vs Thread | In Windows C++, createThread() causes some of the threads to slow down if one thread is doing a very CPU intensive operation. Will createProcess() alleviate this? If so, does createProcess() imply the code must reside in a second executable, or can this all take place inside the same executable?
| The major difference between a process and a thread is that each process has its own memory space, while threads share the memory space of the process that they are running within.
If a thread is truly CPU bound, it will only slow another thread if they are both executing on the same processor core. createProcess will ... |
5,677,652 | 5,677,936 | How can I change the current path using Boost.Filesystem | When starting the program I want to print the current path using current_path() ("C:\workspace\projects"). And then I want to be able to change the path to, lets say "c:\program files", so when i print again the current_path() I want to be printed "c:\program files". Something like this
int main()
{
cout << current_... | int main()
{
cout << current_path() << '\n'; // c:\workspace\projects
current_path("c:\\program files");
cout << current_path() << '\n'; // c:\program files
}
|
5,677,745 | 5,677,980 | Enforcing Common Method Names | Note: This is a follow-up question to this.
I have a group of template classes that do completely different things in completely different ways using completely different datatypes. They do, however, share common method names. For example, Get(), Set(), Resize(), etc. are valid methods for each of the classes in ques... | The compiler will enforce the correct interface by failing to compile any call to a nonexistent function; perhaps the problem is that the error messages are too cryptic?
You could define a base class which declares the required interface as non-virtual functions. The base class functions have no definitions (except whe... |
5,678,173 | 5,678,261 | How to detect C++ compiler with macro in Xcode? | I'm mixing Objective-C (*.m) and Objective-C++ (*.mm) source files in an iOS project.
When I import a C++ header file in a *.m file how can I exclude the C++-specific code in the header file? I want to use a compiler macro, something like:
// SomeClass.h - a file I want to import in C++ and Objectice-C classes
#if CPL... | Objective-C++ is a viral thing that you can't really stop. Your current example gives different parts of your code (C and C++) a different view of the layout of your class, and while I do think it would still work, I'm pretty sure this isn't a very good thing.
When working on ObjC projects interacting with C++, I usual... |
5,678,337 | 5,678,454 | Help with Implementation of binary search for names in an array of structs | I need to use a binary search to find a requested name in an array of structs. I used a binary search example code that searched ints and modified it to search through the array indecies to compare the names in each struct. The program runs but the name is never found so something is definitely going wrong somewhere. N... | In case you try to enter names separated by whitespace you need to use std::getline instead of istream::operator>>.
|
5,678,535 | 5,678,795 | the type of map's key | Just saw a question on STL. The question is
"<"does not need to be overloaded when the key of map belongs to certain types.
What are these types?
Don't quite understand this question! Thanks for answering.
| Assuming the map is instantiated with the default comparator (i.e. as map<Key,Value> with no third argument):
Built-in numeric types
Pointers
Any type for which std::less<Key> has been specialised (as long as the specialisation doesn't require operator<).
Pedantically, any type which already has an overload of operato... |
5,678,551 | 5,706,851 | Performance issues with SQLite3 sqlite3_step function | I have problems with a specific query when using the sqlite3_step function:
SELECT DISTINCT interfaces_int_id,device_dev_id FROM devInterface
INNER JOIN interfaces ON devInterface.interfaces_int_id=interfaces.intf_id
INNER JOIN nlink ON nlink.interfaces_intf_id=interfaces.intf_id
INNER JOIN neighbor ON neighbor.neig... | After upgrading SQLite to the latest version (3.7.6.2), performance is much better.
|
5,678,555 | 5,680,709 | Create PDFs with editable forms in Qt | I'm trying to find out if there's a way to embed an editable text cell in a PDF generated in a Qt application. I'm currently using QPrinter to generate the PDF, but if there's another library that could do this, that would be fine. The environment is limited, though, to C or C++, so libraries like iText are out. In ter... | This may not be terribly helpful, but I'll throw it out there anyway.
wkhtmltopdf is based on QTWebkit.
One of its command line options is to convert HTML fields into PDF fields (off by default).
There's almost no pdf-related code within wkhtmltopdf. Certainly nothing dealing with fields. Something upstream is doing... |
5,678,591 | 5,679,131 | C++ errors LNK2028, LNK2019 and LNK1120. What do they mean and how do I solve them? | I get these three errors and they seem to make little sense to me. If i comment the UserInstruction1(P1, P2, P3); in the console app the errors go away. Both projects are /CLR projects.
error LNK2028: unresolved token (0A000930) "void __cdecl UserInstruction1(double *,wchar_t *,wchar_t *)" (?UserInstruction1@@$$FYAXPAN... | I assume here that all code resides in a single project (Company.Pins.Bank.Win32Console). If so you should move the <\iostream> and <\stdio.h> includes (and any other includes of headers that never/seldom change to stdafx.h:
//stdafx.h
#include <iostream>
#include <stdio.h>
//other headers that are widely used but n... |
5,678,693 | 5,678,763 | A problem with object member | I've got a problem in a C++ program that I can't solve.
I'm trying to pass an object as a construction parameter of an other but i can't figure out how to do this.
My main is creating a Simulation object. In simulation i'm creating two objects a planete and a modelisation. The thing is, i want to pass the planete objec... | You can pass it in by constant reference in the constructor then have a private members that gets initialized like so:
Modelisation(const Planete& planRef) : m_planete(planRef)
Also nifty french variable names ;)
Edit:
There are some interesting design choices here you may want to reconsider global variables in favor o... |
5,678,734 | 5,678,784 | C++: References as return values | I noticed I don't get any compiler errors when I accidentally forget to return from a function that is supposed to return a reference. I wrote some small tests to see what actually happens and I got more confused than anything.
struct Foo
{
int x;
Foo() {
x = 3;
}
};
Foo* foo = new Foo;
Foo& test... | The usual way to lower references in compilers is to pointers. For a reference-returning function, it will mean you get an arbitrary address represented, whatever was in the register or stack slot used for the return value.
Formally in the language, the effects are undefined.
|
5,678,796 | 5,678,867 | Share variables between classes C++? | Yet another question about classes as Im new to OOP. I am creating a game just for fun. Its a top down shooter, space shooter.
I have a few different classes:
Bullet (a list of bullet coordinates),
Player (player sprite, position etc),
Enemy (enemy sprite, position etc),
Collision (taking coordinates Ax, Ay, and Bx, B... | Probably what you want to do is to have a common class "SceneObject" that has a position. Then Player, Enemy and Bullet all inherit from that class.
Your Collision then does not need knowledge about Players, Enemies etc. but only SceneObjects which have a position. You can write a Getter method in your base class that ... |
5,678,932 | 5,678,975 | Fastest way to read numerical values from text file in C++ (double in this case) | Currently, my code is simply this:
void ReadFile(double Cst[][1000], char* FileName, int height)
FILE* ifp;
double value;
int nRead = 0;
int mRead = 0;
//open the file, check if successful
ifp = fopen( FileName, "r" );
if (ifp==NULL){
...
}
for (nRead = 0; nRead < height; nRead++){
for (mRead = 0; mRead < 1... | atof is probably much faster, it doesn't have to process the format string.
If you don't need to support all 1001 recognized input formats (with and without exponents, etc) then a custom function may be faster yet. If atof is still too slow for you, say so and I can clean up the code I use (it's not really suitable fo... |
5,678,949 | 5,679,040 | Getting debug symbol's module name |
Is there a way to get the module's name of a debug symbol obtained by using dbgHelp in C++/Windows?
thanks :)
| Use SymGetModuleBase to get the module base address for a symbol - then GetModuleFileName to find the associated DLL/EXE.
|
5,679,006 | 5,692,727 | Why can't get data from tail -f? | In my program I'm redirecting output of child process to pipe and in parent getting this result and doing something (this is not important). But my program doesn't work when I'm using tail -f test.txt command and doesn't recieve any data during tail is running, and getting this data only after tail is finished (or kill... | This strange problem have been solved very strangely. I have just set buffers of files to 0 this way:
else if (pid != -1)
{
// This is the parent process, Closing write end of pipes and opening fds as FILE
close(outpipe[1]);
*child_stdout_stream=fdopen(outpipe[0], "rt");
setbuf(*child_stdout_stream, NULL);
... |
5,679,029 | 5,679,844 | Read file format using C/C++ in a proper manner | How would you go about reading a simple file format using C or C++?
For example, take the Wavefront .obj file format, sample:
# this is a box
o 1
v -0.5 -0.5 0.5
v -0.5 -0.5 -0.5
v -0.5 0.5 -0.5
v -0.5 0.5 0.5
v 0.5 -0.5 0.5
v 0.5 -0.5 -0.5
v 0.5 0.5 -0.5
v 0.5 0.5 0.5
usemtl Default
f 4 3 2 1
f 2 6 5 1
f 3 7 6 2
f ... | If it were me, I'd leverage as much of the standard library as I could:
struct Command { /* Abstract Base Class */ ... };
struct VCommand : Command { std::vector<double> dims; ... }
struct FCommand : Command { std::vector<int> vertexes; ... }
struct FootCommand : Command { enum {LEFT, RIGHT, IN, OUT} e; ... }
std::vect... |
5,679,073 | 5,679,150 | Overloading operators in derived class | Must I need to redefine all the overloading operators with derived type if I require to use them in derived class?
The following code compiles fine:
class Point {
public:
Point(int X = 0, int Y = 0):x(X), y(Y) {}
virtual ~Point() {}
Point operator +(Point &rhs) {
return Point(x + rhs.x, y + rhs.... | What it means is that if Point had more than one operator+(), and you only redefined one of them, then only that one would be accessible in the derived class; the other overloads would be hidden. If you declare no operator+() in the derived class, then all of the parent ones are available; if you declare any in the der... |
5,679,686 | 5,679,702 | Curly Braces in C and C++ | Why does this Compile:
int main()
{
{}
}
But this does not:
{}
int main()
{
}
| First case, you're defining a block inside a function, which is allowed (it limits visibility).
Second case, you're defining an anonymous block, which is not allowed (it needs to be predeceded by a function definition, otherwise, the compiler will never know when it will have to execute it)
|
5,679,724 | 5,679,806 | using macros to place #ifdef in the code | I am trying to do something like this
#define VB_S #ifdef VERBOSE
#define VB_E #endif
so that in the code instead of writing
#ifdef VERBOSE
cout << "XYZ" << endl;
#endif
I can write
VB_S
cout << "XYZ" << endl;
VB_E
This gives me a compile time error: Stray '#' in the program.
Can anyone put light on wha... | You could do something like this:
#ifdef VERBOSE
#define VB(x) x
#else
#define VB(x) do { } while (false)
#endif
VB(cout << "foo");
|
5,679,764 | 5,680,199 | boost::asio::streambuf empty? | I am using boost::asio::streambuf to write a ostream to my boost socket.
Name name;
name.set_name("platzhirsch");
boost::asio::streambuf b;
std::ostream os(&b);
ZeroCopyOutputStream *raw_output = new OstreamOutputStream(&os);
CodedOutputStream *coded_output = new CodedOutputStream(raw_output);
coded_output->WriteVar... | It was no problem of boost::asio, it was a problem of Google protobuf.
In order to flush the CodedOutputStream, they have to be deleted:
ZeroCopyOutputStream *raw_output = new OstreamOutputStream(&os);
CodedOutputStream *coded_output = new CodedOutputStream(raw_output);
coded_output->WriteVarint32(name.ByteSize());
na... |
5,679,852 | 5,680,040 | C++ Dynamic ND Arrays | I have a problem creating ND arrays dynamically.
So for example:
int **A = 0;
A = new int *[rowsA];
for (int i=0;i<rowsA;i++) {
A[i] = new int[columnsA];
for(int j=0;j<columnsA;j++) {
cout << "Enter " << "(" << i << "," << j << "): ";
cin >> A[i][j];
}
}
And passed to a function li... | If by a ND array you mean an Iliffe vector, you aren't building it correctly. The data has to be allocated consecutively and thus in one allocation as the memory returned by successive calls to new isn't necessarily consecutive. This should do the work:
int **A = new int *[rowsA];
int *data = new int[rowsA*columnsA];... |
5,679,909 | 5,680,049 | Looking for OpenCV tutorial | Does anyone know some good easy to learn openCV c/c++ tutorial you can recommend? I tried Google, but I wasn't very satisfied with results.
| OpenCV has recently provided a list of books they recommend.
Other interesting materials:
There's a great introduction to OpenCV at Gady Agam's introduction to OpenCV.
Noah Kuntz OpenCV tutorials are OK. It covers image manipulation, data types, image processing, camera stuff and several other topics.
There's also the... |
5,680,263 | 5,680,299 | Use Curiously Recurring Template Pattern (CRTP) with additional type parameters | I try to use the Curiously Recurring Template Pattern (CRTP) and provide additional type parameters:
template <typename Subclass, typename Int, typename Float>
class Base {
Int *i;
Float *f;
};
...
class A : public Base<A, double, int> {
};
This is probably a bug, the more appropriate superclass would be Base... | You can use a traits class:
// Must be specialized for any type used as TDerived in Base<TDerived>.
// Each specialization must provide an IntType typedef and a FloatType typedef.
template <typename TDerived>
struct BaseTraits;
template <typename TDerived>
struct Base
{
typename BaseTraits<TDerived>::IntType *i;
... |
5,680,386 | 5,687,402 | Can I tell Boost.MPI which class version to use with Boost.Serialization? | I'm using Boost.MPI to exchange messages between processes. Each message carries one of my classes, serialized using Boost.Serialization. I also use the same serialization code to save that class to a file. What I need to send over MPI is smaller than what I need to save to a file (fewer relevant members). I was thinki... | It is not possible to serialize two different versions of the same type in the same binary module. The reason is that the version used is a compile time constant specified using the BOOST_CLASS_VERSION construct (the version number defaults to zero if not specified).
What you could try is to implement specializations o... |
5,680,530 | 5,680,980 | Using #pragma detect_mismatch to ensure a DLL uses the correct statically linked library | I have a static S.lib that is used by my D.dll.
I'm trying to use #pragma detect_mismatch to make sure that both were compiled under the same release or debug settings.
I've followed Holger Grund's instructions here
http://boost.2283326.n4.nabble.com/Boost-and-Microsoft-s-SECURE-SCL-td3025203.html
dumpbin on S.lib show... | I'm just guessing here - I'll have to experiment with this tonight.
Holger Grund's instructions are designed for objects that depend on the DLL. In your case the DLL depends on the static lib.
So, I'm guessing that you want the _dll_impl_interface_mismatch_check object to be added to the static lib rather than the DLL... |
5,680,635 | 5,680,646 | Vectors inside a struct in C++ | struct node {
char name_;
vector<node*> nbs_;
};
node a, b, c;
a.name_ = 'a';
b.name_ = 'b';
c.name_ = 'c';
a.nbs_.push_back(&b);
a.nbs_.push_back(&c);
for (vector<node*>::iterator i = a.nbs_.begin(); i != a.nbs_.begin(); i++) {
cout << (*i)->name_;
}
Why isn't the above code working. It prints... | i != a.nbs_.begin();
should be
i != a.nbs_.end();
|
5,680,774 | 5,680,951 | Phantom Bugs using Queue (STL Library), Windows/MingW/G++ | I'm having two unexpected problems using Queue from the STL Library:
1) I'm trying to clear a Queue (Queue does not have a function clear),
but the intuitive way is giving me a CORE DUMP:
//The queue is defined Globally but the problem happens even
//if i define it locally and pass it by reference.
queue<pair<int,int> ... | The best way to clear a queue is:
Q = queue< pair< int, int > >(); // assign value of an empty temporary
As for the front bug, I have to agree with Oli and suspect that there is an invalid reference.
|
5,680,877 | 5,680,929 | Rvalue references and SFINAE | I recently started using rvalue references and I've run into a case where I don't understand why they're working the way they are.
I'm trying to determine if a type can have begin and end called on it. The below code gives the expected results if I change foo to take it's parameter by value or const reference, but I... | It is because T gets deduced as an lvalue reference type when foo is called with an lvalue. Try:
has_begin_end<typename remove_reference<T>::type>::value
|
5,681,206 | 5,681,290 | TCP_NODELAY not found on Ubuntu | I am trying to disable the Nagle's Algorithm with my TCP sockets on an Ubuntu Linux box by setting the TCP_NODELAY parameter. For some reason, this constant is not defined in <sys/types.h> or <sys/socket.h>. Has this constant been deprecated and then removed from Linux or am I just missing something?
bool Socket::set... | Did you #include <netinet/tcp.h>?
|
5,681,284 | 5,681,468 | How do I distinguish between left and right keys (CTRL and ALT)? | I started making use of Win32's raw input features to detect all keys on the keyboard. So far, everything is working great! I can distinguish between numbers on the top row and numbers in the keypad on the right. I can even detect between the left and right shift keys. However, the control and alt keys do not return un... | If you want to get low level enough to detect key up events, you should process the WM_KEYDOWN and WM_KEYUP events:
http://msdn.microsoft.com/en-us/library/ms646267%28v=vs.85%29.aspx#_win32_Keystroke_Messages
Pressing a key causes a WM_KEYDOWN or
WM_SYSKEYDOWN message to be placed in
the thread message queue att... |
5,681,489 | 5,681,956 | Boost scoped_ptr / scoped_array with custom deleter | I don't see how to get scoped_ptr or scoped_array to use a custom deleter. Maybe there is another implementation which allows controlled deletion similar to shared_ptr?
Btw, why does shared_ptr allow custom deleter but scoped_ptr doesn't? Just curious.
|
I don't see how to get scoped_ptr or scoped_array to use custom deleter
You can't.
Maybe there is another implementation which allows controlled deletion similar to shared_ptr?
If your compiler supports rvalue references and your Standard Library implementation implements std::unique_ptr, you can use that.
Otherwis... |
5,681,577 | 5,681,603 | What happens when you increase the size of a struct in a vector? | A problem I'm working on involves a large tree structure. Initially I was creating the tree by newing new nodes and attaching them to their parent node and such. This was taking an awful long time. A friend suggested instead I forgo the dynamic memory allocation and structure the tree as an array with offsets to child ... | You're not using dynamic allocation, but the vector class is. The internal vector<int> is storing its variable-length array externally to the Entry object that you're putting in the outer vector.
|
5,681,948 | 5,682,082 | Multiple Textures OpenGL GLUT C++ | Okay still having a few problems with it, this is what I have so far:
Bitmap Display::m_HeightMap;
unsigned int Display:: textures;
My initialise method:
glEnable(GL_TEXTURE_2D);
Bitmap image[2];
GLuint *textures = new GLuint[2];
glGenTextures(1, textures);
glGenTextures(2, textures);
image[0].loadBMP("myTexture.bm... | So. glGenTextures takes two parameters. An int, and a GLuint*. The int tells GL how many textures to generate, and the GLuint* is an array of GLuints (where to generate the textures). The reason you do the following...
GLuint m_TextureID
glGenTextures(1, &m_TextureID)
is because you only have one texture. If you have ... |
5,682,205 | 5,683,176 | What's the best tool you can use to learn to program shaders? | I've recently been doing some DirectX 10 work and I'm looking to move to DirectX 11 and Shader Model 5.0. I've written a few very simple shaders in the past and I'm looking to broaden my horizons and venture into more complex shaders. My question is sort of multi-fold:
What is the best tool out there to program shader... | What is your ultimate goal? If you'd just like to know a little more about shading, or if you are an artist or technical artist, then 1. FX Composer and RenderMonkey are pretty good.
If you are a programmer and you'd like to make graphics engines, then 1. you should use a text editor, because the shader is just one sm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.