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
7,015,362
7,015,555
<unresolved overloaded function type> when trying to pass an aggregated object's method to its class method
I have some problem compiling my code. I have the following structure: #include <cstdlib> using namespace std; typedef double (*FuncType)(int ); class AnotherClass { public: AnotherClass() {}; double funcAnother(int i) {return i*1.0;} }; class MyClass { public: MyClass(AnotherClass &...
The following function class will match the signature of your FuncType: struct Foo { AnotherClass & a_; Foo(AnotherClass & a) a_(a) {} double operator()(int i) const { return a_.funcAnother(i); } }; Change MyClass::compute to a template, thusly: template<typename FuncType> void MyClass::co...
7,015,860
7,015,873
Algorithm to make a polygon from an image
I came across an application called PhysicsEditor and it traces images and results in vertices that make up the shape. I'm interested in implementing something that would do this but I'm not sure what type of algorithm can do this.
You get all of the points that make up the image (you might need to do this with edge detection or some kind of PCA if you're dealing with bitmaps) Then you compute a convex hull : http://en.wikipedia.org/wiki/Convex_hull
7,015,874
7,016,822
OpenCV running kmeans algorithm on an image
I am trying to run kmeans on a 3 channel color image, but every time I try to run the function it seems to crash with the following error: OpenCV Error: Assertion failed (data.dims <= 2 && type == CV_32F && K > 0) in unknown function, file ..\..\..\OpenCV-2.3.0\modules\core\src\matrix.cpp, line 2271 I've included the ...
The error says all: Assertion failed (data.dims <= 2 && type == CV_32F && K > 0) These are very simple rules to understand, the function will work only if: mImage.depth() is CV_32F if mImage.dims is <= 2 and if K > 0. In this case, you define K as 6. From what you stated on the question, it seems that: IplImage* ipl...
7,016,011
7,016,991
Number of Concurrent Threads in CreateIoCompletionPort
On MSDN page for CreateIoCompletionPort there's a very short description for the last parameter of this function: NumberOfConcurrentThreads [in] The maximum number of threads that the operating system can allow to concurrently process I/O completion packets for the I/O completion port... What exactly does it mean...
See http://msdn.microsoft.com/en-us/library/aa365198(v=VS.85).aspx When the total number of runnable threads associated with the completion port reaches the concurrency value, the system blocks the execution of any subsequent threads associated with that completion port until the number of runnable threads drops...
7,016,016
7,016,302
Is ModelViewProjection the same as WorldViewProjection?
I am converting some code from HSLSL and XNA to CG and OpenGL. The code is for rendering volume data. But volume data is not also sampled using the same distance in each dimension, for example (0.9f, 1f, 1f). So a scale factor need to be applied. In the XNA and HLSL example, they do the following: mul(input.Position * ...
The volume is been rendered with glMatrixMode set to GL_MODELVIEW. Will I have to create my own matrices? If so, any good tutorials? :D glMatrixMode is kind of like a with statement for the other matrix manipulation functions. So glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslate(...); is to be interpreted l...
7,016,098
7,016,180
Implicit conversion from char** to const char**
Why my compiler(GCC) doesnt implicitly cast from char** to const char**? Thie following code: #include <iostream> void print(const char** thing) { std::cout << thing[0] << std::endl; } int main(int argc, char** argv) { print(argv); } Gives the following error: oi.cpp: In function ‘int main(int, char**)’: oi....
Such a conversion would allow you to put a const char* into your array of char*, which would be unsafe. In print you could do: thing[0] = "abc"; Now argv[0] would point to a string literal that cannot be modified, while main expects it to be non-const (char*). So for type safety this conversion is not allowed.
7,016,206
7,016,400
Trying to CreateDirectory, getting char* to LPCWSTR error, willing to try another function
I've tried Googling this, and there are so many answers based on various specific situations that frankly I'm more stuck than I was when I started. The facts are these: Language: C/C++ OS: Windows IDE: Visual Studio 2005 I'm trying to create a directory from a function in my program, using CreateDirectory (after a #i...
This is completely crazy. Microsoft have mechanisms to support both ANSI (as they call it) and UNICODE from the same code, because Windows 95/8/Me were ANSI operating systems and NT/XP/Vista etc are UNICODE operating systems. So if you really want to you can write one set of code that supports both systems and just rec...
7,016,663
7,031,074
Loading Mixed-Mode C++/CLI .dll (and dependencies) dynamically from unmanaged c++
I have a managed C++ assembly I'm loading dynamically in an unmanaged c++ application through a standard LoadLibrary() call. The managed C++ assembly has dependencies on several more managed (C#) assemblies. Everything worked fine until I moved all the managed assemblies to a subdirectory of the unmananged application....
The CLR gets loaded in an unusual way in this scenario, through a thunk that the compiler injected when compiling the native export for __declspec(dllexport). Doing this is fine, it just isn't particularly fast. The CLR will go out hunting for a .config file to initialize the primary AppDomain. And will look for MyCo...
7,016,730
7,016,940
Compiling with Clang using Libc++ undefined references
The first couple are too long to reference. I get this error when I try to compile clang++ -stdlib=libc++ ../main.cc ... with clang and libc++ from the SVN. error: undefined reference to 'typeinfo for char const*' error: undefined reference to '__cxa_allocate_exception' error: undefined reference to '__cxa_throw' /tmp...
I believe libc++ doesn't support all exception functions yet. See the status page: http://libcxxabi.llvm.org/spec.html You could probably link against gnu's libstdc++
7,016,861
7,016,898
Why are NULL pointers defined differently in C and C++?
In C, NULL is defined as (void *)0 whereas in C++ it is 0. Why is it so? In C I can understand that if NULL is not typecast to (void *) then compilers may/may not generate warning. Other than this, is there any reason?
Back in C++03, a null pointer was defined by the ISO specification (§4.10/1) as A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero. This is why in C++ you can write int* ptr = 0; In C, this rule is similar, but is a bit different (§6.3.2.3/3): An integer ...
7,017,010
7,017,152
Implementing parallel exceptions to get trees of errors?
Consider the following code: // this method should add numbers, the requirements are: // x >= 3 and y <= 5 int add(int x, int y) { if(x < 3) throw new ...; if(y > 5) throw new ...; } It's absolutely traditional approach, but in case you pass invalid values for both x and y, you'll only get an exception for x. Why ...
You seem to want to enforce a set of business rules. One approach is to create a collection of broken rules and add specific broken rules (e.g. input too short, input must be alphanumeric) as separate elements of that collection, then throw a BrokenRulesException that includes the collection of broken rules as a parame...
7,017,518
7,017,556
c++ file will not compile with a certain #include while all others do
I have a c++ file that keeps throwing errors about four files up the chain, while every other file using that #include compiles fine. It keeps giving me this kind of stuff. I am certain the include file is fine as 1. All of the others which use this same file compile fine and 2. I looked at the file, and it is fine. /u...
Assuming you're using gcc, run gcc -E your-file.c > tmpfile. This runs just the preprocessor. The output is going to be quite voluminous, but it should help you track down the problem. What does line 305 look like? EDIT: Given your update, yes, the problem is that "None" is being defined as a macro before your mediaf...
7,017,593
7,017,624
strange cout behaviour
I compiled on Ubuntu a program that was developed for (and works on) Windows. On Ubuntu, I see this code: string s = values_[9]; cout << s << endl; cout << s << "x\n"; producing this output: high xigh The expected output for the second line is "highx". I know that the value of values_[9] is originally read from a f...
Run the command with its output piped through cat -A. Probably either the value of s, or the output produced by endl is giving you a '\r' character, which typically sends the cursor back to the beginning of the line. EDIT: On further thought, the stray '\r' is almost certainly in s, not in the output produced by endl....
7,017,605
7,019,537
Structuring C++ class hierarchies for maintainability and encapsulation
I have some general questions about encapsulation as it relates to maintainability. Here is an example class that I used to assist in the construction of a parse tree. (I have avoided STL for education's sake.) The Node class describes a node in a tree. The managing class ParseTree (not shown) is responsible for buil...
Ask yourself, what's a Node? Clearly, it's something that may have a parent, a left child and a right child. It also holds a pointer to some data. Does a node have a height? It depends on the context, is it possible that your nodes may at some point be part of a cycle? A ParseTree has a concept of height, it doesn't se...
7,017,785
7,018,684
macro solution for duplicate, const and non-const, getters?
Can this solution be turned into a macro so that I call something along the lines of: CALL_CONST_FUNC(objToReturn, thisPtr)->SomeConstFunc(); For functions that return a value and another for functions that don't. My macro token skills are not that great so I thought maybe someone here can come up with one (or tell me...
If a function doesn't return a value (reference or pointer), do you need const overloads in the first place? It seems that the only reason to have two is to get a const or non-const reference out of the class. Otherwise the const version alone should be enough. As to making the idiom sweeter, how about a few template h...
7,017,807
7,017,891
Any way to detect 64 bit vs 32 bit machine in QT Creator .pro file?
I am linking to a .a lib and need to link to the right version for the machine that's compiling. Is there a way to detect the type of machine in a .pro file in linux? I found this article, but they only discuss Windows: http://developer.qt.nokia.com/faq/answer/how_can_i_detect_in_the_.pro_file_if_i_am_compiling_for_a...
By doing your conditional on a mkspec, (see Platform Scope Values here), you can check for a very large variety of compiler/platform. My mkspec directory (Linux64 machine), gives the following differentiations: aix-g++/ irix-g++-64/ qconfig.pri wince50...
7,018,009
7,018,091
C++ -- Why 'what' print "Unknown exception" in catch scope?
try { range_error r("Hi I am hereeeee!"); cout << r.what() << endl; // print "Hi I am hereeeee!" // case one exception *p2 = &r; cout << p2->what() << endl; // print "Hi I am hereeeee!" // case two throw p2; } catch (exception *e) { cout << e->what() << endl; // print "Unknown exception" ...
This program results in undefined behavior. Because the variable r is declared inside the try block, it goes out of scope before the catch handler is invoked. At this point, e points to some area on the stack where an object of type range_error used to exist. The following program should print the expected results: r...
7,018,183
7,018,298
Provide array of derived objects to function that operates on base objects
Finding the appropriate title to this question is a little difficult for me, but here is my situation. Say I have a base class and a derived class, can I pass a function that takes a parameter of type *base a type of instead *derived class base { protected: float M_OutputValue; float M_InputValue; public: ...
You are right. Stay away from arrays, and preferably use std::vector<std::unique_ptr<base>> or if you don't have a C++0x-ready compiler (if this is the case, then consider upgrading), you can use boost::ptr_vector<base> Both are vectors of pointers which automatically clean up the pointed to objects. Avoid raw point...
7,018,228
7,018,258
How do I redirect output to a file with CreateProcess?
I tried using CreateProcess to run a simple command like hg > test.txt. I tried running the string as a whole (as opposed to separating it into an application name and its parameters). Why does CreateProcess(0, "notepad.exe test.txt", ...) work but CreateProcess(0, "hg > test.txt", ...) does not?
You can't use stdout redirection in the command line passed to CreateProcess. To redirect stdout you need to specify a file handle for the output in the STARTUPINFO structure. You are also making another, more subtle, mistake. The second parameter, lpCommandLine must point to writeable memory because CreateProcess over...
7,018,357
7,018,544
How to convert STL string vector into char* in an elegant/quick way?
This splits to smaller stages: How do I calculate the total length of the all the strings in the vector? Allocate the char* mem space Copy the vector strings into that space Is there a quick elegant way to do that?
The most elegant, but perhaps not the quickest, way that I can think of would be the following: std::string s = std::accumulate(v.begin(), v.end(), std::string()); char * c = new char[s.size() + 1]; std::strcpy(c,s.c_str()); Although I'm not myself a fan of naked dynamic allocation, and personally would never use it, ...
7,018,510
7,018,545
Confusing C++ code involving *this?
Could someone explain this code? I don't understand line 3: MyString MyString::operator+(const MyString &str) { MyString ss(*this); //----> explain this part ss += str; return ss; } Thanks!
This code: MyString ss(*this); Says "declare a new variable of type MyString that's named ss, and initialize it as a copy of *this." Inside of a member function, this is a pointer to the receiver object (the object that the member function is acting on), so *this is a reference to the receiver object. Consequently, ...
7,018,854
7,019,241
Why does using the wrong calling convention sometimes work?
I used "StartServiceCtrlDispatcher" function to register a callback function (called ServiceMain) in windows, but the callback function I declared got compiled with the wrong calling convention. The thing is that on some computers, when the application returned from the callback function, the application crashed, but o...
This is all very Windows-specific, we're not talking standard C++ here. Checking out the documentation of StartServiceDispatcher it has only one argument, and is declared as WINAPI which in turn means __stcall calling convention. For freestanding functions, __stdcall is one of two main calling conventions. The other on...
7,019,092
7,019,107
How the create "Application file" for code in visual studio 2010
I have a project in c++ with a sime gui (form) I remember that the application file (file that runs the project) should be in the "Debug" directory of the project, but I don't find it. How can I create this file ? Thanks
Hit the "Build / Build Solution" menu command?
7,019,310
7,019,362
Effectively changing constness of member variable in subclass
While developing a game I have designed a class that in normal operation has a const member variable like so: class Foo { /* ... */ protected: const boost::unordered_map<short, short> m_map; }; However, in the accompanying game editor I would like to reuse the Foo class, but provide a way to edit this const me...
If making your variable non-const and protected feels too intrusive perhaps you can have a design where the variable is non-const and private, and provide protected member functions to manipulate it with whatever constraints you had in mind when you made the variable const in the first place.
7,019,454
7,019,483
Why does std::cout output disappear completely after NULL is sent to it
It took me a while to figure out why some cout output seem to disappear into the ether. The culprit: std::cout<< "This line shows up just fine" << std::endl; const char* some_string = a_function_that_returns_null(); if (some_string == 0) std::cout<< "Let's check the value of some_string: " << some_string << std::en...
const char* some_string = a_function_that_returns_null(); Do you mean that it literally returns a null pointer? [2003: 27.6.2.5.4]: template<class traits> basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const char* s); 3. Requires: s is non-null. Then streaming some_string is Undefined Behav...
7,019,471
7,019,541
performance of find in an unordered_map
I know this is probably a stupid question, but I wanted to make sure and I couldn't readily find this information. What is the performance characteristic of find() in an unordered map? Is it as fast/nearly as fast as a normal lookup? I.e. std::string defaultrow = sprite.attribute("defaultrow").value(); auto rclassIt = ...
find and operator[] on an unordered container are O(1) average, O(n) worst-case -- it depends on the quality of your hash function.
7,019,527
7,019,604
How to get the time in milliseconds since epoch time from boost::posix_time::ptime
I've seen some other answers on SO that suggest we can get the time from epoch in milliseconds by subtracting the epoch time from the "other" time, but it doesn't work when I try it: ptime epoch = time_from_string("1970-01-01 00:00:00.000"); ptime other = time_from_string("2011-08-09 17:27:00.000"); long diff = (other...
Presumably you're on a platform on which long is smaller than 64 bits. Let's assume it's 32 bits – in that case, the maximum value of a long is 2147483648. However, it's been ~1312000000000 milliseconds since epoch, so long is clearly insufficient to hold this value and consequently you're seeing overflow. I'd do somet...
7,019,564
7,019,598
Detect and Report typedef Errors... What's This Doing?
I was reading about making code more portable by using fixed-width integers. I found this article which helped explain things, and at the end it suggests using this anonymous union to detect and report typedef errors: static union { char int8_t_incorrect[sizeof( int8_t) == 1]; char uint8_t_incorrect[sizeof(...
It's abusing the compiler, that's what it's doing. Basically the sizeof(type) == num is being evaluated at compile time, and it's going to produce either a 0 or a 1 (false or true). If it's 0 (which none of them should be), it produces a compiler error, since you can't declare an array of size zero. But as mentioned, t...
7,019,589
7,019,691
C++ reading from a multi-type csv file
I'm trying to use C++ to read from a file, which is structured like this: frank, 80, 90 johnny, 10, 25 ... I made a loop to go through each line of the file, but every time I read the name string, the comma is included with the name (so instead of frank I get frank,). My code in question is: // var declarations ifstre...
IIRC the streams use space as a default delimiter and you will have to specify that ',' is another delimiter. Here's another question on SO regarding specifying delimiters, that should solve your problem.
7,019,848
7,019,867
Convenient way to convert vector<string> to vector<double>
Is there any convenient way in C++ to convert a vector to a vector other than using transform algorithm and istringstream? Thanks a lot for your help!
lexical_cast is quite "convenient". for(size_t i = 0; i < vec.size(); ++i) { vec2.push_back(boost::lexical_cast<double>(vec[i])); } Of course this becomes even more fun with std::transform: std::transform(strings.begin(), strings.end(), std::back_inserter(doubles), boost::lexical_cast...
7,019,849
7,019,878
Convert only digits to int in a std::string
I'm trying to convert only the digits from a string to an int vector, but that gives me the ASCII codes for numbers 0 to 9 instead. Is there any way to convert only the digits to integers? I guess I'll have to use a char array since atoi() don't work with std::string and the c_str() method don't work for every characte...
ASCII Character ASCII Code(decimal) Literal Integer '0' 48 0 ... ... ... '9' 57 9 int(chars_and_numbers[i]) returns you the underlying ASCII code of ASCII character instead of the literal intege...
7,019,856
7,019,890
Does different instances of boost::array with different sizes generates whole new classes?
If I make some code like this: boost::array<10> a1; boost::array<20> a2; boost::array<30> a3; Will the template generate 3 different classes for me and make the size of my code grow? If it does, is the compiler/linker smart enough to only include the methods definitions of what I'm actually using? For example: if I us...
Will the template generate 3 different classes for me Yes; every instantiation of a template with different template arguments in in effect a different type. and make the size of my code grow? Extremely unlikely, certainly no worse than enabling inlining does. If it does, is the compiler/linker smart enough to onl...
7,020,038
7,020,070
How to get C++ to perform I/O from a USB Port like a Serial Port
Is it possible to read/write from/to a specific USB port, avoiding all that USB handshaking stuff? What I want to do is communicate with a microcontroller, for example, that doesn't have a USB driver on board via USB. I want my C++ application to be able to send data via a specific USB port and then to receive data fro...
Use one of the USB to serial port adapters. The USB port will look just like a serial port to your C++ program.
7,020,292
7,020,407
How to ensure that the template parameter is a subtype of a desired type?
I have a template class, what I want to do are the following Make sure that an object is instantiated only if the template parameter passed is a subtype of a desired type Communicate to the user of the code upfront what is it that the template parameter must satisfy (1) is sort of taken care automatically in the sens...
Given some complete type MyBase, the following will yield a compile-time error if T is not derived from MyBase: #include <boost/type_traits/is_base_of.hpp> #include <boost/static_assert.hpp> template<typename T> class Foo { BOOST_STATIC_ASSERT_MSG( (boost::is_base_of<MyBase, T>::value), "T must be ...
7,020,381
7,020,507
Finding center of a set of points to sort them clockwise?
I want to sort a vector of points in clockwise order to form a polygon but I need the proper center to do so. I have tried the averages method, but a few of the points did not sort correctly at all. What is the correct way to find the center that will work when sorting points in a clockwise manner? It is failing on the...
The notion of "sorting in clockwise order" is not well-defined if you don't have a pre-defined center point. If all you have is just a bunch of points that you need to sort and you don't know the center in advance, then the problem does not generally have a single solution. The problem has many alternative solutions, ...
7,020,464
7,020,495
C++ macro causing null pointer
I was wondering if someone can explain this macro to me. #define Q_DECLARE_PRIVATE(Class) \ inline Class##Private* d_func() { return reinterpret_cast<Class##Private *>(d_ptr); } \ inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(d_ptr); } \ friend class Class##Private; I...
The compiler can explain it best of all: g++ -E foo.cc will put foo.cc to stdout after passing through the pre-processor. It lets you see what the compiler sees which (especially with token pasting) is usually less than obvious.
7,020,869
7,020,885
In Windows, can you programmatically (C++) detect which DLLs have been loaded by other running programs?
I hope this is not a no-brainer question, but in Windows, is it possible to programmatically (C++) check which DLLs have been loaded by other concurrently running programs? I know that the GetModuleHandle functions can be used to detect DLLs that have been loaded by the current program, but it does not work across prog...
Toolhlp32.dll does that. See here: http://msdn.microsoft.com/en-us/library/ms686840(v=VS.85).aspx The API you ultimately want is Module32First/Next.
7,020,974
7,021,307
Scheduled task for C++ EXE not working
I've bought a VPS, but it has been restarting on occasion. The server is meant to be running my game server 24/7, but when it restarts obviously the game goes down too. I'm trying to setup a scheduled task to run the C++ game server EXE on start up, but it isn't working. I've already set a scheduled task to run WAMP so...
Since you are using Windows Server 2003, check out here to allow services to interact with desktop.
7,021,016
7,021,030
Is it advisable to use extern to avoid header dependency?
I have eliminated two header inclusions in a translation unit using extern. Is this advisable? My specific situation: I have a class called ParseTree that accumulates Token*'s. ParseTree* is a private member of Parser. Initially, I had the following lines in parse_tree.cc. #include "parser.h" #include "token.h" Afte...
If you use extern declarations, you're unnecessarily repeating yourself by restating the prototype of the function everywhere you use it. With a header file, if you want to change the prototype, you only need to change it in one place. So no, don't use extern when you already have a suitable header file.
7,021,164
7,028,082
How can I protect a vector with a Mutex?
I am working on designing a C++ server that accepts multiple different interacting clients, and I use vectors to keep track of all of them individually. However, I realized that, because of so many threads running, there's a tiny chance a vector might be read and written to at the same time by two threads. Is there a q...
Since you are using VS2010, you should use Concurrency::concurrent_vector. But be aware that there are limitations with this class, and is not fully thread-safe. You may use Concurrency::critical_section or Concurrency::reader_writer_lock. Reader-writer lock would give good performance when there are more reads than wr...
7,021,371
7,022,418
Boost lib appears to be missing hpp files?
I'm trying to compile a C++ project that requires Boost. I downloaded the latest build from the web site and copied the appropriate files to the appropriate libs folder (I'm using MinGW). When I compile, I'm get this error: In file included from main.cpp:4:0: headers.h:59:29: fatal error: boost/foreach.hpp: No such fi...
You should make sure that your include path is set correctly. Assuming you downloaded Boost 1.47.0 your path should contain the location to your Boost installation up to the boost_1_47_0 directory, but leaving out the boost one, e.g. /path/to/boost/boost_1_47_0 and not /path/to/boost/boost_1_47_0/boost
7,021,420
7,030,795
Boost::Spirit mini_c tutorial
Is there any tutorial describing mini_c example from boost::spirit? It looks as good example of using grammar from boost::spirit::qi, but it's rather complex one and some guide through the code would be helpful.
None that I know of. However, the mini_c example is step 9 in a series of calculator examples. Therefore, if you start working from calc1.cpp up to mini_c (or even the new 'conjure' examples now added to SVN) you shouldn't have a hard time understanding what's going on.
7,021,451
7,021,559
can i pass std::ostream& to a function expecting std::ofstream
What i'm trying to do is: I want to redirect my error message erither to std::cerr or to a file depending upon the command-line argument. If there is no log file provided then the program should output the error message on screen. Here is my approach: class A { void SetLogFileStream(T& err_outstream); }; //main.c...
Declare the method as this: class A { void SetLogStream(std::ostream& err_outstream); }; There are several problems with your code. The file stream opened gets out of scope and is destroyed. You need to fix it like this: std::ofstream f; // <-- this have to remain in scope while you use it for 'a' A a; if(args > ...
7,021,529
7,021,544
Dynamic size of array in c++?
I am confused. I don't know what containers should I use. I tell you what I need first. Basically I need a container that can stored X number of Object (and the number of objects is unknown, it could be 1 - 50k). I read a lot, over here array vs list its says: array need to be resized if the number of objects is unknow...
std::vector is what you need. You have to consider 2 things when selecting a stl container. Data you want to store Operations you want to perform on the stored data There wasa good diagram in a question here on SO, which depitcs this, I cannot find the link to it but I had it saved long time ago, here it is:
7,021,624
7,021,669
error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion)
I am really confused on why I am getting following compilation error. Microsoft Visual Studio Compiler. error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion) #include <stdio.h> #include <iostream> #include <sstream> #include <itera...
You declare the method as const const char* what() const throw(){ but then you try to change the object m_message = custom_message.str(); so you get an error. What you should do instead is construct the custom message in the constructor. class MyException { public: MyException(const std::string& message, int lin...
7,021,833
7,022,813
Handle uploaded file with cgi c++ on apache2
Can we handle uploaded file from a html form with cgi c++ on apache2?
Yes, you could ;) Requirements for your code is the same as for perl, etc: your cgi script (application in your case) should do correct output, should be able read data from stdin, etc... You could check this as example http://www.yolinux.com/TUTORIALS/LinuxTutorialC++CGI.html
7,021,888
7,022,345
Ensure GLSL compatibility
How can ensure that GLSL shaders are compatible with most modern cards? I've got a software where I use GLSL code from here. But even though I've added #version 120 to the beginning of my final shader and made sure it compiles, on some users computers they get shader compilation errors (even though they support OpenGL ...
There is no tool for validating a shader. Even if there was, it wouldn't be useful to you, because what good is a shader that is "valid" if it doesn't run on the hardware you want? You can be right all you want, but if your hardware rejects it even though you're technically right, your shader still won't run. If a shad...
7,021,956
7,021,989
Menu item without a modifier key
I want to create menu using GTK+. My question is: is there any way to create menu items with accelerators, but without a modifier key?
Just put an underscore before the underlined letter, it will be underlined and used as a shortcut. For example, in pygtk: copy = gtk.ImageMenuItem(gtk.STOCK_COPY) copy.set_label("_Copy It!")
7,021,963
7,022,605
Converting variable type (or workaround)
The class below is supposed to represent a musical note. I want to be able to store the length of the note (e.g. 1/2 note, 1/4 note, 3/8 note, etc.) using only integers. However, I also want to be able to store the length using a floating point number for the rare case that I deal with notes of irregular lengths. class...
I see several possible solutions: the first is just to use double. It's true that extended computations may result in inaccurate results, but in this case, your divisors are normally powers of 2, which will give exact results (at least on all of the machines I've seen); you only risk running into problems when dividin...
7,022,082
7,037,609
How to find closed loops in graph networks
I have an undirected graph network made of streets and crossings, and I would like to know if there is any algorithm to help me finding closed loops, ie places where I can put buildings. Any help appreciated, thanks !
Based on comments to my earlier answer: It seems the graphs are all undirected and planar, i.e. can be embedded in a 2D plane without crossing edges, and one such embedding is given. This embedding will partition the plane. E.g. a figure 8 partitions the plane in three: two "inner" areas and an infinite outer area. An ...
7,022,196
7,047,680
How to monitor apps which are being executed by user
I want to create an application/service to monitor user activity, especially to log every application that user is running. Is this possible in c#? I think not. So how to do this in c++ and winapi? I don't want whole solution because it's surely complicated. Give me an advice only. Thanks!
You could write a DLL that hooks CreateProcessW. In this hook, you would (a) do what you want to do when a process is spawned, and (b) inject itself into the new process. Then, inject the DLL into all currently running processes. EDIT: My answer to another related question should help you.
7,022,208
7,022,412
Convert QString to Local8bit then Converted String to QString
How can i convert this to local8bit then converted string to QString: QString m = QString::FromStdString("Ú©Ù?Ù?ات Ù?رتبط(0):<BR> <BR><HR><BR><BR><A href='bword://0'>بازگشت بÙ? Ù?اÚ?Ù? 0</A></B><BR><BR><HR><BR><A href='bword://latitude (l,0)'>latitude (l,0)</A> <BR> <B...
If I understand correctly you are looking for the following functions: std::string str = m.toLocal8Bit().data(); and vice versa QString m = QString::fromLocal8Bit("SomeText in Local");
7,022,990
7,023,278
Unzipping a file from C++ on Redhat: alternatives to system()
I need to unzip a file while running a C++ program (as described in Waiting for unzip to finish before carrying on C++ code on a RedHat machine) To do this I currently do something like this: system("unzip /usr/bin/File/ZippedFile.gz -d /usr/bin/File/) Which unzips "/usr/bin/File/ZippedFile.gz" to "/usr/bin/File/Zippe...
You can use plain zlib, or the boost::iostream gzip facility. System isn't wrong per se, but you could also write a replacement for it which doesn't use the shell with fork, exec, wait and mkstemp. This is cumbersome though. Using boost::gzip_decompressor is the best C++ option to me if you decompress single files. Fo...
7,023,188
7,023,318
stl::map erase vs std::vector erase behave differently
class CSensor { public: CSensor(int nVal1,char* pVal2,unsigned int nVal3); CSensor(const CSensor& refMessage); const CSensor& operator=(const CSensor& refMessage); ~CSensor(void); private: int m_nVal1; char* m_pVal2; unsigned int m_nVal3; }; // vector erase std::vector<CSensor> ...
This is not a behaviour of .erase per se, but a consequence of how each respective container works. Deleting from a vector When you delete from a vector (List is a really poor name for a vector, btw), its contents must be shuffled along to fill the gap because the elements of a vector are always stored contiguously in ...
7,023,211
7,023,264
using compile time constant throws error
in the below program i have used static const int init. But it is throwing error /tmp/ccEkWmkT.o(.text+0x15d): In function check::operation()': : undefined reference tocheck::init' This error is coming only when used with vector. Can someone please help? what is the exact behaviour?? #include<vector> #include<iostream...
If you pass it by reference it is "used" and you may have to define in the .cpp file so that it gets an address. If you just use the value of the constant, you might get away with not defining it.
7,023,539
7,023,657
Create vector of sizes of the vectors inside a "2d-vector" (vector< vector<> >)?
I have a vector of vectors, say std::vector< std::vector<int> > my2dArray; Now I would like to have a vector that contains the sizes of the vectors inside my2dArray. Manually this would look something like std::vector<int> mySizes; for (int i = 0; i < my2dArray.size(); i++ ) { mySizes.push_back( my2dArray[i].size() ...
C++03: typedef std::vector<int> IntVec; std::vector<size_t> sizes(my2dArray.size()); std::transform(my2dArray.begin(), my2dArray.end(), sizes.begin(), std::mem_fun_ref(&IntVec::size));
7,023,634
7,024,394
Swap position of two iterators in container
I want to swap position of two iterators first and second in container and also keep them valid after operation. Moreover if I have iterator other pointing at the same value as first I want to keep it valid too (keep it pointing at the same value). Is it possible to achieve with any STL container?
std::list allows you to splice a piece of one list into another (removing it from the first list) without invalidating any iterators, references or pointers, and the source list and destination list can be the same object. (This is according to the draft C++11 standard; I don't know if the C++03 standard says the same ...
7,023,666
7,023,690
A doubt about sizeof
I was trying to do something using sizeof operator in c++. Please refer to the following code snippet. http://ideone.com//HgGYB #include <iostream> using namespace std; int main() { int *pint = new int[5]; int temp = sizeof(*pint); cout << "Size of the int array is " << temp << endl; return 0; } I was...
Here is pint is an int*. So, sizeof(*pint) == sizeof(int) Compiler doesn't know about new int[5], when it does sizeof(*pint) (because sizeof() is a compile time operator). [Note: Try the same test with statically declared array, int pint[5]; and will see the expected result. Additionally, sizeof() returns size_t (whic...
7,023,751
7,023,767
reference collapsing for local variables
In a function template parameterized on T, the type T&& may or may not be an rvalue reference, depending on the value category of the argument: template <typename T> void function(T&& x) { // ... } std::string some_named_string; function(some_named_string); // T&& is std::string& function(std::string("hello...
Yes. auto is exactly specified as template argument deduction.
7,023,827
7,024,041
LPBYTE data to CString in MFC
I am encrypting data using CryptProtectData function and I am getting encrypted data in LPBYTE format, I want to save that data into a file and then read back for decryption. In order to write string in file, I used following one to convert LPBYTE data to CString: CString strEncrUName = (wchar_t *)encryptedUN; I even t...
The encrypted data is a buffer of raw bytes, not characters. If you want to convert it to a string, you'll have to encode it somehow, such as by converting it to Hex chars. eg. byte 0xd5 becomes 2 chars: "D5" Looping through each byte and converting it to hex chars is an easy exercice left up to the reader. Of course, ...
7,024,154
7,024,231
Will std::swap still be defined by including algorithm in C++0x?
The swap function template was moved from <algorithm> to <utility> in C++0x. Does the former include the latter in C++0x? Or do they both include a common header the defines swap? In other words, is the following code guaranteed to compile in C++0x? #include <algorithm> // will this pull in std::swap? // ... using ...
The FDIS (n3290), in Annex C, "Compatibility", C.2.7 says: 17.6.3.2 Effect on original feature: Function swap moved to a different header Rationale: Remove dependency on <algorithm> for swap. Effect on original feature: Valid C++ 2003 code that has been compiled expecting swap to be in <algorithm> may have to ins...
7,024,198
7,024,227
std::for_each, object with operator() overloaded not maintaining state
In trying to answer this question I came up with the following code: #include <string> #include <iostream> #include <algorithm> #include <vector> class Sizes { public: void operator() ( std::vector<int> v ) { sizeVec.push_back( v.size() ); } std::vector<int> sizeVec; }; void outFunc (int i) { ...
std::for_each takes a functor by value, not by reference, so the original object is unaffected. You need to do: sizes = std::for_each( twodVec.begin(), twodVec.end(), sizes );
7,024,339
7,024,491
Missing header from Qt
I'm getting error while compiling qt project which #include's < qvaluelist.h > that this file cannot be find, yet I'm finding on qt website documentation for this header. How to solve it?
This (and its friend QPtrList) are deprecated in Qt 4. You probably have Qt 3 code. Look here: Porting to Qt 4 You can either link with the QT3 support library in Qt 4 or replace it with QList.
7,024,414
7,024,599
Can type_info pointers be used to distingush types in C++?
I have a set of polymorphic C++ classes and they are all instantiated by the same module (Windows DLL). Now having two pointers to such classes and having called typeid: SomeCommonBase* first = ...; //valid pointer SomeCommonBase* second = ...; //valid pointer const type_info& firstInfo = typeid( first ); const type_in...
As I'm writing this, your code is SomeCommonBase* first = ...; //valid pointer SomeCommonBase* second = ...; //valid pointer type_info& firstInfo = typeid( first ); type_info& secondInfo = typeid( second ); It should not compile because typeid returns a reference to const. Worse, you are asking for type info about the...
7,024,433
7,024,600
Sending http and https requests from C/C++
Is there any other variants to send http/https request from C/C++ except using libCurl? I can't figure out how to use libCurl with OpenSSL :( I want to interact with YoutubeAPI.
SFML has a nice, simple to use in-built HTTP implementation. You can find a tutorial here. It looks to me that for youtube you can simply use POST - look here.
7,024,615
7,031,183
Putting a for loop in a CUDA Kernel
Is a bad idea to put a for loop in a kernel? or is it a common thing to do?
It's common to put loops into kernels. It doesn't mean it's always a good idea, but it doesn't mean that it's not, either. The general problem of deciding exactly how to effectively distribute your tasks and data and exploit related parallelisms is a very hard and unsolved problem, especially when it comes to CUDA. Act...
7,024,746
7,026,556
Equations Equality test (in C++ or with Unix tools) (algebra functions isomorphism)
I am looking for C++ open-source library (or just open-source Unix tool) to do: Equality test on Equations . Equations can be build during runtime as AST Trees, string or other format. Equations will mostly be simple algebra ones, with some assumptions about unknown functions. Domain, will be integer arithmetic (no flo...
Your topic is one of automated theorem proving, for which a number of free/open source software packages have been developed. Many of these are meant for proof verification, but what you ask for is proof searching. Dealing with the abstract topic of equations would be the theories mathematicians call varieties. These...
7,024,818
7,024,843
What's the lifetime of the object returned by typeid operator?
If I call typeid and retrieve the address of returned type_info: const type_info* info = &( typeid( Something ) ); what's the lifetime of the object returned by typeid and how long will the pointer to that object remain valid?
However the implementation implements them, the results of typeid expressions are lvalues and the lifetime of the objects that those lvalues refer to must last until the end of the program. From ISO/IEC 14882:2003 5.2.8 [expr.typeid]: The result of a typeid expression is an lvalue [...] The lifetime of the object refe...
7,024,910
7,025,155
Framerate differences and UDP connections
I am writing a Kinect WPF application in C# to send gesture commands to aLinux C++ application. My problem is when the Linux app's framerate drops below the Kinect's (25fps), it begins to register commands incredibly slow. A rotation would occur 5 or so seconds after the information was sent. From this I feel as if its...
What are possibly solutions to alleviate this delay? A very simple method would be to use acknowledgement packets. Send a bunch of messages (up to a chosen threshold, for example, 1 second's worth). As long as the acknowledgement packets are received, you will continue to send data packets about what is happening on ...
7,024,967
7,504,065
remove Protected section from Documentation?
I have been using doxygen to generate html document for my project. And my generated documents contain a files tab. How could I remove protected attribute and protected member function fields from it? Protected Member Functions Protected Attributes
If you do not wish something to be extracted it should not have a documentation block. In your release provide a header file that has only the methods you wish to be exposed, create a separate header file for your own use. You may also use the \internal flag if you want internal documentation for your benefit, howeve...
7,025,043
7,075,700
Path stroke algorithm (convert to triangles/quads) or other suggestions
Does anyone know a good algorithm for converting a vector path into a stroked path that is composed of triangle/quad faces? Ideally with round line joins. Basically I am trying to draw a thick path that whose colour is based upon a value that varies with the distance along the path. I'm thinking that converting the pa...
For anyone looking for a solution to this, I found this useful: https://keithp.com/~keithp/talks/cairo2003.pdf So you can effectively convolve a regular polygon with the line to generate the mesh. Requires a slightly more complicated algorithm than outlined in the pdf in order to output triangles, but it's not actuall...
7,025,054
7,025,401
Ambiguous injected class name is not an error
What I read in the C++ standard about injected class names contradicts (as I see it) with the behavior of a sample program I will present shortly. Here's what I read: From 3.4 (paragraph 3) The injected-class-name of a class (clause 9) is also considered to be a member of that class for the purposes of name hiding ...
I found it! It's right there in the standard! I was right! It should be ambiguous! Clause 14.6.1 Paragraph A lookup that finds an injected-class-name (10.2) can result in an ambiguity in certain cases (for example, if it is found in more than one base class). If all of the injected-class-names that are found re...
7,025,169
7,025,663
template compilation of friend functions
I'm trying the example from http://www.acims.arizona.edu/PUBLICATIONS/PDF/RajnikanthTemplates04.pdf. But receiving compilation errors such as '~' : 'friend' not permitted on data declarations. Can anyone provide more details?
Watch out. That code has lots of problems. Here is corrected version that compiled fine using c++ 4.3 : #include<iostream> #include<vector> using std::cin; using std::cout; using std::vector; using std::endl; const int ROWS = 2; const int COLS = 2; template<class T> class matrix { public: //declare a vector...
7,025,477
7,025,504
What does object file look like
As i know .c source goes to assembly then it goes to object file, object files then are linking to each other(and to libraries) and we get application we can run from os. But what does object file look like? Does it look like .asm or more like .exe? How are instructions inside object file stored? As "mov add call" pseu...
Machine code. You can use gcc -S to get assembly and gcc -c to get object files.
7,025,532
7,026,165
v8 extension for node.js - cannot set FunctionTemplate to target
I'm just starting out with writing a binding to a C library (link-grammar, to be precise) via a v8 extension (following instructions on Node.JS docs and v8 API docs). My problem is that I am getting the following build error: /usr/include/v8.h: In constructor âv8::Handle<T>::Handle(v8::Handle<S>) [with S = v8::Function...
The Set method expects a Handle<Value>, but you are passing a FunctionTemplate, which can't convert itself automatically. You need to be use GetFunction on the template to get a value handle for it. target->Set(String::New("parse"), FunctionTemplate::New(v8parse)->GetFunction()); However, there is a macro for this, so...
7,025,593
7,059,168
How to use functions defined in a C++-produced .dll or .lib file within Lazarus (freepascal)?
I want to use functions from the 'ANN' library (Approximate Nearest Neighbor) in my Lazarus code. This application is written in C++, and comes with source code. How can I access the functions from within Lazarus/FreePascal? Edit: Lazarus/FPC is similar to Delphi.
It depends on the library. If it is the "C" subset of C++, or if the interface is specially crafted to be interoperable, see opc0de's answer. An important signal that this is the case is an "extern C {}" block. If the library is true C++, you have a problem. There is no universal exporting mechanism for C++, and even t...
7,025,744
7,025,855
sorting a vector on its element's feature
First, I would like to thank people for having helped me so far. You are great!!!!! (if only you knew it) typedef template<class T>struct { T homepet_; T wildpet_; }Animal; std::vector<Animal> va; std::sort(va.begin(),va.end(),Pred<std::string>(sort_based_on_bool_and_arg)); I would like Pred(sort_based_on_bool...
I believe you need something along these lines: struct functor { inline bool operator()(const Animal& a, const Animal& b) const { return (does a come before b); } }; typedef std::vector<Animal> va; va list; std::sort(list.begin(), list.end(), functor()); //call operator() on functor
7,025,840
7,025,916
Will equal type_info addresses mean equal types?
I'm micro-optimizing code for identifying object types. I assume I can use the following for checking whether two objects instantiated in the same module have identical types: SomeCommonBase& first = ...; SomeCommonBase& second = ...; const type_info& firstInfo = typeid( first ); const type_info& secondInfo = typeid( s...
Obviously. Equal addresses mean that both pointers refer to the same object in memory. If the pointer is of type type_info*, then obviously it means the objects (i.e first and second in your case) passed to typeid() are of same type. After all, how can two pointers having same address, might refer to the different typ...
7,025,862
7,025,886
Why does the inclusion of an unused bool affect the reference of a char?
This code... #include <iostream> int main(int argc, char * argv[]) { char c = 'A'; std::cout << &c; return 0; } ...correctly outputs "A" both in Eclipse debug mode and on the command line. However when I modify the code to... #include <iostream> int main(int argc, char * argv[]) { char c = 'A'; b...
In the first version you are getting (un)lucky. In the second one you are getting (un)lucky (that it does not crash) but it prints more garbage. When you use & on a char object you get a char*. When you try and stream a char* it acts differently to all other pointers (which normally prints the address). But a char* is ...
7,026,129
7,026,311
How will I add multiple textures without glaux?
there's a problem which I don't know how to solve. I know how to get multiple textures in my 3D openGL and MVC++ 2010 game but the way is extremely slow. The more textures I load the more the game gets slower. It has been 2 weeks since I got stuck with this. I searched many sites but none of them helped me. I don't wan...
It might not be a good idea to load and destroy all textures every frame? Definitely not a good idea and surely the cause of your performance drop! That's what texture objects are for (the IDs you get from glGenTextures). These are handles to the textures in video memory. So you load all your textures at start, then ju...
7,026,347
7,026,494
dynamic_bitset, crash my program
I'm new with boost. I have a program which uses dynamic_bitset inside a lambda function. After I try to run the program, I get this message. This message appears even without the function that initializes the bitset and the functions that handle it. Does anybody know what this message means and what might be the proble...
Probably the dynamic_bitset variable that you are referencing in the lambda has gone out of scope and has already been destroyed, or something similar. (Without the source code it's difficult to be more specific)
7,026,350
7,026,414
What's char* const argv[]?
I'm studying linux C++ programing when I see int execve(const char *path, char *const argv[], char *const envp[]); I don't understand what is char *const argv[] . I know char *const foo is a const pointer to char. And const char *foo is a pointer to a const char. But what's char *const argv[]? Is...
Is it an array of const pointers to char or an array of pointers to const char? Read types right to left: const always binds to the left (unless it is on the very left) char *const argv[] ^^ Array of ^^^^^ const ^ pointer to ^^^^ char An array of "const po...
7,026,475
7,026,575
Template classes with specialised constructors
Consider the following contrived example of a templated array definition: template <typename t, unsigned int n> class TBase { protected: t m_Data[n]; //... }; template <typename t, unsigned int n> class TDerived : public TBase<t, n> { TDerived() { } }; I can specialize this type to provide a non-...
I think deriving your class from a base class is not relevant to the question here, that's a mere implementation detail. What you really seem to be after is if there's a way to partially specialize member functions, like the constructor. Do you want something like this? template <typename T, int N> class Foo { Foo(...
7,026,542
7,026,988
Interaction between runtime and fusion sequences
Further to my question C++ Tuple of Boost.Range - get Tuple of element types? I have the following: TupleOfRanges ranges; TupleOfElements elements; std::vector<int> offsets; All containers (both meta and runtime) are of size N. I would like to write code that does the following: boost::fusion::at_c<0>(elements) ...
You can obtain a sequence of ascending non-type template parameters with boost::mpl::range_c. You will need to copy this sequence to another mpl::sequence as ranges don't fulfil all necessary concept requirements to be used with transform. The sequence can be adapted with fusion.
7,026,707
7,026,858
syntax highlighting for files without extensions
I am working an some library headers that do not have a .h or .hpp extension. Visual Studio does not give me syntax highlighting and other features for those files. Is there any way to turn them on?
Found it. In the German version of Visual Studio, the option can be found under "Extras / Optionen /Text-Editor / Dateierweiterung / [x] Dateien ohne Erweiterung zuordnen zu: Microsoft Visual C++".
7,026,733
7,027,371
Can/should i inherit from a Boost.Fusion sequence?
Can/should i inherit from a Fusion sequence to implement my own sequence class? If no, why not? For example: typedef boost::fusion::vector< std::vector<const char*>, int, double > MyVector; class MyVectorWithData : public MyVector { public: MyVectorWithData(int i); // Constructor does some initializa...
Like standard containers, Fusion containers do not provide a virtual destructor, so the same arguments against extending them hold. In addition to that, in my experience, template metaprogramming and inheritance does not combine seamlessly. The main problem is that base classes are not considered to select template spe...
7,027,025
7,027,066
overloading inserters and strange output(for '20' and '020')
i was learning to overload '<<' in a very simple program,& during my study,i found the following surprising output of my program. #include<iostream> #include<conio.h> #include<string> using namespace std; class student { int age; public: student(){} student(int a){age=a;} friend ostream &operator<<(ostream &strea...
0 is the octal prefix for C++ integer literals and 20 in octal is 16 in decimal. To explain further: If a literal starts with 0 the rest of the number will be interpreted to be in octal representation. In your example 2*8^1 + 0 * 8^0. The syntax for integer literals is given in §2.14.2 in the most recent standard draft...
7,027,142
11,087,420
How does the opencl command queue work, and what can I ask of it
I'm working on an algorithm that does prettymuch the same operation a bunch of times. Since the operation consists of some linear algebra(BLAS), I thourght I would try using the GPU for this. I've writen my kernel and started pushing kernels on the command queue. Since I don't wanna wait after each call I figures I wo...
First, you shouldn't wait for an event from a previous kernel unless the next kernel has data dependencies on that previous kernel. Device utilization (normally) depends on there always being something ready-to-go in the queue. Only wait for an event when you need to wait for an event. "does all of this get pushed to ...
7,027,147
7,027,255
Tracking memory leak
The situation: I see around + 120kbytes increase when closing the class, so when i close the clas few times memory increases - and i need to find out what is causing this. Just looking for any good tip or trick of how to find out what is not freed/released with vstudio 2010 - any ideas? Here's more clearly what i do ( ...
The most straight forward method is to use the Windows API functions for memory usage tracking, like _CrtDumpMemoryLeaks. Using this in conjunction with _CrtMemCheckpoint can prove to be vital when tracking down stubborn leaks. If you are using MFC, you can optionally define DEBUG_NEW, which adds additional tracking to...
7,027,150
7,027,222
What is the difference between long long and long int
I know the difference between long and int But What is the difference between "long long" and "long int"
There are several shorthands for built-in types. short is (signed) short int long is (signed) long int long long is (signed) long long int. On many systems, short is 16-bit, long is 32-bit and long long is 64-bit. However, keep in mind that the standard only requires sizeof(char) == 1 sizeof(char) <= sizeof(short) <...
7,027,523
7,027,695
What can I do with a moved-from object?
Does the standard define precisely what I can do with an object once it has been moved from? I used to think that all you can do with a moved-from object is do destruct it, but that would not be sufficient. For example, take the function template swap as defined in the standard library: template <typename T> void swap(...
Moved-from objects exist in an unspecified, but valid, state. That suggests that whilst the object might not be capable of doing much anymore, all of its member functions should still exhibit defined behaviour — including operator= — and all its members in a defined state- and it still requires destruction. The Standar...
7,027,922
7,027,991
int(int, int) style template function type syntax
I remember that when using Boost.Spirit and for the std::function addition to C++0x, you specify the function type by using a syntax that doesn't use pointers, like in defining std::function<bool(int)> fn, whereas you would cast a pointer like (bool(*)(int))fn. Can anyone tell me the name of this new syntax or any refe...
bool(int) is the type of the function; bool(*)(int) is the type of the function pointer. In other words, if you define typedef bool(BF)(int); typedef bool(pBF*)(int); then BF* is the same as pBF. The std::function template captures the return and argument types via (variadic) templates: template <typename R, typename ...
7,028,124
7,028,234
shared object error when using binary on different machine
How can I avoid this? I have a pretty simple c++ program compiled on a ubuntu box. When I move it over to red hat and try to execute it I get an error something like: cannot find shared object stdlibc++5.so How does commercial software get around this, the stdlib installed on users machines is going to vary a lot. Is ...
I think you need to recompile it again because: OS is different [Ubuntu and Red Hat] The location of libraries might be different. Also there are chances (though very minute) that stdc++ library is not present at all. In commercial software employing compiled languages like C/C++ , the applications are deployed on t...
7,028,174
7,028,721
const-correctness and the safe bool idiom
I have another question related to the safe bool idiom: typedef void (Testable::*bool_type)() const; // const necessary? void this_type_does_not_support_comparisons() const {} // const necessary? operator bool_type() const { return ok_ ? &Testable::this_type_does_not_support_comparisons : 0; } How c...
The "safe bool idiom" is the technical answer to the question "i want a vehicle that is both sports car and tractor, and maybe a boat". The practical answer is not the technical answer… That said, the problem it solves is just to give a result that is convertible to bool but not to much of anything else (otherwise an i...
7,028,304
7,028,381
Error LNK2019 when using GetFileVersionInfoSize()
I just included this bit in my already working code, but I am getting an LNK2019 error. I'll paste the error after pasting the code. The Class CAboutDlg has: public: CStatic m_VersionInfoCtrl; virtual BOOL OnInitDialog(); }; The Function itself: BOOL CAboutDlg::OnInitDialog() { CDialog::OnInitDialog(); ...
You need to link against the library that contains the two functions VerQueryValue and GetFileVersionInfo - the linker doesn't know by default where to find them. A quick search for the two functions on MSDN suggests that they're both in the system library version.dll and the library you want to link against is version...
7,028,494
7,028,791
Accessing the the coordinates in a QPushbutton clicked slot
I have a QPushButton with an image that has two areas that I want to handle differently when clicked. Due to the positioning on the image, I cannot really use separate buttons for the two images. What I'd like to do is, in the slot where I am handling the click, have it check the coordinates of the click to determine ...
This is what first comes to mind. It should work, although there may be a simpler way: Create your own class that derives from QPushButton. Override the necessary mouse events (mousePressEvent and mouseReleaseEvent) and, before calling the base class implementation, set a property in your object using setProperty with...
7,028,590
7,028,617
`cd` into another directory and do stuff in there
Using the Windows API, how can I cd into a directory I just created such that all new files I create will be added to that directory?
SetCurrentDirectory
7,028,591
7,028,788
Binding the parameters before setting the function pointer?
I would like to try something out and unify some boilerplate code in one of our dynamic library API wrappers. Essentially, I would like to do the following: typedef bool (*MyFPtrT)(long id, std::string const& name); typedef boost::function<bool (long id, std::string const& name)> MyFObjT; ... ... MyFPtrT pDllFun = N...
I don't think it can be done directly like that, because bind creates a new object that takes the function object and the arguments by reference, and you can't rebind references. However, you can easily enough write your own templated functor wrapper with a reassignable function pointer: template <typename R, typename ...
7,028,666
7,028,747
Change the icon in About Box
Could you tell me as to how do I change the default image that is displayed in an About Box? The one that comes default with MFC as three boxes. I would want to change that to my present icon that I have created using MFC. My icon works but I just need to change the picture/image in my About Box. Thanks for your prompt...
A typical MFC application has the About dialog as part of the resource file that can be edited in the WYSIWYG editor. Open your projects .rc file, and click on the About Box dialog (the default IDD is IDD_ABOUTBOX). Right click on the Icon and select properties. From there you can change the icon that is used. Usua...
7,029,598
7,030,836
Are there any browser-based multi-player capable libraries for C++?
I've made a bunch of games from my own homegrown C++/DirectX 2D engine. I was thinking some of them would be more fun with the introduction of multi-player and at the very least it would be easier to distribute them and get people to play if they could run in a browser. I'm looking to port my games into a web format an...
The short answer is no. C++ requires the code to be compiled into a binary executable, and for various reasons, such code is not allowed to be run in the browser. The long answer: The native client by Chromium/Google allows you to write native C++ code and run it in the browser. However, support is very limited, in t...