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,731,021
7,731,152
C++ (gcc): undefined reference to `Stack<int>::Stack(int)'
Possible Duplicate: Why can templates only be implemented in the header file? I've struggled with this for a while, and I've taken a look to several questions here, but being new to C++ I haven't been able to understand where I am wrong. Here is the code, I took it from this page and tried to make it work, but so fa...
You can only have a template class definition in a cpp file if it's a specialized definition - i.e. you know what T is. Other than that, and your case belongs here, all definitions of your template class have to go in the header file. The compiler has to know about these each time a new instance is declared or defined ...
7,731,546
7,731,883
Side Scroller in C++
I'm looking at creating a basic side-scroller using OpenGL and C++, however I'm having trouble tackling a few basic conceptual issues, namely: Dividing the window into easy "blocks" (some sort of grid system). On what level would I want to do this? (The OpenGL viewport size, or through some abstraction that ensures wo...
Usually, it isn't the window (ie. viewport) which is divided into a grid but rather the "gameplay area". Pick a good size according to the style of your art (something like 64px - you might want to select a size that is a power of two for technical reasons) and create tiles of that size for your game (stored and loaded...
7,731,634
7,731,659
Change property access based on template argument
I have a base class that is a template that looks like this: template <typename T> class Foo { public: T bar; }; What I'd like to do is introduce a template argument that can be used to control the access mode of the member bar. Something like this: template <typename T,bool publicBar=true> class Foo { public: ...
This can be done using partial template specialization: template <typename T,bool publicBar> class Foo { }; template <typename T> class Foo<T,true> { public: T bar; }; template <typename T> class Foo<T,false> { protected: T bar; }; The only gotcha here is that you would need to replicate the entire class f...
7,731,648
7,731,663
Using auto and decltype in templated functions
I've been trying to use auto return type templates and am having trouble. I want to create a function that accepts an STL map and returns a reference to an index in the map. What am I missing from this code to make it compile correctly? (Note: I'm assuming the map can be initialized with an integer assignment of 0. I w...
Add typename before MapType in the suffix return type declaration. If you forget to add the typename you would get such kind of error (here GCC 4.6.0) : test.cpp:2:28: error: expected type-specifier test.cpp:2:28: error: expected initializer That would give you something like : template <typename MapType> auto FindOrI...
7,731,671
7,732,080
Converting Matlab to C++
I need to convert some MATLAB code to C++. I am using Visual Studio 2010 and have MATLAB compiler installed. I am wondering how do I go about doing this. Also when I publish my project will the end user have to install anything by MATLAB? (this cannot be the case)
You can compile Matlab scripts into standalone executables, but I'm not familiar with a Matlab tool to convert Matlab code to Visual C++ code. You can convert Matlab code to C or C++ using Simulink Coder (formerly Real-Time Workshop), which is available from Mathworks as a separate product. To run the standalone execut...
7,732,303
7,732,378
C++ comparison and decreasing variables
if(y-- > 0 && matriz[x][y--]!=9 && matriz[x][y--]!=0) When i'm doing this, my variable y is not decremented, right? And i can do this comparison y-- > 0? Imagine that i have y=0, i want to compare if -1 > 0. Thanks
Assuming all tests pass, your code is effectively equivalent to this: if (y > 0) { y--; // post-decrement if (matriz[x][y] != 9) { y--; // post-decrement if (matriz[x][y] != 0) { y--; // post-decrement // all true } } } If any fail, you still d...
7,732,653
7,732,873
List structure for c++ game
I'm making a very very basic game in C++ to gain some experience in the language and I have hit a bit of a brick wall in terms of progress. My problem is, while I was designing a class for the player's weapons, I realized I required a list, as I will only have a certain number of weapons throughout the game. So I ask y...
I would use the standard implementation (std::list<Item*>) because it's easy to use ("out of the box") and, out of the standard containers, it seems to be most suitable: You probably need support for fast adding/deleting of weapons (so no std::vector or C arrays) You probably don't need support for fast searching of t...
7,732,726
7,808,675
Bad file descriptor closing Boost socket
I'm using Boost 1.45 ASIO to handle some socket connections in an application that runs on both Windows and Mac. On Windows, the following code does not cause any errors, and my sockets are closed cleanly. On Mac though, both the shutdown and (if I comment it out) the close functions give me "Bad file descriptor" err...
if(socket.is_open()) { socket.shutdown(socket.both); socket.close(); } Unless you have a good reason for doing this, I suggest letting the socket::~socket() destructor close the underlying native file descriptor. If you are concerned about leaking descriptors, use a tool like valgrind to analyze your program.
7,732,755
7,745,953
Function parameter duplicating another parameter's pointer address accidently?
Today I've run across a rather strange error. Essentially what is happening is inside the function foo the first parameter is being set to the pointer value of the pointer crosssegments. So say crosssegments is location at 0x0045 then iMeaninglessdata will be set at 0x0045. If I take out iMeaninglessData and simply hav...
Turns out it is a bug in the visual studio 2008 debugger when used with release mode versus debug mode. I'm generating the PDB file, but apparently until you use the value, such as in a command window, it doesn't correctly locate the pointer for the variable.
7,732,798
7,732,824
C++, Invalid conversion from ‘char’ to ‘const char*’
In C++ I have this program: #include <iostream> using namespace std; int main(){ string expression_input; cout << "User Input: " << endl; getline(cin, expression_input); expression_input.insert(0, '('); //error happens here. expression_input.append(')'); } I am getting the following error: prog.c...
The error message tells you everything you need to know - you're trying to pass a char parameter where a const char * is required. You just need to change: expression_input.insert(0,'('); expression_input.append(')'); to: expression_input.insert(0,"("); expression_input.append(")");
7,733,113
7,733,149
accessing map elements increase it's allocated memory size
I have a map<vector<double>,double> element in my code named EU. I have noticed that the memory usage by my code tends to accumulate until I have used the entire available memory on my machine (going from ~200 MB to ~ 4GB). commenting out stuff in my code I have come to the conclusion that a line that access an elemen...
When you access an element in a std::map, if the index has no associate value then a new element is created. So each time you access the map with a new key a new node is created to hold both the new std::vector< double > key and double value.
7,733,197
7,733,228
Include std library in header or cpp?
If I have a class A which uses iostream, should I put the include statement of iostream in A.h or A.cpp?
This is an area of some controversy. My own preference is that each header should be able to stand alone, so if it needs other headers, it includes them. In other words, if client code is going to need to include <iostream> (or whatever) anyway, your header should handle that for them. OTOH, if the user of the iostream...
7,733,582
7,733,598
Value not being increased after addition statement?
I have two functions where I'm adding random numbers to the total value. The problem is that every time I call the function and print the total, it does not add. If it generates 2 it will say the total is 2. After that if I call it again and it generates 5, it says the total is 5, and doesn't add (it should be 7 if th...
You are modifying the value of the internal copy of the argument passed to the functions. If you want the change to be done on the external variable, change your function definitions to take references instead: int& score. Also note that rand() % 7 will give you a value in the range [0, 6]. A dice has values in the ran...
7,733,634
7,733,651
Simplifying if else user input validation
This gets the job done for what I need it to do, but I am wondering if there is an easier/more efficient way of accomplishing the same thing. The user inputs two numbers and they need to be between 0 and 50, if it doesnt fall within the required range it ends the prog cout << "Enter the pixel coordinate (x, y): "; cin...
cout << "Enter the pixel coordinate (x, y): "; cin >> usrInput1 >> userInput2; if ( (usrInput1 > 50) || (usrInput1 < 0) || (usrInput2 > 50) || (usrInput2 < 0) ) { cout << "ERROR!" << endl; return 0; } cout << "Success" << endl; xvar = usrInput1 + usrInput2; You could actually combine it further if you ...
7,733,667
7,733,675
How can I limit my printf statement to 80 characters per line in the code in c++?
My professor requests that my code does not exceed 80 characters per line, but I have some printf statements that exceed this limit. Is there a way to break this statement into two or more lines without changing the output? Example by request: printf("\n%-20s %-4d %-20s %-4d %-20s %-4d\n%-20s %-4d %-20s %-4d%-20s %-4d\...
In C++, you can break literal strings like this: printf("This is a very long line. It has two sentences.\n"); into printf("This is a very long line. " "It has two sentences.\n"); Any double-quoted strings that are separated by only whitespace, are coalesced into one string by the compiler before parsing. The r...
7,733,688
7,733,757
Libcurl sample code come up with error
Hi I'm very new to libcurl and I want to essentially get the source code from a website into a string so I can extract data from there using simple functions in visual C++. This is the code I'm using (taken from the curl site, sample section): #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/c...
first error, change mem->memory = realloc(mem->memory, mem->size + realsize + 1); to mem->memory = (char *) realloc(mem->memory, mem->size + realsize + 1); second error, change chunk.memory = malloc(1); /* will be grown as needed by the realloc above */ to chunk.memory = (char *) malloc(1); /* will be grown as nee...
7,733,691
7,733,775
How to create target for makefile
Hello: g++ Hello.cc dep.o -o Hello dep.o: dep.cc dep.h g++ -c dep.cc I am trying out this makefile,but I want the target to be "make Hello". How should I modify my makefile? It work when I typed "make".
You need to add all the dependencies, recursively: Hello: Hello.cc dep.o g++ -o $@ $+ dep.o: dep.cc dep.h g++ -c -o $@ $< It would probably be better to add a separate compilation stage for Hello.o, but I'll stick with the format prescribed by the question. You should probably also add $(CXXFLAGS) and...
7,734,001
7,734,026
Use a polymorphed subclass's respective methods
I'm having an issue with the wrong method being called. In my program, I have 3 classes: symbol, nonTerminal, and terminal. nonTerminal and terminal are both subclasses of symbol. In my program, I only ever create a terminal or nonTerminal. Here are some condensed versions of each class: #ifndef SYMBOL_H #define SYM...
Your function addFirst is receiving your object by value. What this means is that: Every time you call addFirst() a new symbol object is created and copied from existing terminal or nonTerminal. Whenever said copy occurs, the resulting object is neither terminal nor nonTerminal, but their base class - symbol. To coun...
7,734,045
7,734,210
C++ Blowfish Hashing Implementation
A number of scripting languages (Python/PHP/etc...) include functionality (sometimes through extensions) that allows you to use Blowfish as a one way hash on passwords. I'm trying to find a similar implementation for C++ but everything I've come across is an encryption/decryption solution. Can somebody recommend a l...
There's a java version at jbcrypt. There's a paper on bcrypt at openbsd.org and microsoft. You can find the source for bcrypt at http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/crypt/ and more info at http://www.openwall.com/crypt/
7,734,242
7,734,383
Homework: Avoiding magic numbers
For my c++ homework assignment, I have to write a Tic-Tac-Toe Win32 console application. I've created a grid on the screen using a coordinate system and I use _getch() and SetConsoleCursorPosition(...) to move the cursor around when the user presses the arrow keys and to draw an X or and O when the users presses one of...
it's all relative to your initial settings they could look like: const int CELLWIDTH = 1; // how big one cell is (space in it) const int BORDERWIDTH = 1; // width of the border const int GAMESIZE = 5; // size of game field like 5x5 const int CELLSIZE = CELLWIDTH + BORDERWIDTH; const int MAXOFFSET = GAMESI...
7,734,265
7,734,827
Why does my program freeze in the middle of a pipe read?
I'm writing a C++ program for class that requires a set of N child processes to communicate with their parent process on a Unix-based system. To that end, I declared two arrays of N pipes, one for each direction of communication, before forking the process: int pipesToParent[N][2]; int pipesToChild[N][2]; ... // for i...
Seems like deadlock to me - both your processes are waiting for another one to write something - but none of them actually writes anything, so everything stops. Make sure that your comunication design is deadlock-free (eg. clients reding conantly and writing only on reading READY comunicate, and server reading only ft...
7,734,346
7,734,400
error: cannot convert Elem to Elem* for argument 1 to void addHead(Elem*, Elem*)
I am compiling my code with g++ -g and I am getting the error message in the title. The error is related to a function I have made, it's signature being: void addHead( Elem *&start , Elem *newStart ); and I am passing this function these two variables: Elem * head; Elem * tempEl; so that it looks like this: addHe...
It's being pretty specific: You're passing an Elem, but it takes an Elem*. In particular, head is of type Elem*, but you are passing *head: of type Elem. Also, your definition signature doesn't match your definition, so even when you fix the call, you will get a linker error when it can't find addHead(Elem*, Elem*). De...
7,734,390
7,734,438
Overload an operator taking pointers in parameter
I am trying to overload the '>' operator taking a pointer in parameter, however I get an error saying "operator > must have at least one parameter of type class". I do not get that error if I do not use pointer. Note: S1 is a typedef'd structure, as well as elem. bool operator>(S1 const *V1, S1 const *V2){ if (V1->...
The compiler will want to turn your example into comparing the two pointer values. Having one parameter as a class type will tell it what it needs to know to resolve the overload. bool operator>(const S1& V1, const S1& V2){ if (V1.elem->code > V2.elem->code) return true; return false; } S1 * funct(S1...
7,734,452
7,734,545
C++: no matching function call for constructor?
Here is the declaration of the constructor I'm using: _Task Multiplier { int **Z; int **X; int **Y; int xr, xcols_yrows, yc; void main() { for( int i = 0; i < xcols_yrows; i++ ) { matrixmultiply(Z, X, xr, i, Y, yc); } } public: Multiplier( int *Z[], int *X[], i...
The problem is that the function parameters X, Y and Z basically expect a array of pointers to int, but you're giving it a pointer to an array of arrays of int. Specifying a parameter as an array (declared with []) decays to declaring a parameter as a pointer. And this is ok, as an array variable can be basically treat...
7,734,486
7,734,525
priority queue in stl
I followed the article to code a hanffman coding method using stl's priority_queue, however I think there are some bugs in the final code or it's not updated. The main problem is the declaration of the priority_queue, I believe it should take three parameters like: priority_queue< node, vector, greater > q, instead of ...
You need to define an operator>() for your class because you are using std::greater<> as the comparison in the priority_queue. The only operator I saw in the code was operator<().
7,734,564
7,734,638
Server supporting multiple clients with listen maybe?
I was writing a simple server, just for fun and I realized that the third step meaning calling the listen(...) function takes two arguments. The second one being the backlog. While I don't fully understand the meaning of this argument but I think it queues up the clients. So assuming I'm right I was wondering how the ...
Yes you are right - backlog is the supposed queue of possible connections (AFAIK it is ignored on Linux) After you create a listening socket you call accept() on it and assuming your socket is blocking - the accept call shall not return until it pull the first client request off the queue. So you can do something like ...
7,734,609
7,734,660
using stringstream to print a rounded floating point number
i have floating point variables "lmin" and "lmax". i wish to display only 4 significant digits. i am currently using something i have found online of the form ... string textout; stringstream ss; ss << lmin; textout = ss.str(); output(-0.5, -0.875, textout); ss.str(""); ss << lmax; textout = ss.str(); output(0.2, -0....
Use std::setprecision to specify the number of digits after the decimal point. #include <sstream> #include <iostream> #include <iomanip> int main() { double d = 12.3456789; std::stringstream ss; ss << std::fixed << std::setprecision( 4 ) << d; std::cout << ss.str() << std::endl; } Output: 12.3457
7,734,944
7,734,966
Declaring a vector of pointers to vector of strings
I have a 2D table of strings (using STL vector) and am trying to modify so that the table is a vector of pointers to vectors of strings. I know that this will require changing the constructor so that rows are created dynamically, and pointers to the rows are inserted into the table, but I'm not sure how to go about cre...
It looks like you are trying to create some form of multidimensional vector. Have you considered using boost? http://www.boost.org/doc/libs/1_47_0/libs/multi_array/doc/user.html
7,735,108
7,735,130
Function pointer as non-type template parameter
I'm currently porting GTK+ to a dynamic language, one of the challenge is to convert GTK+ functions to language bindings. I attempt to use C++ templates to simplify it. For example, to convert 'gtk_widget_show_all' to dynamic language's 'show_all', I first define following generic function: template<class Type, class G...
You can define a number of overloads, based on the number of arguments, like this: template<class Type, class GtkType, class ReturnType, ReturnType function ()> static Handle<Value> SimpleMethod (const Arguments& args) { ... } template<class Type, class GtkType, class ReturnType, class Arg0, ReturnType function( A...
7,735,203
7,739,818
Setting separate material properties for different objects in OpenGL
How can I have separate material properties for different objects drawn in OpenGL? I did the following code, which apparently only shows the later colour: //************** Object 1 ************** glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glColor4f(149.0/255.0, 78.0/255.0, 22.0/255....
First, your example code looks reasonable and your objects should indeed have different materials. But keep in mind that you only change the diffuse material color for your second object, as you set exactly the same specular colors and shininess values for both objects. And the ambient of the second object is also the ...
7,735,241
7,735,251
String reverse error
Can anyone explain to me why im getting a ".exe has encountered a problem and needs close"error, it compiles and works sometimes when i fiddle with the char array, but when it does work i sometimes get strange characters at the end of the string. #include <iostream> using namespace std; char* StrReverse3(char*); ch...
You are not initializing p. It's an uninitialized pointer that you are writing to. Since you are writing this in C++, not C, I'd suggest using std::string and std::reverse: #include <string> #include <algorithm> #include <iostream> int main() { std::string str = "Saw my reflection in snow covered hills"; std:...
7,735,332
7,735,346
Are pointers private in OpenMP parallel sections?
I've added OpenMP to an existing code base in order to parallelize a for loop. Several variables are created inside the scope of the parallel for region, including a pointer: #pragma omp parallel for for (int i = 0; i < n; i++){ [....] Model *lm; lm->myfunc(); lm->anotherfunc(); [....] } In the re...
Yes, all variables declared inside the OpenMP region are private. This includes pointers. Each thread will have its own copy of the pointer. It lets you do stuff like this: int threads = 8; int size_per_thread = 10000000; int *ptr = new int[size_per_thread * threads]; #pragma omp parallel num_threads(threads) { ...
7,735,451
7,735,661
How do I compile a dll with R and RCPP?
I have written a .cpp file and I want to compile it to a .dll for use with R and RCPP. (without using the inline package). I am using WinXP and R 2.13.2 and RCPP 0.9.7. I am using Rtools 2.14. How do I include Rcpp.h in minGW's search path? I underastand that the files that I need to include are in C:\Program Files\R\...
A couple of quick points: The gcc and g++ compilers from MinGW behave just like other compilers from the gcc family. That means there is no 'add to search path': you use the -I/some/dir switch to add that path and directory. Similarly, -L/some/lib adds that directory to the linker path. You really want to use a Makefi...
7,735,526
7,765,066
Compilation Error due to InCorrect Direct X Version
I got the Sample Project for video capture from video Camera. I was trying to compiling it. I am Using windows 7 and vs 2008. I got following compilation error. 1>------ Build started: Project: VidCap, Configuration: Debug Unicode Win32 ------ 1>Compiling... 1>cl : Command line warning D9035 : option 'Wp64' has been de...
Problem is solved Direct X9 Version is needed here which contains stream.h
7,735,542
7,735,556
Destructor for multiple constructors
I have two constructors in C++ and one destructor. When I use the first constructor for my object the destructor is called to delete A[] which is what I want, but when I used the second constructor I don't need to call destructor but C++ compiler calls it anyways which causes an error. What is the best way to solve thi...
Store a flag indicating whether the destructor should call delete or not. Note that you also need a user-defined copy constructor and copy assignment operator, when manually managing memory.
7,735,608
7,735,659
Convert system clock (microsecond) stored in int64_t to float(s)?
Currently I have a function, f(), which returns the current system clock in microseconds. I need to convert it to seconds, preserving several digits after the decimal point. I want to store the result in a float(is it long enough?). But what f() returns is a int64_t variable; I tried many methods, like: (double)(f() / ...
Your float has (assuming IEEE-754) 23 bits for the mantissa, how do you expect to store a 64-bit value in there without losing precision? (The value you showed needs 31 bits just to store whole seconds, your precision is only to the nearest 128 seconds)
7,735,945
7,736,011
Create dialog in windows services at vista+ system
I use CreateDialogParam to create a dialog in my service, it can run normally in XP system.But when I put it into Vista or Win7, it doesn't work. I want to know why or what else APIs I can use?
With session 0 isolation introduced in Vista, services cannot show UI since they run in a separate, non-interactive session. You need to run a standard app on the interactive desktop and use an IPC mechanism to communicate with the service in order to show UI on behalf of the service.
7,735,979
7,736,154
Fast Qt C++ compile on windows
I have a large project that uses the Qt framework and am trying to find the fastest way to compile it on my Windows install. On my linux machine at home I use 3 year old Linux Mint setup with a dual core (the machine is 3 years old not Linux Mint install), using: make -j2 both cores are used full(ish) and compiles the ...
The following have helped the speed of our Windows C++ Qt builds, over the years: Customised the settings on our anti-virus software, to exclude from scanning the locations of our Source code, object code, and all headers and libraries we are building against (Visual Studio, Qt etc). (There's a separate AV check that ...
7,736,391
7,736,409
printf changing the value while using %.22f
I have a issue with basic typecasting. #include<stdio.h> int main() { printf("%.22f",0.30); return 1; } The output I am getting is 0.2999999999999999888978 Why is 0.3 converted to a lesser value Any help much appreciated Nandish
This is because 0.30 cannot be exactly represented in binary floating-point. Internally, only an approximation to 0.30 can be stored. Therefore, when you print it all out, you'll get a slightly different number. http://en.wikipedia.org/wiki/Floating_point
7,736,505
7,736,546
C/C++ Linux: fastest write of a fixed chunk of memory to file (1 Hz)
On a Linux system, I have one 7MB chunk of memory of fixed size (no growth) whose contents I refresh in a real-time application. I need to write this chunk of memory to disk (same file) once per second. Taking into consideration modern (late 2011) CPUs and HDDs, what is the most efficient way to implement this function...
mmap(2) is the way to go. Just call msync(2) with MS_ASYNC when you want to write it.
7,736,618
7,736,721
Converting Japanese characters from wide characacter to multibyte using API WideChartoMultibyte gives '????'
In my MFC application I am reading Japanese characters from string table then converting it into multibyte using following code WCHAR wBuf[1024]; int rc; rc = LoadStringW(hInstance, iResourceID, wBuf, 1024); WideCharToMultiByte(1252, WC_COMPOSITECHECK, wBuf, -1, buf, 1024, NULL, NULL); But every Japanese charact...
Windows-1258 is the code page for Vietnamese text. Japanese cannot be expressed in the Vietnamese code page, so the output is mapped to question marks. The same goes for 1252, it's only for West European languages. In the case of 1200, that's not a real code page: according to MSDN, it's only available to managed appli...
7,736,659
7,736,744
BOOST ASIO - asynchronous sockets
I am trying to use BOOST ASIO library asynchronous sockets. My platform is Linux. My client sends data, which I am able to read at server side. For sending data second time, client has to connect again. Is there a way I can use asynchronous sockets and keep the connection alive till explicit disconnection. Details of m...
well in Handler::handleRead() you got to schedule the async_read_some() again
7,736,725
7,760,501
Vector print out wrong value
Hi I got a question about the following code. I will copy a char string, which i read out of a file into a vector and print out this vector on the screen. the program copy the string out ouf the textfile but the vector only gives out the last element of the vector. what did i wrong here?? : #include <fstream> #include ...
Your problem starts right at the top of the code string buffer; string dev_no; stringstream devss; char *reg_no_c = new char [buffer.length()+1]; char *start_reg_c = new char [buffer.length()+1]; char *adresse_c = new char [buffer.length()+1]; char *id_c = new char [buffer.length()+1]; char *zeit_c = new char [buffer.l...
7,736,768
7,736,998
function pointers and dll load order
I am using function pointers and LoadLibrary. Following is the my code. When I added EvtExportLog after _EvtSubscribe call, it started corrupting _EvtSubscribe values, If i added it before as done in following code everything works fine, now When I add another function pointer I am facing the same problem, anybody know...
This has nothing to do with DLL Load order, you're trashing the stack somewhere else, and it just happens that _EvtSubscribe is the victim depending on how you order the objects on the stack. The easiest way to trash the stack is if you were calling a function with the wrong signature, possibly by transcribing them by ...
7,736,891
7,829,807
Why code completion using CEDET in Emacs so slow?
I recently try KDevelop. It looks up for symbols (variables, function names, class, struct...) much faster (instantly) than semantic-complete-self-insert or M-Ret. Using M-Ret is faster, but it does not have nice format like other IDEs, instead the meaningless one like From nil >. In emacs, I must wait for at least ~1...
This simplest answer is likely that KDevelop's DUChain and parsers are written in (I presume) C++ with token management similarly built. CEDET's parsers are all in Emacs Lisp, and the databases and lookups are also in Emacs Lisp. While some tables are built and cached between calls to the completion engine in Emacs, ...
7,737,479
7,780,539
C++, Python, Incompatible Types of Numbers
I am having difficulty using the vector_indexing_suite in Boost. In C++ I have defined: class_<std::vector<double> >("PyVecDouble") .def(vector_indexing_suite<std::vector<double> >()); and class_<std::vector<long> >("PyVecLong") .def(vector_indexing_suite<std::vect...
The relationships between Numpy and C types is listed here (check the "compatible: C ..." sections): http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#built-in-scalar-types The size-specified types (int16 etc.) map to C int, long, long long etc. in a platform-specific way. numpy/ndarrayobject.h however defi...
7,738,005
7,740,118
Macro definition in C and C++
I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like: /* Flags for ds_flags */ #define DSF_OVER (1<<0) #define DSF_DISPLAY (1<<1) #define DSF_CALLFLOW (1<<2) I am not able to understand w...
Some times the position of the bits represent some bit operations like in your case: #define DSF_OVER (1<<0) is 1 #define DSF_DISPLAY (1<<1) is 2 #define DSF_CALLFLOW (1<<2) is 4 (This is not 3) If you were to add a new item later, you will do it as #define DSF_OVER 1 #define DSF_DISPLAY 2 ...
7,738,027
7,738,133
C++ start new process and terminate the current one under linux
This question has been asked several times here, but I can't find answer for the following situation: My program uses statically linked libraries, which open file handles, so, I'm unable to set FD_CLOEXEC on those file handles simply calling exec causes alot of errors in new process, because of unavailable file handles...
Closing all filedescriptors should be as simple as #include <unistd.h> for (i=getdtablesize();i>=0;--i) close(i); /* close all descriptors */ This is also a standard step during daemonizing, see e.g. http://www.enderunix.org/docs/eng/daemon.php
7,738,256
7,738,284
c++ class inheritance and operator overloading; do operator overloads get inherited?
Just a quick question, if I have a template class: template <typename T> class foo { public: bool operator!=(foo& other) const { //... } } And then I inherit said class: template <typename T> class bar : public foo<T> { //... } Does the operator overload get inherited? And if not, how would I go ...
Your operator definition isn't quite correct: bool operator!=(foo& other) const { //... } should be bool operator!=(const foo& other) const { //... } since you are trying to compare with a temporary, which can only be bound to a const reference.
7,738,314
7,738,356
compilation error with boost dynamic_bitset
I'm trying to use boost::dynamic_bitset, as shown below: #include <boost/dynamic_bitset.hpp> class Bitmap { public: Bitmap(std::size_t size = _size); void setBit(int pos); void clearBit(int pos); bool get(int pos); void resize(int size); private: boost::dynamic_bitset<> _bitset(8); static const std::siz...
The difference is that you are trying to initialize member variable, not "freestanding" one. Either run with -std=c++0x (see comment at end of post) or do: // in class definition: boost::dynamic_bitset<> _bitset; // in constructor: Bitmap(/* params */) : _bitset(8) { /* rest of code */ } Initializing members the way ...
7,738,593
8,898,601
boost::geometry multi_point can't be constructed like polygon
First off, a big thanks to the people behind the new boost::geometry library! This question replaces an earlier one which I have now split into two as two separate issues have become clearer. I have read http://www.boost.org/doc/libs/1_47_0/libs/geometry/doc/html/geometry/design.html which explains the traits mechanism...
This turned out to be a bug in boost. It is now fixed in the head revision and should roll out in 1.49.0.
7,738,721
7,755,792
is it valid to async send data before completion handler of the previous one was invoked?
I'm sending data asynchronously to TCP socket. Is it valid to send the next data piece before the previous one was reported as sent by completion handler? As I know it's not allowed when sending is done from different threads. In my case all sending are done from the same thread. Different modules of my client send dat...
Is it valid to send the next data piece before the previous one was reported as sent by completion handler? No it is not valid to interleave write operations. This is very clear in the documentation This operation is implemented in terms of zero or more calls to the stream's async_write_some function, and is kno...
7,738,755
7,803,428
Troubles with ::MoveWindow - leaving blank space
I am quite desperate to resolve this very annoying issue :( I am trying to display a child window on parent window. Some time the window need to be resized. But for some reason, when I using MoveWindow function it leaves blank space on the top of the parent window. I would like to present a picture here but I can not p...
The problem was WS_POPUP flag to the parent window. Very strange. As far as I know it was not suppose to have such an effect. Thanks for everyone!
7,738,840
7,739,009
c++ function template specialisation
Given this code: class X { public: template< typename T > void func( const T & v ); }; template<> void X::func< int >( const int & v ) { } template<> void X::func< char * >( const char * & v ) // 16 { } When I compile it I get the following error. test.cpp:16: error: template-id 'func<char*>' for 'void...
The reason you face this error is because you write const before the type. Although this is common practise, it is not conducive to understanding how const/volatile-qualifiers (cv-qualifier) work. In this case const T when T is char* doesn't mean const char*. It rather means char* const because T is char* and no matter...
7,738,848
7,739,127
C++: Any great difference in _implementation_ of the reference and the pointer
I caught that I use references not understanding how they really work (that's why I use them not so often). Pointer seem to be implemented simply somehow like: a simple WORD variable with address of some other variable. We copy it when we pass it as a parameter to function. And what happens when we pass reference as a ...
The two don't have as much in common as you'd think, really. A reference exists at a higher level of abstraction in the compiler. It doesn't need to generate any code at all. It is essentially an alias for an object, so whenever it is used, the compiler treats it as a use of the referenced object. Of course, sometimes,...
7,738,888
7,739,024
what is concept of Inline function and how it is differ from macro?
Possible Duplicate: c++ inline function? What is the the real concept of inline function. i really unable to understand the inline function. why & where should i use inline function? How it is differ from normal function? Edit: what is difference between macro & inline function?
The main language difference between an inline and a non-inline function is that inline functions are exempt from the one-definition rule, provided all definitions are the same. This is a crucial feature for C++, since it allows you to write member function definitions inside class definitions and still be able to incl...
7,738,981
7,739,082
Simple collision with .bmp's in an 2 dimensional array?
so I'm making a really simple program in which I want one sprite to collide with another. I made a 'level' by making a grid with images, using a two-dimensional array. How would I implement simple collision? I would appreciate coding examples, so I can actually see what's going on. Thanks. Here's the code: int pacmanPo...
if you calculate the position of the pacman to correspond to the landTitle array by dividing the pacmanPosX and pacmanPosY with the size of each square (32) and then cast it to an int. then you could simply check if the position in front of you is set to 1 or 0 in the landTile and in that way you can get a very simple ...
7,739,144
7,739,197
Thread safety for overloaded operator new
Though standard doesn't guarantee the thread-safety for new, most of the multi-threading operating systems support thread-safe operator new. I am implementing my own memory management for the dynamic allocation of certain class (say MyClass) in my code. For thread safety of MyClass, I may have to use pthread or boost::...
It is. However note that in C++11 new is thread safe. Of course, when you add thread unsafe code, it makes your operator new thread unsafe. Following your edit (which changed the whole question): The assumption that the compiler adds thread safety code around the new call is pretty wrong. Sane implementations will al...
7,739,235
7,739,514
Ubuntu - issue with opening a .txt file from terminal
I have built a .cpp program in order to write some content to a .txt file created within the .cpp file. I manage to write the desired content, however, when I am trying to open the created file from terminal, it says that it cannot find it although it is there. When I try to open it with vi or nano it's content it's em...
You are using strcat in a wrong way. I don't know if that's the cause of your problem, but it can result in undefined behavour; int main(int argc,char* argv[]) { fstream RawStipFile; RawStipFile.open(strcat(argv[1],".txt")); Here you modify argv[1]. You append 4 characters to it, without allocating any memory....
7,739,310
7,739,856
strings with the arrays
hello i have an struct like this: struct Student { string name,lettergrade; int stdnumber,*examgrades; double avarege; }; I have to make a programme which it calculates student's avarege and letter grades. I have to use this functions: void getdata(); double calcgrades(); void show(); void erase(); I have to ask use...
In your code k is an array of Student, not an array of Student*. So you need to use . instead of ->. That's why you get that error. Another issue with that code is that you're using a non-constant value for the array size, which is not allowed in C++. For dynamic allocation, the easiest solution would be to use std::v...
7,739,323
7,739,401
Freeing memory in caller or callee?
A function (Say "fun()") allocates memory and returns the pointer to allocated memory. How should I make sure I that this memory is released. I can't release it immediately in function "fun()" as it is returned to caller. And what if fun() is part of library? Whose responsibility it is to free memory. In case of fopen(...
The following is the answer for C, posted before the OP confessed to using C++. In that language, use RAII and smart pointers, as recommended by others. If a function returns allocated memory, then the caller is responsible for deallocation and this must be stated in the function's documentation. If more cleanup is ne...
7,739,453
7,739,725
C++ template working fine for GCC but showing compile time error in LLVM-GCC compiler
typedef char TCHAR; template <class T> class MyTemplateString { }; template <class T> class MyList { }; typedef MyTemplateString<TCHAR> MyString; MyList<MyString> outlist;// here it's showing compile time error The error is: Implicit instantiation of undefined template MyList <MyTemplateString<char>> Wor...
The code as posted above compiles fine here without any errors or warnings using both g++ and llvm-g++: $ g++ -Wall -c template.cpp $ llvm-g++ -Wall -c template.cpp Version info: $ g++ -v Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5666.3~123/src/configure --disable-checking ...
7,739,695
7,743,724
C++ library to handle eps/pdf
Do you know if a library exists under Win32 to handle EPS and PDF format files without installing Ghostview/ghostscript. (I'm currently using ImageMagick) Thanks...
ImageMagick is available for win32 as well. Link
7,739,877
7,739,946
Map two types at compile time
I have a set of types related with a one-to-one relation, for example: TypeA ---> Type1 TypeB ---> Type2 TypeC ---> Type3 I know these relation at compile time. Then, I have a template class that depends on this two types: template<class T1,class T2> class MyClass { T1 foo; T2 bar; }; Now, the user of my library...
template<class T> struct get_mapped; template<> struct get_mapped<TypeA>{ typedef Type1 type; }; // and so on.... template<class T> class MyClass{ typedef typename get_mapped<T>::type T2; T foo; T2 bar; };
7,739,983
7,741,032
EAI_NODATA and EAI_ADDRFAMILY undeclared (Linux OS)
Does anybody know why those constants fail to compile? I changed gcc and it looks that I have problems with some dev libraries. I was thinking to fix it with -DDEAI_ADDRFAMILY -DEAI_NODATA in the CCFLAGS. Does it ring a bell?
You are missing an include file #include <netdb.h>
7,740,031
7,740,296
Is it possible to print line-by-line on a network usb printer using Qt on windows?
The title says pretty much everything, I have to convert old com/serial-printer-port code to 'new flashy Qt code' that should work with a network usb printer. I have searched quite a lot and I can't find anything about how to print line-by-line (ie. when I send just one text line to the printer, it shouldn't print a wh...
This page documents the Windows APIs that can be used to send raw data to a printer: http://msdn.microsoft.com/en-us/library/windows/desktop/dd162959(v=vs.85).aspx This might be OK if you only want to print simple text. I don't know of a way to use the drawing capabilities of Windows to print less than a page.
7,740,056
7,740,564
Firebreath project with objective-c++
I need to incude some objective c code into my Firebreath project. The problem is that the project is in c++ lenguage. So I am trying with objective-c++ code. The plugin project name is "OpenOnDesktopPlugin", I renamed the "OpenOnDesktopPluginAPI.cpp" to "OpenOnDesktopPluginAPI.mm" and I created an objective-c class ca...
The source code file with the DistributedNotification class in it is not being linked. Make sure it is in your target's list of compiled files.
7,740,114
7,740,364
Map inserstion failure: can not overwrite first element?
static std::map <unsigned int, CPCSteps> bestKvariables; inline void copyKBestVar(MaxMinVarMap& vMaxMinAll, size_t& K, std::vector<unsigned int>& temp) { // copy top k variables and store in a vector. MaxMinVarMap::reverse_iterator iter1; size_t count; for (iter1 = vMaxMinAll.rbegin(), count = 0; iter1...
map::insert isn't supposed to update/overwrite anything, just insert not-yet-present elements. Use operator[] for updating, it also inserts elements when the specified key is not present yet.
7,740,139
7,740,557
Android - JNI NewObject() does not save values when passing it to Java
I am using native code to create an object which I then pass as an argument to a method I call. Nothing appears to go wrong in native code, but when I get the call in Java, the object seems to have nulled values. Here's the code of the java object I create in native: package org.test; import java.util.ArrayList; publ...
You're not passing the object you constructed to the method (or indeed doing anything with it). Instead of jenv->CallVoidMethod(clientHandle->job,mid); don't you want jenv->CallVoidMethod(clientHandle->job,mid,dataObject); ? Also you're not checking whether that call succeeded or not....
7,740,215
7,740,766
Improving the dll missing error message
I have a program written in QT that works just fine. However it has an indirect dependency on dnssd.dll since a dll loaded by the program uses bonjour. If bonjour is not installed on the machine running the program it will say The program can't start because dnssd.dll is missing from your computer. Try reinstalling ...
Set it to delay load, then as early as possible (before you cause loading to happen), try to load it yourself (with LoadLibrary) and report the problem. http://msdn.microsoft.com/en-us/library/151kt790.aspx
7,740,350
7,740,378
overloading postfix and prefix operators
please consider following code #include <iostream> using namespace std; class Digit { private: int m_digit; public: Digit(int ndigit=0){ m_digit=ndigit; } Digit& operator++();//prefix Digit& operator--(); //prefix Digit operator++(int); Digit operator--(i...
The pre- and post-increment are two distinct operators, and require separate overloads. C++ doesn't allow overloading solely on return type, so having different return types as in your example wouldn't be sufficient to disambiguate the two methods. The dummy argument is the mechanism that the designer of C++ chose for ...
7,740,434
7,740,482
Can function overhead slow down a program by a factor of 50x?
I have a code that I'm running for a project. It is O(N^2), where N is 200 for my case. There is an algorithm that turns this O(N^2) to O(N logN). This means that, with this new algorithm, it should be ~100 times faster. However, I'm only getting a factor of 2-fold increase (aka 2x faster). I'm trying to narrow down t...
Firstly, your interpretation that O(N logN) is ~100 times faster than O(N^2) for N=200 is incorrect. The big-Oh notation deals with upper bounds and behaviour in the limit, and doesn't account for any multiplicative constants in the complexity. Secondly, yes, on modern hardware function calls tend to be relatively expe...
7,740,692
7,747,612
Open yml file in opencv 1.0
I have a yml file and i want to open the file for reading using the existing opencv 1.0 functions. The file contains something like this: %YAML:1.0 Image file: "00961010.jpg" Contours count: 8 Contours: - Name: FO Count: 41 Closed: 0 Points: - x: 740.7766113281250000 y: 853.01245117187500...
You're going to want to look at the cvFileStorage data-structures, and functions. Here is an example from OpenCV to get you started: #include "cxcore.h" int main( int argc, char** argv ) { CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); CvStringHashNode* x_key = cvGetHashedNode( fs, ...
7,740,761
7,740,854
how do static variables inside functions work?
In the following code: int count(){ static int n(5); n = n + 1; return n; } the variable n is instantiated only once at the first call to the function. There should be a flag or something so it initialize the variable only once.. I tried to look on the generated assembly code from gcc, but didn't have any ...
This is, of course, compiler-specific. The reason you didn't see any checks in the generated assembly is that, since n is an int variable, g++ simply treats it as a global variable pre-initialized to 5. Let's see what happens if we do the same with a std::string: #include <string> void count() { static std::string...
7,740,925
7,740,957
Define variables in c++
I am always confused with the concept "define variable." What does define mean? For example: void main { map<int,int> *infoMap; if() { //some check here,if it passes this check, then new infoMap } infoMap = new infoMap; } So does map<int,int> *infoMap; or map<int,int> *infoMap = new inforMap; define a variable?...
The top one is the declaration, or if you like, definition. Here, the compiler allocates space for the variable. The bottom one is an assignment. Here, the compiler fills the space it allocated at definition time. You can have more than one assignment, if you want to change the value of the variable to something else.
7,741,168
7,741,227
about the const in an operator overloading definition
For the following definition of const vector3F operator*(const vector3F &v, float s); There are two const, what are their respective usages?
The const-reference in the argument means that you don't change v, so you can pass constant vectors (and temporaries!) to the function. That's a Good Thing. The constant by-value return is sort of a gimmick. It prevents you from writing things like this: vector3F v = get_vector(); vector3F w = v; (v * 1.5) = w; // ...
7,741,346
7,741,507
Inline calls to non-inline base class functions (what does that mean exactly)?
I'm reading through a C++ book and I'm in a section about reducing the object code generated by templates (Effective C++ III By Scott Meyers). One of the examples it gives is: template <typename T, std::size_t n> class SquareMatrix: private SquareMatrixBase<T> { public: SquareMatrix() : SquareM...
The point is that SquareMatrix::invert() is inlined, so the function doesn't even appear in the resulting code, and instead the protected base function SquareMatrixBase::invert(n) is called directly. Now since that function is not inlined, there is only one single instance of that function (for each type T), rather tha...
7,741,455
8,021,955
Creating a boost::python::object from a std::function
How can I construct a boost::python::object from a std::function ?
Use boost::python::make_function, and provide a signature because the default one doesn't handle std::function. For example, we want to wrap the return type of: std::function<std::string(int, int)> get_string_function(const std::string& name) { return [=](int x, int y) { return name + "(x=" + std::to_st...
7,741,531
7,741,915
Conversion operator template specialization
Here's a largely academic exercise in understanding conversion operators, templates and template specializations. The conversion operator template in the following code works for int, float, and double, but fails when used with std::string... sort of. I've created a specialization of the conversion to std::string, wh...
You can reproduce the problem by just using std::string t(a); Combined with the actual error from GCC (error: call of overloaded 'basic_string(MyClass&)' is ambiguous) we have strong clues as to what may be happening: there is one preferred conversion sequence in the case of copy initialization (std::string s = a;), a...
7,741,558
7,741,589
the meaninings of two ** for an iterator
In the following code segment vector<SceneObject *> sceneObjs; vector<SceneObject *>::iterator iter; iter = sceneObjs.begin(); while (iter != sceneObjs.end()){ cout << **iter <<endl; iter++; } why **iter has two *s ?
The first * dereferences the iterator, giving a SceneObject * pointer. The second * dereferences this SceneObject * pointer to the SceneObject itself.
7,741,652
7,743,091
Can we use a lambda-expression as the default value for a function argument?
Refering to the C++11 specification (5.1.2.13): A lambda-expression appearing in a default argument shall not implicitly or explicitly capture any entity. [ Example: void f2() { int i = 1; void g1(int = ([i]{ return i; })()); // ill-formed void g2(int = ([i]{ return 0; })()); // ill-formed void g3(in...
Yes. In this respect lambda expressions are no different from other expressions (like, say, 0). But note that deduction is not used with defaulted parameters. In other words, if you declare template<typename T> void foo(T = 0); then foo(0); will call foo<int> but foo() is ill-formed. You'd need to call foo<int>() expl...
7,741,696
7,741,944
Do I even need libusb?
I have a feature request on a project I work on, it is to integrate with a Paylife CC handheld, which has a USB connector to connect with the computer. I have the docs, and am reading up on it. When I searched on google how to read/write to a usb device on linux, it said, use libusb. I was wondering, is there another...
It is definitely possible when the device complies with one of the USB device classes -- drivers for them are universal. If that's not the case, then you may stick with a manufacturer-provided or a third-party driver, given there is one and you possess enough of it's documentation. If that's also not the case, libusb-1...
7,741,751
7,741,959
Sending variable length arrays over a network?
In the game I'm making, I nee to be able to send std::vectors of integer over a network. A packet seems to be made up entirely of a string. Since enet, the network libray im using takes care of endian, my first idea on solving this is to send a messsage where the first byte is the message id, as usual, the next 4 bytes...
In general, there are two approaches to solving this problem which can be combined. One is to put the length of the array before the actual array. The other involves including some framing to mark the end (or beginning) of your message. There are advantages and disadvantages to each. Putting the length before the array...
7,741,867
7,741,901
Is there Path Edit Control in Win32?
I would like to add an edit box (or is it a combo box?) for entering a file-path using Visual C Win32 so that it offers auto-complete - the same as when you type in Windows Explorer's address bar. Is there a common control or property I'm missing that allows me to do that?
You can use the standard edit control and call SHAutoComplete. Like this: SHAutoComplete(editWnd, SHACF_DEFAULT); The system will do the rest for you.
7,742,040
7,742,074
How to read raw data from disk in mac os
Question basically as in the title. I could use c/c++/objective-c. I would like to read data from some offset on the disk. Just some basics, I will dig dipper when you show me where :).
Just open /dev/rdisk?s?. They represent the byte sequences on the disk as a device file.
7,742,216
9,842,856
MPI parallel program execution on single computer
I want to run parallel codes on single pc with core i7 cpu I can compile my code but I have problem with running it. I compile my code with mpicxx and when I run it by " mpirun -np 8 ./a.out" only one process is. My operating system is linux ubuntu 11.04. Working what must I do? For example I want to run this code: #in...
If you use ubuntu operating system you can execute your codes with mpiexec -n 8 /path/to/application too and no machine file is required just be sure that you installed mpich library properly for doing this you can use synaptic package manager for installing library.
7,742,290
7,742,819
Problems trying to apply shader to vertex array in OpenGL using C++
I have 4 dimensional vertices(X,Y,A,B) that I'd like to draw as 6 separate 2D plots (XxY, XxA, XxB, YxA, ...) My vertices are defined as follows: GLint data[MAX_N_POINT][4]; I can draw the first (X,Y) of the 2D plots just fine with: glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(4, GL_INT, 4*sizeof(GLint), &da...
You have to set the axes uniform (glUniform1i) after you enabled/use the program (glUseProgram), otherwise it doesn't have any effect (and your axes uniform keeps its default value, which seems to be 0). But I hope your program also contains a valid fragment shader that uses your passcolor varying, as the fixed functio...
7,742,332
7,742,607
Purpose of --enable-auto-import Warning
I am trying to compile the following program: #include <iostream> int main(){ std::cout << "Hello, world!"; return 0; } When I compile it, I get this message: C:\programs>g++ test.cpp Info: resolving std::cout by linking to __imp___ZSt4cout (auto-import) c:/mingw/bin/../lib/gcc/mingw32/4.5.0/../../../../mingw...
I did some reading and it looks like it might be related to the mingw32 dll not having dllimport attributes defined. Perhaps there is a patch or you can rebuild mingw32 yourself and add them?
7,742,361
7,742,450
C++ writing an object to a file then later reading it in?
Possible Duplicate: How to serialize in c++? How to implement serialization in C++ I've been toying around with C++ more and more these days and have only had a couple experiences with ofstream at this point. Most of said experiences have been doing simple file output of variables and reading them back in with ifs...
You could just write the object to a file by copying it's contents in memory. But then you hit the tricky bits! You can't copy any items that are pointers to memory, because when you load them back in they don't own that memory. That means copying things like std::string which may internally contain their own memory al...
7,742,563
7,794,943
Inline namespace emulation for MSVC (10.0/11.0)
Is there any way to emulate an inline namespace with MSVC? LLVM's libc++ uses this to create a hidden versioned namespace like so: #define _LIBCPP_BEGIN_NAMESPACE_STD namespace std {inline namespace _LIBCPP_NAMESPACE { #define _LIBCPP_END_NAMESPACE_STD } } #define _VSTD std::_LIBCPP_NAMESPACE namespace std { inline ...
I'm afraid there is no possibility of such emulation. Microsoft seems to be very uninterested in symbol versioning, even though they break ABI on their standard library on every single new revision of their compiler. The GCC emulation works because strong using was the basis for the inline namespace feature. Microsoft ...
7,742,836
7,742,882
How to have a derived class use the base implemention to satisfy an interface
I have the following two interfaces, which are not part of an inheritance hierarchy. I then have two concrete classes, one which derives from the other. class ICar { public: virtual void drive() = 0; }; class IFastCar { public: virtual void drive() = 0; virtual void driveFast() = 0; }; class Car ...
The problem lies in the fact that there's multiple inheritance taking place here ... even though FastCar is derived from Car, the version of drive() in the base-class Car only overrides ICar::drive(), not IFastCar::drive(). Thus, since you are deriving FastCar from IFastCar, you will need to, at some point, define a f...
7,742,865
7,744,677
glBindFramebuffer causes an "invalid operation" GL error when using the GL_DRAW_FRAMEBUFFER target
I'm using OpenGL 3.3 on a GeForce 9800 GTX. The reference pages for 3.3 say that an invalid operation with glBindFramebuffer indicates a framebuffer ID that was not returned from glGenFramebuffers. Yet, I output the ID returned by glGenFramebuffers and the ID I send later to glBindFramebuffer and they are the same. The...
If glBindFramebuffer(GL_FRAMEBUFFER) works when glBindFramebuffer(GL_DRAW_FRAMEBUFFER) does not, and we're not talking about the EXT version of these functions and enums (note the lack of "EXT" suffixes), then it's likely that you may have done something wrong. GL_INVALID_OPERATION is the error you get when multiple co...
7,743,213
7,743,275
Possible to eliminate this base-class constructor?
Is there any way to eliminate the explicit constructor call in Foo and somehow have Bar::len assigned to the size of any of Bar's sub-classes? class Bar { size_t len_; Bar(size_t len) : len_(len) { } }; class Foo : public Bar { Foo() : Bar(sizeof(Foo)) { } };
You could use a "curiously recursive template" to inform the base class of the derived class's type: template <typename Derived> class Bar { size_t len_; protected: Bar() : len_(sizeof(Derived)) {} }; class Foo : public Bar<Foo> { };
7,743,252
7,743,348
Can I make clang generate absolute addresses for function pointers?
Here's a simplified version of some code I'm working with right now: int Do_A_Thing(void) { return(42); } void Some_Function(void) { int (*fn_do_thing)(void) = Do_A_Thing; fn_do_thing(); } When I compile this in xcode 4.1, the assembler it generates sets the fn_do_thing variable like so: 0x2006: calll 0...
You're looking at position independent code (more specifically Position Independent Executable) in action. This, as you noticed, allows the OS to load the binary anywhere in memory, which provides numerous security improvements for potentially insecure code. You can disable it via removing a linker option in XCode (-Wl...
7,743,287
7,743,343
class with both abstract and virtual methods
Can I write a class which has virtual methods - (which can be overridden but have a default behaviour) and also abstract methods - (which have to be overridden) Can I have a definition in which I define implementations for the virtuals but not the abstracts? Additionally can I create abstract methods that don't have an...
Can I write a class which has virtual methods - (which can be overridden but have a default behaviour) and also abstract methods - (which have to be overridden) Yes. Can I have a definition in which I define implementations for the virtuals but not the abstracts? Yes. Additionally can I create abstract methods tha...
7,743,356
7,743,397
Length of a C++ std::string in bytes
I'm having some trouble figuring out the exact semantics of std::string.length(). The documentation explicitly points out that length() returns the number of characters in the string and not the number of bytes. I was wondering in which cases this actually makes a difference. In particular, is this only relevant to non...
When dealing with non-char instantiations of std::basic_string<>, sure, length may not equal number of bytes. This is particularly evident with std::wstring: std::wstring ws = L"hi"; cout << ws.length(); // <-- 2, not 4 But std::string is about char characters; there is no such thing as a multi-byte character as f...
7,743,511
7,743,626
Fast way to decode JPEG image
I need to decode (unpack into bitmap) pretty small (about 1200 * 1200) JPEG. The problem is I need to do it quickly. I have tried libjpeg, and it's quite slow. I have also tried BitmapFactory.decodeByteArray - it's a bit faster, but still not fast enough. What are another options? A native (C++) library is much preferr...
Try Libjpeg Turbo: http://libjpeg-turbo.virtualgl.org/
7,743,718
7,743,882
Shifting back to something
word color; crap = ((color & 0xffc0) >> 1) | (color & 0x1f) I have this shifting code. I have no idea what the purpose is of this code, but I suspect it has something to do with switching between 555 to 565 colors. How would I create a function that does the exact opposite as the code above? That converts the variabl...
I suspect it has something to do with switching between 555 to 565 colors. Yes, that's what it's doing. color will be the 565 representation, and crap the corresponding 555 representation. Lets look at what each operation does. I'll refer to the three fields as a (5 bits), b (6 bits, transformed to 5) and c (5 bits)....
7,743,734
7,743,865
Can the unsigned keyword be used in non-obvious ways?
Every time I've used the unsigned keyword it has been before int, or another built-in type. I was wondering if there were any other ways unsigned could be used. Can user defined types (classes/structs) use the unsigned keyword? Can templates make special use with unsigned? If not, why does it have its own keyword? Wh...
No, it can't be used with classes or structs since they're not integral types. All a template can do with it is make an int unsigned. I think it was chosen as a separate keyword since it can be applied to any integer type (char, int, long, long long), thereby achieving with one keyword what would have required four m...
7,743,771
7,744,342
Function hooking in C++?
With "hooking" I mean the ability to non-intrusively override the behavior of a function. Some examples: Print a log message before and/or after the function body. Wrap the function body in a try catch body. Measure duration of a function etc... I have seen different implementations in various programming languages a...
If you're talking about causing a new method to be called before/after a function body, without changing the function body, you can base it on this, which uses a custom shared_ptr deleter to trigger the after-body function. It cannot be used for try/catch, since the before and after need to be separate functions using...