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,640,880
7,640,914
c++ calling a non static function from a static function
I'm experiencing an access violation error when I try to call non static function. my .h file looks like this. class World { public: World(); virtual ~World(); static void CALLBACK DispatchCallback( SIMCONNECT_RECV *pData, DWORD cbData, void *pContext ); void Process(SIMCONNE...
You're passing NULL as the context parameter to SimConnect_CallDispatch, so your callback has no idea which World object to call Process on -- how could it possibly if you don't tell it? Change the call to pass in this as the context parameter, like the example does: SimConnect_CallDispatch(hSimConnect, DispatchCallba...
7,640,889
7,640,989
Determine if a byte array contains an ANSI or Unicode string?
Say I have a function that receives a byte array: void fcn(byte* data) { ... } Does anyone know a reliable way for fcn() to determine if data is an ANSI string or a Unicode string? Note that I'm intentionally NOT passing a length arg, all I receive is the pointer to the array. A length arg would be a great help, but I...
First, a word on terminology. There is no such thing as an ANSI string; there are ASCII strings, which represents a character encoding. ASCII was developed by ANSI, but they're not interchangable. Also, there is no such thing as a Unicode string. There are Unicode encodings, but those are only a part of Unicode itself....
7,641,439
7,641,492
What is wrong with my header setup
What is wrong with my setup with DWORD and LPCTSTR? class myApp : public CApplication { public: unsigned int DWORD; const char *LPCTSTR; myApp( CApplication::ApplicationByteAware theAppByte = CApplication::AB_SINGLEBYTE ); virtual ~myApp( void ); DWORD IsProcessRunning(LPCTSTR procname); bool...
You're declaring DWORD and LPCTSTR as member variables but trying to use them as types. What you want to do instead is // declare the typedefs here typedef unsigned int DWORD; typedef const char *LPCTSTR; class myApp : public CApplication { public: myApp( CApplication::ApplicationByteAware theAppByte = CApplicat...
7,641,625
7,641,672
Is there a way to read programming languages on an iphone?
Something like github on an iphone for times I'm not at the desk would come in handy.. Is there such thing?
There are a handfull of IDE Apps available for Ios: A simple search for "Iphone IDE App" yealded: Gusto - Code Editor and FTP Client Markup for iPad Mides IDE Source Viewer XL
7,641,705
7,641,721
How to translate paths with environment variables (Eg. %temp%)
I am searching for a winapi function to expand paths with environment variables. I have tried GetFullPathName but the result is weird: "%appdata%\something" becomes "C:\<path to directory of exe>\%appdata%\something". How to do this correctly?
Try ExpandEnvironmentStrings.
7,641,764
7,641,886
Return an object in VBA
I've built a custom DLL which, for this example, has a function login. In C++ I use it by creating an object and then accessing the function through the object pointer, like so: ConnectMe *cm = new ConnectMe("216.239.51.99"); cm->login("username", "password") What I'd like to be able to do is use this code in Excel. I...
If your DLL is registered in machine, in tools/reference, set the check to. After, in your code use dim cm as new ConnectMe cm.ConnectMe("216.239.51.99") cm.login("username","password")
7,641,801
7,641,897
Comparing two times for equality within tolerance?
I have an MFC application where I want a certain method to be called at specified times. I will specify the times by using a vector of tm structs that have the hour minute and second filled out. Possibly I may need to store a boolean value for each time to indicate whether the method was called at the specified time....
You need to use mktime to get a time_t. time_t is generally the number of seconds since the beginning of 1970, so you don't need to worry about 2:10:59 vs 2:11:01. struct tm expected_tm; struct tm actual_tm; // set those tms to something time_t expected_time = mktime( &expected_tm ); time_t actual_time = mktime( &ac...
7,641,814
7,641,930
Stopping at Blank Line During User Input (C++)
I've got a file that I need to parse using cin and a redirect at the command line. The first however many lines consist of two doubles and two strings, then comes a blank line, then more information. I need to stop reading in the data at this blank line and switch to different variables because the data will be formatt...
Parse it like you would parse any file and just keep track of when an empty line happens: #include <sstream> #include <fstream> #include <string> int main() { std::ifstream infile("thefile.txt", "rb"); std::string line; while (std::getline(infile, line)) // or std::cin instead of infile { if (line == "") ...
7,641,817
7,650,499
CUDA and templates: specialization declaration needed?
I have a templated wrapper function that calls a kernel (__global__) defined in a .cu file like this template<typename T, class M> __global__ void compute_kernel(T* input, T* output, n) { M m; // compute stuff using m }; template<typename T, class M> void compute(T* input, T* output, int n) { // ... comp...
This is a C++ FAQ, not limited to CUDA. If you have a template implementation in a .cpp or .cu file then when you compile that translation unit the compiler cannot possibly know what permutations of template parameters you will need. Therefore when you link you will get the errors. You could put the implementation in a...
7,642,021
7,642,060
C++ What's wrong with this class?
It doesn't compile in Visual Studio, it says 1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup 1>position.exe : fatal error LNK1120: 1 unresolved externals #include <iostream> #include <cstdlib> using namespace std; class Position { private: int...
It compiled for me under Visual Studio Professional 2008. Try creating a new project. Select File->New and specify Project Type of Visual C++ -> Win32 -> Win32 Console Application. Then click Ok. Then click on Application Settings and uncheck "Precompiled header". Then paste in your code and compile it successfully.
7,642,055
7,642,483
Voxels... Honestly, I need to know where to begin
Okay, i understand that voxels are just basically a volumetric version of a pixel. After that, I have no idea what to even look for. Googling doesn't show any tutorials, I can't find a book on it anywhere, I can't find anything even having to do with the basic idea of what a voxel really is. I know much of the C++ li...
Minecraft is a good example of using voxels. In Minecraft each voxel is a cube. To see a C++ example you can look at the Minecraft clone Minetest-c55. This is open source so you can read all of the source code to see how its done. Being cubes is not a requirement of voxels. They could be pyramids or any other shape th...
7,642,085
7,642,623
How to get total memory in bytes used by OpenGL in C++?
How to get total memory in bytes used by OpenGL in C++? I'm building an OpenGL application and the total memory used seems to be rising, I can get the info about the total memory used by variables & objects created by myself but can't guarantee how much memory OpenGL is using for its variables & objects & textures, et...
In general, you don't. OpenGL is ultimately a hardware abstraction. And OpenGL simply doesn't provide a way to get that sort of information. There are vendor-specific extensions that will give you ways to ask, though what you get back depends on the architecture. AMD hardware provides the ATI_meminfo extension. It brea...
7,642,125
7,642,137
visual c++ 2010 errors importing User32.dll into 64bit win7
Running visual c++ 2010 on 64bit win7, this line #include "C:\Windows\SysWOW64\user32.dll" its the correct path, the errors however include variations of 1>C:\Windows\SysWOW64\user32.dll(1): error C2018: unknown character '0x3' 1>C:\Windows\SysWOW64\user32.dll(1): error C2018: unknown character '0x4' 1>C:\Windows\Sys...
That's not how you import libraries. You just tried to include a binary. This has nothing to do with 32/64 bits. What you need to do it add user32.lib to your library path. You can import a library in Visual Studio by: Project -> Properties -> Linker -> Additional Dependencies Add "user32.lib" to the list.
7,642,217
7,642,237
snprintf with "%0*d" , too few arguments
I needed to dynamically generate a string like the following: 001 / 192 However , the number of digits varies , thus i must define another variable , called print_width , which is , in this case: 192 % 10 snprintf ( statusString , 30 , "%0*d / %0*d" , snprintf_width , completed[tid] , total[tid]); The code above pos...
You need an integer width argument for each * as well as for each d in the format. You've provided 3 of the requisite 4 arguments, and your compiler is kind enough to tell you, rather than producing garbage at run time. Hence, for example: if (snprintf(statusString, sizeof(statusString), "%0*d / %0*d", snprintf_width,...
7,642,224
7,642,240
simplifying and rewriting my code
I will be as specific as possible.. I have this code: // bintodec.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <iostream> #include <string> using namespace std; int main(){ string inp; int dec = 0; char base; cout << "Input a number: "; cin >> inp; c...
1: You can't do inp.length() because you declared inp as a char. And a char isn't a string. Try declaring inp as a string: string inp; 2: "subscript requires array or pointer type" Same reason as above. inp is a char and not an array or a string. 3/4: "'++' needs l-value" You're missing a semicolon after: dec=dec + (x...
7,642,248
7,643,775
How to enable custom gcc parameters in Qt Creator?
I needed to pass in "-std=c++0x" for g++ , in Qt Creator. I placed a variable in Build Environment: But i still receive the warning: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
You need to add QMAKE_CXXFLAGS += -std=c++0x to your .pro file.
7,642,359
7,642,391
"no match for call" error using boost::bind
I'm still new to boost::bind, and now porting a program that was written 2 yrs ago in 2009, seeing the compile error below. Any idea to workaround would be appreciated. Extracted cpp file: class ClassA { private: cNamespace::Bounds bounds_msg_; void boundsHandler(const PublisherPtr& p) { p->publish(bo...
It looks like the function object that is produced by boost::bind is called with a different type than the function you bound. i.e. it's called with const ros::SingleSubscriberPublisher& argument, instead of the expected const PublisherPtr& p. Assuming SubscriberStatusCallback is a boost::function, you should make sure...
7,642,614
7,642,713
find size of derived class object using base class pointer
Is it possible to find the size of a derived class object using a base class pointer, when you don't know the derived type. Thank you.
There's no direct way, but you can write a virtual size() method child classes can implement. An intermediary templates class can automate the leg work. struct base { virtual size_t size() const =0; virtual ~base() { } }; template<typename T> struct intermediate : base { virtual size_t size() const { return si...
7,642,842
7,648,390
Deformable terrain in OpenGL 2D [Worms like]
I've searched for a while and I've heard of different ways to do this, so I thought I'd come here and see what I should do, From what I've gathered I should use.. glBitmap and 0s and 0xFF values in the array to make the terrain. Any input on this? I tried switching it to quads, but I'm not sure that is efficient and th...
I would suggest you to use the stencil buffer. You mark destroyed parts of the terrain in the stencil buffer and then draw your terrain with stencil testing enabled with a simple quad without manually testing each pixel.
7,642,865
7,642,881
Memory address in dynamic allocation
#include <iostream> int main() { int anything[] = {5}; int *something = new int; *something = 5; std::cout << &anything << "==" << &anything[0] << "==" << anything << std::endl; std::cout << &something << "!=" << &something[0] << "==" << something << std::endl; } Why is the memory address in &something ...
&something is the memory address of the pointer itself (hey, it needs to store that value somewhere!), while &something[0] is the address of the actual memory that is storing your stuff.
7,642,955
7,644,057
Problems compiling an c++ application using QT and OpenGL
I'm following this tutorial for building a simple OpenGl application in C++ using QT. I'm trying to compile the application using g++ and the command line but I get the following errors: /tmp/ccH2KFoZ.o: In function `GLWidget::GLWidget(QWidget*)': GLWidget.cpp:(.text+0x38): undefined reference to `QGLWidget::QGLWidge...
The .pro file is needed by QMake, the make app distributed with Qt. This pro file specifies all the files needed to build your project, as well as the Qt modules. More about qmake and the .pro file here: http://qt-project.org/doc/qt-4.8/qmake-manual.html If you install the IDE QtCreator, the task of modifying the .pro ...
7,642,987
7,643,028
Differentiate between pointers and data variables
given a function with a variable number of parameters... void function(int count,...) { ... } how do i differentiate between pointers and data variables... given i don't know the types beforehand. i.e char *p=new char(); *p='v'; function(2,5,p); how to know if p is a pointer so that it can be handled that way inside...
This is not possible using variable arguments. The type of the arguments must be known when calling va_arg. One possible way to do this is pass pointers to self describing data like variants.
7,643,231
7,643,268
Three20 titleForHeaderInSection
Here is what I added. It just lists all the objectsForCharacters under each one of the alphabet characters. - (void)tableViewDidLoadModel:(UITableView*)tableView { items = [[NSMutableArray alloc] init]; arrayOfCharacters = [[NSMutableArray alloc]init]; objectsForCharacters = [[NSMutableDictionary alloc]init]; NSM...
you can check out the link.http://blog.webscale.co.in/?p=240
7,643,245
7,644,836
Curly Bracket Initialization in C++ and Java
In the code below, I don't seem to understand the limitations of the curly bracket initialisation. What do they actually do? It seems in the case of A it just sets a[0] equal to the value directly. In the case of b it using implicit conversion. Does it decide which one to do based on what is available, or is there s...
Since the Java part has already been answered, I will add a bit about the C++ part. The specific version of curly brace initialization that you refer to is called aggregate initialization and (unsurprisingly) is used to initialize aggregates. Each element in the aggregate will be initialized with the corresponding elem...
7,643,315
7,643,351
Convert vector to map with pointers to members?
I'm having trouble understanding why the code below #include <string> #include <vector> #include <map> using namespace std; struct Student { int id; string name; }; template<typename T, typename U, U T::* Member> map<U, T> group_by(const vector<T> &items) { map<U, T> result; for (vector<T>::const_iterator it...
it is not a pointer to a Student so you can't use it with the ->* member access operator`. I think you meant: result[(*it).*Member] = *it; To form a pointer to member, you need to use &, it is not optional. You also need to introduce dependent type names (such as vector<T>::const_iterator with typename). This version ...
7,643,342
9,345,345
convert keypoints to mat or save them to text file opencv
I have extracted SIFT features in (opencv open source) and they are extracted as keypoints. Now, I would like to convert them to Matrix (With their x,y coordinates) or save them in a text file... Here, you can see a sample code for extracting the keypoints and now I would like to know how convert them to MAT or save t...
Convert to cv::Mat is as follows. std::vector<cv::KeyPoint> keypoints; std::vector<cv::Point2f> points; std::vector<cv::KeyPoint>::iterator it; for( it= keypoints.begin(); it!= keypoints.end();it++) { points.push_back(it->pt); } cv::Mat pointmatrix(points); Write to filestorage is cv::FileStorage fs("test.yml",...
7,643,359
7,643,431
template specialization with multiple template parameters
Say I have this: template<typename T, int X> class foo { public: void set(const T &t); }; template<typename T, int X> void foo::set<T, X>(const T &t) { int s = X; // ...etc } Could I specialize the function type 'T' but leave 'X' as a template parameter? class bar; template<int X> void foo::set<bar, X>(const ...
This is surprisingly easy once you get the hang of it template<typename T, int X> class foo { private: template<typename, int> class params { }; public: void set(const T &t) { set(t, params<T, X>()); } private: template<typename T1, int X1> void set(const T1 &t, params<T1, X1>) { // ... } tem...
7,643,490
7,643,547
How to use odbc to import excel file into mysql table via c++?
I have a c++ program, and I am planning to use odbc to communicate my c++ program with mysql tables. There is alot of tutorials online on how to access mysql tables using c++ and odbc, but how do I use c++ and odbc to load a excel file into mysql tables?
One way is to save the file as a CSV and then execute the following statement LOAD DATA LOCAL INFILE ‘C:\\temp\\yourfile.csv’ INTO TABLE database.table FIELDS TERMINATED BY ‘;’ ENCLOSED BY ‘”‘ LINES TERMINATED BY ‘\r\n’ (field1, field2); in your program. i.e. if you are using the C++ wrapper, stmt = con->createState...
7,643,528
7,643,568
How many usage does "volatile" keyword have in C++ function, from grammar perspective?
I asked this function based on this concept (maybe incorrect?!): Wherever a const can exist, a volatile can exist at the place. class classA { public: const int Foo() const; } Here the first "const" means the return value is const, we can not change it. the second const means "Is Query", this function can not chan...
Volatile has one primary function, which is to say "STOP! This object is connected to external resources, and thus when I write to it, don't reorder the write with respect to other volatile reads or writes, and when I read to it, don't reorder it likewise and don't optimize these away!". To support this, you can put v...
7,644,002
7,644,033
How to convert from recursive algorithm to iterative
How do I convert following recursive algorithm to iterative DFS-Visit(U) color[u] = GREY d[u] =time time = time + 1 for each v = Adj[u] do if color[v] = WHITE then p[v] = u DFS-Visit(v) color[u] = BLACK f[u] = time time = time + 1
USE stack to save the state instead..of calling it recursively this might help you : http://www.cs.mcgill.ca/~pnguyen/251F09/DFS.pdf
7,644,113
7,644,228
Is there a guaranteed width of the underlying int for an enum?
In the example in N2347 one advantage if the new stongly typed enums (C++11) compared the current (C++03) is explained by an example with an "old" enum: enum Version { Ver1 = 1, Ver2 = 2 }; struct Packet { Version ver; // ... more data ... // bad, size can vary by implementation Version getVersion() cons...
The relevant paragraph of the C++03 standard is §7.2.5: The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying ty...
7,644,154
7,644,297
Calling base class virtual method by derived class virtual method
In C++ - take a case where derived class deriving from a base class and there is a virtual method in base class which the derived class is overriding. Could someone tell me a real life scenario where the derived class version of the virtual function might require to call the base class version of the virtual function? ...
You do that every time when you also need base class behavior but don't want (or can't) reimplement it. One common example is serialization: void Derived::Serialize( Container& where ) { Base::Serialize( where ); // now serialize Derived fields } you don't care how base class is serialized, but you definitely...
7,644,176
10,219,000
get LCID from string
How to get LCID from string like "en-US"? I know about GetLocaleInfoEx function, but it doesn't work on windows XP. Can I get LCID from CRT locale? UPD: Can I convert between LCID and CRT locale (created by _create_locale function)? CRT locale may be created by _create_locale and string - Locale name.
http://msdn.microsoft.com/en-us/library/aa741018%28v=vs.85%29.aspx Seems to go back as far as IE 4.0, so you should be OK on XP.
7,644,251
7,644,685
Qt Designer undefined symbol with Custom Widget plugin
I am using Qt 4.7.2 under Fedora 14. I have a working library of custom widgets which I am trying to integrate into Qt Designer. There is a simple widget base class, then some more complex widgets inheriting from it. The simple widget integrates fine, but I have a problem with the more complex ones. The problem comes f...
The error message looks as if the linker did not find a definition for the constructor myWidget(QString, my_struct*, QWidget*). Have you added the relevant source file to your release build? Do you actually have a definition for this constructor? It is also possible that you have to exchange the object file linking ord...
7,644,460
7,644,671
pthreads program works for some time and then stalls
There is a program I am working on that, after I launch it, works for some time and then stalls. Here is a simplified version of the program: #include <cstdlib> #include <iostream> #include <pthread.h> pthread_t* thread_handles; pthread_mutex_t mutex; pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; int thread_cou...
I think you should init the thread number to numb_count rather then argv then replace long thread = (long) j % thread_count; with long thread = (long) j; won't sure it fix it, but it's needed anyway... Moreover, it's not about the number 76 or 77, you have a race condition in the thread use. lets say that one of yo...
7,644,982
7,645,023
Ambiguous if and else branches: Is the behaviour defined?
I recently came accross some C++ code like the following: if(test_1) if(test_2) { // Do stuff } else exit(0); This is ambiguous, since the compiler could see this as: if(test_1) { if(test_2) { } else { } } or as: if(test_1) { if(test_2) { } } else { ...
Is the behaviour of this code defined according to any standard (C, C++)? Yes, it is defined. In C (and all similar languages as I know), the "dangling else" binds to the last free if, therefore this interpretation if(test_1) { if(test_2) { } else { } } is correct.
7,644,996
7,647,083
How to increase contours precision?
I am working on a project using OpenCV. I need to precisely crop out some objects from HD photos. I'm using a quad tree to cut my photos in pieces and then I calculate the homogeneity of each quad to determine if a piece of the object is in the quad. I apply some filters as Canny with different thresholds depending on ...
Maybe you could use some kind of an average filter to approximate the curve and then use AproxPoly with a small gradient to smooth it. Here is a similar method: void AverageFilter(CvSeq * contour, int buff_length) { int n = contour->total, i, j; if (n > buff_length) { CvPoint2D32f* pnt; floa...
7,645,041
7,652,699
Simple working example of GzipOutputStream and GzipInputStream with Protocol Buffers
after some days of experimenting with Protocol Buffers I tried to compress the files. With Python this is quite simple to do and does not require any play with streams. Since most of our code is written in C++ I would like to compress/ decompress files in the same language. I've tried the boost gzip library, but c...
Your assumption is right: the code you posted doesn't work because you're writing directly to the ofstream instead of through the filtering_streambuf. To make this work you can use filtering_ostream instead: ofstream file(filename.c_str(), ios_base::out | ios_base::binary); filtering_ostream out; out.push(gzip_compre...
7,645,394
7,646,071
Combining the 'using' directive with partial overloading: gcc feature or intel bug?
I wish to use a set of libraries written in C++ with the Intel compilers. I've attached sample code which demonstrates the problem. There are many places in the libraries where they make use of combining the 'using' directive with partial overloading (e.g., I want to use the foo(void) method from the base class but rei...
For C++11, the relevant Standard quote can be found in 7.3.3 The using declaration [namespace.udecl] 14/ If a function declaration in namespace scope or block scope has the same name and the same parameter types as a function introduced by a using-declaration, and the declarations do not declare the same function, the...
7,645,403
7,645,754
Serial port won't accept baud rate
I am trying to setup a serial port on centos but can't get it to work. this is the code that I'm having trouble with. tcgetattr(idComDev[i], &options); // get current settings printw("default baudrate is %d ", cfgetispeed(&options)); cfsetispeed(&options, B115200); // set baud rate cfsetospeed(&options, ...
B115200 is a macro, and expands to 0x1002. That's a combination of two bits: 0x1000 signals that it's a non-standard rate (as you discovered) and 0x2 is the second non-standard rate (B57600 is 0x1001, the first non-standard rate).
7,645,556
7,645,616
try to change ActivePowerScheme: RegOpenKeyEx failed with error 0
I need to set ActivePowerScheme by changing it in registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power\User\PowerSchemes. So I try to do it with winapi functions RegOpenKeyEx and RegSetValueEx wchar_t *PowerScheme=TEXT("8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c"); HKEY hRootKey = HKEY_LOCAL_MACHINE; PWCHA...
You are going about this the wrong way. You RARELY need to change stuff in the registry yourself. Read Power Scheme Management on the MSDN site for the proper way of doing it.
7,645,578
7,645,618
Best way to represent Nullable member in C++?
Possible Duplicate: Nullable values in C++ What is the best way to represent nullable member in C++? In C#, we can use Nullable<T> type. Such a data type is very much needed as not everything can have meaningful value. It is so important data type that @Jon Skeet has spent one entire chapter, spanned over 27 pages, ...
You could look into Boost.Optional: struct Person { std::string Name; DateTime Birth; boost::optional<DateTime> Death; //... }; Your Death is "uninitialised" at first. You can then assign a value to it with =, like Death = myDateTime. When Death.is_initialized(), you can use Dea...
7,645,675
7,658,546
OpenGL ES texture origin differs from top/left to bottom/left on different phones
I'm currently developing an NDK-based OpenGL ES 2.0 app. And i'm loading textures using libjpeg flipping it vertically (as OpenGL standard says). It works fine on Samsung Galaxy SII, HTC Desire HD and so on (+ Windows's SDL implementation). But on some phones (like Samsung Galaxy S GT-I9000 by reports from Android Mark...
Looks like i've fixed this problem myself. I've started using compressed ETC1 textures instead of uncompressed ones and that helped to fix this strange issue.
7,645,723
7,651,242
Parsing escaped strings using Boost::Spirit
I would like to write a boost::spirit parser that parses a simple string in double quotes that uses escaped double quotes, e.g. "a \"b\" c". Here is what I tried: #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <iostream> #include <string> namespace client { namespace qi ...
Been a while since I had a go at spirit, but I think one of your rules is the wrong way round. Try: content = +(escChar | ~char_('"')) instead of: content = +(~char_('"') | escChar) It is matching your \ using ~char('"') and therefore never gets round to checking if escChar matches. It then reads the next " as the en...
7,645,914
7,646,048
QMap and QPair, C++, Qt
I want to make a data structure for accessing strings by two ways: Access by ID Access by name My first idea is using two maps for each method but it leads to duplication of data: QMap<int, QString> accessById; QMap<QString, QString> accessByName; I'm searching for a better way, something like this: QMap<QPair<int, ...
How about: QMap<QString, int> nameIdMap; QMap<int, QString> accessById; You access by id and create a map for names and ids. Then you can access by name with QString data = accessById[nameIdMap[the_name]];
7,646,055
7,647,058
Supressing Script Error in IE8 (C++)
I want to prevent IE from showing JS error dialogs, I read that it can be done by setting ScriptErrorsSuppressed = true. Where exactly do I set it in IWebBrowser2? Thanks
The docs you are reading refer to what you can do if you embed an IE HTML rendering pane in your own application. They allow you to alter the behavior of that pane. If you have done that, then you can use COM to QueryInterface an IWebBrowser2 interface from the component. See more here: http://support.microsoft.com/kb...
7,646,194
7,647,544
Programmatically open System Information
I am trying to programmatically open Window's "System Information" across different Window's version. At the moment it involves opening a cmd.exe window which then finds "System Information". The problem is that I have an extraneous black command-line window while the "System Information" is open. Is there a way of doi...
It is a known app, like Wordpad, the reason that cmd.exe can find it. Just use ShellExecute to open msinfo32.exe. For example: #include <shellapi.h> #pragma comment(lib, "shell32.lib") ... // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (mes...
7,646,243
7,646,290
C++ operator overloading on templated class
I have a templated Stack class implemented internally with vector. Here is the content of my (simplified) TStack.h: #include <vector> #include <iostream> template<typename T> class TStack; template<typename T> TStack<T> operator+(const TStack<T> &s1, const TStack<T> &s2); template<typename T> class TStack { frien...
Use const_iterator instead of iterator: typename std::vector<T>::const_iterator it; Because s1 is a const object. So s1.items will also be const object as well, which means s1.items.begin() will return const_iterator, not non-const iterator . Better implementation of operator+() You can improve the implementation of...
7,646,318
7,646,389
How to resolve the linker error in C++ compiler
I have to compile PJSIP in CPP compiler. Because I am integrating an API with PJSIP. It is in CPP. So I have to use g++ instead of gcc. But now I didn't integrate any other API. But I am getting linker error in CPP compiler. If it is C compiler, it is working fine. Error: Undefined symbols for architecture arm: "_cry...
Don't compile C source code with a C++ compiler. Just compile it with a C compiler and link it into your C++ program using a C++ linker. Declare all C symbols in an extern "C" block; either wrap your #include directives in such a block, or put it in the headers themselves. (Check whether there's not such a block in th...
7,646,512
7,646,810
Testing if given number is integer
I am trying to implement user defined function which tests if a number is an integer: #include <iostream> #include <typeinfo> using namespace std; bool integer(float k){ if (k==20000) return false;; if (k==(-20000)) return false; if (k==0) return true; if (k<0) return inte...
#include <cmath> bool is_integer(float k) { return std::floor(k) == k; } This solution should work for all possible values of k. I am pretty sure this is a case where you can safely compare floats using ==. Try to thoughtfully name functions. integer does not give any clue what it actually does, so I changed the fu...
7,646,574
7,646,627
Repeated call of copy constructor for same pointer-variable a memory leak?
I have a small question: Foo *myFoo; myFoo = new Foo(anotherFoo); // some deep copy of another object myFoo = new Foo(yetAnotherFoo); // another deep copy of yet another object Is this a memory leak and if yes, how can I avoid it properly? The situation in my program is, that 'myFoo' is a class member and I want ...
Yes, it is a memory leak, because the second assignment to myFoo causes the first Foo you allocated to become inaccessible. Deleting myFoo between successive allocations is the correct thing to do. Note that you don't need to check for a null pointer: delete takes care of that. It looks very likely that you have some p...
7,646,820
7,646,863
Problems with ifdef based inheritance in C++
I was looking at the code of some class I was using, and I came across code like this: #ifdef SOME_OBSCURE_CONDITION class A { #elif class A : public B { #endif Can there be any problems with such code? Specifically, suppose file x.cpp includes y.h and z.h. z.h and y.h both include a.h (which defines class A), but a...
yes, the two variations simultaneously would violate the ODR (One Definition Rule) and may lead to anything ranging from compile errors link errors undefined behaviour (including but not limited to crashing) As long as you can make sure that the SOME_OBSCURE_CONDITION define is globally identical (also across partial...
7,646,967
7,647,006
Is it possible to create an object of a class, inside a class definition, without using default constructor
Is it possible to create an object of a class, inside a class definition, without using default constructor? class Vector3D { public: Vector3D(int x, int y, int z); virtual ~Vector3D(); private: int m_X; int m_y; int m_z; }; class CustomClass { private: Vector3D m_Vec(50,50,50); //error };
Yes, this can be done, but the syntax is different: class Vector3D { public: Vector3D(int x, int y, int z); virtual ~Vector3D(); private: int m_X; int m_y; int m_z; }; class CustomClass { private: Vector3D m_Vec; public: CustomClass(): m_Vec(50,50,50) {} };
7,647,690
7,647,826
Struct linking to linked list
I am new to c++, and am trying to port a program i have made in python to c++. I have a struct that is a linked list with a list of parts. Each of these parts contains one or more components. So i have tried to create two structs, where one struct links to the other struct. But i dont seem to get the list_part to link ...
You have 2 big mistakes in addcomp function, this should work: (also moved some things) void addcomp(char compname[]) { struct component_list *tempcomp; struct component_list *currentcomp; tempcomp = (struct component_list *)malloc(sizeof(struct component_list/*FIX 1*/)); strcpy_s(tempcomp->compname,c...
7,647,958
7,648,143
How to check if the template parameter of the function has a certain type?
Say I have a function with template type T and two other classes A and B. template <typename T> void func(const T & t) { ........... //check if T == A do something ........... //check if T == B do some other thing } How can I do these two checks (without using Boost library)?
If you literally just want a boolean to test whether T == A, then you can use is_same, available in C++11 as std::is_same, or prior to that in TR1 as std::tr1::is_same: const bool T_is_A = std::is_same<T, A>::value; You can trivially write this little class yourself: template <typename, typename> struct is_same { stat...
7,648,150
7,648,208
What will happen when we assign a pointer NULL?
I have a pointer which points to some data. Now I have created a similar pointer. Now this new pointer is assigned to the old one. If i delete the old one what will happen? A* a = new A(); A* b = a; a = NULL; what will happen to both "a" and "b"? Moreover, if I do following things: A* a = new A(); A* b = a; delete a; ...
A* a = new A(); A* b = a; a = NULL; After this, b still points to the object allocated in the first line. a now points to nothing. You can still "use" the object via the b pointer, and you can delete the object via delete b;. You can delete a; here - it will have no effect (since a is NULL), but it is safe and will no...
7,648,465
7,648,527
Default template parameters?
I am currently trying to make an old project in C++ work with more recent tools: the project has been developped on Windows XP with VC71 and I am now trying to make it run on Windows 7 with VC100. I didn't get any "big" problem yet but however I am having a last compilation issue which led me to some code - pretty obsc...
It looks like it's attempting to instantiate a specific instantiation of std::pair. Without more context I can't see why this would be attempted, but you might try just making the macro define to nothing and see if the code compiles, links, and appears to work. They may have changed template compiling in 10.0.
7,648,756
7,648,812
Is the order of iterating through std::map known (and guaranteed by the standard)?
What I mean is - we know that the std::map's elements are sorted according to the keys. So, let's say the keys are integers. If I iterate from std::map::begin() to std::map::end() using a for, does the standard guarantee that I'll iterate consequently through the elements with keys, sorted in ascending order? Example:...
Yes, that's guaranteed. Moreover, *begin() gives you the smallest and *rbegin() the largest element, as determined by the comparison operator, and two key values a and b for which the expression !compare(a,b) && !compare(b,a) is true are considered equal. The default comparison function is std::less<K>. The ordering is...
7,648,820
7,648,850
Codepad.org C++ code gives wrong result
Just a tiny question: Can you tell me what's the issue here in this code ? It should print out 9 but it does 4.8921e-270, however, when uncommenting line 4, it works just fine, too. I don't understand what might be wrong here. Thank you ! Code: double& foo() { double x = 9; double &y = x; //cout << y << "\n"; ...
It is a bad idea to return references/pointers to objects on the stack. They are likely destroyed when you leave the function. Try returning it as per value: double foo() { double x = 9; double &y = x; //cout << y << "\n"; return y; } Now the return value is copied instead of a reference to an object that is p...
7,648,841
7,648,989
Segmentation fault trying to dereference a pointer from a vector of pointers
I have a vector of pointers to objects that I am iterating through using std::vector::iterator`. Since the element returned is itself a pointer I dereference the iterator twice, once to return the pointer and once to resolve the pointer to the actual object. I'm trying to invoke a member function (getClass) that ret...
In my opinion the vector elements are badly initialized. Perhaps you have to test the code that fill the vector independently before testing to extract them. Sorry for my english ;)
7,648,963
7,649,066
Qt Designer and stylesheets
I have derived a CalibrationWindow from QWidget, and I have a vector of CalibrationWindow*. Now, I'm trying to change the background color in the Designer with the following stylesheet: #calibrationWindow { background : rgb(220, 220, 220); } (The Qt object name is calibrationWindow). In the Designer, it looks as ...
Sorry, I was not overriding the paintEvent() function... It's compulsory when subclassing from QWidget.
7,648,979
7,649,199
Proper named temporaries and rvalue-reference/move
Prior to C++11, and as a standard programming idiom, temporaries are often assigned to variables to make the code cleaner. For small types a copy is typically made, and for larger types perhaps a reference, such as: int a = int_func(); T const & obj = obj_func(); some_func( a, obj ); Now, compare this to the inlined f...
Part 1: The compiler is not allowed to implicilty transform obj into a non-const rvalue and thus use a move constructor when calling some_func. Part 2: auto&& obj = obj_func(); This will create a non-const reference to the temporary, but it will not be implicitly moved from when calling some_func because obj is an lva...
7,649,649
7,649,711
What is dynamic type of object
What i think is that dynamic type means dynamically allocated object using new. In the following case, do you say p points to dynamic type or static type of object? In standard, it doesn't say about dynamic type being dynamic object. 1.3.3 - The type of the most derived object (1.8) to which the lvalue denoted by an...
What i think is that dynamic type means dynamically allocated object using new. Nope. The dynamic type is the real type of an object that might be accessed via a reference (pointer included) that point to a base type of its real type. That is, if we have : class A { }; class B : public A { }; B l; A& k = l; He...
7,649,749
7,649,864
What is the proper way to forward declare a pointer to a class for use inside the class declaration?
For example, class Segment { friend bool someFunc( P_Segment p ); }; typedef boost::shared_ptr<Segment> P_Segment; How best to declare P_Segment so this compiles?
In this case you have no choice since you can't forward declare typedefs. You'll have to forward declared the Segment class instead. class Segment; typedef boost::shared_ptr<Segment> P_Segment; class Segment { friend bool someFunc( P_Segment p ); };
7,649,855
7,650,642
Are there any good concurrency/parallelism books out there that are NOT focused on Java?
I want a more C++/Linux oriented book. I do have some basics of multithreading/parallel programming under my belt, but I want to both brush my skills and improve them further.
The reference for pthreads is Programming with POSIX Threads, by David Butenhof; in addition to the specifics of pthreads, it presents a lot of very good information about concurrency in general. It is, however, strictly C, and it doesn't really say much about parallel programming. Still, I'd definitely recommend it....
7,649,944
7,650,075
How do I imitate the Microsoft version of __FUNCTION__ using gcc?
When I use the __FUNCTION__ macro/variable to print out debugging information, there seems to be a difference in what it outputs when using the Microsoft C++ compiler and gcc. For example, using the following trivial code: class Foo { public: void Bar(int a, int b, int c) { printf ("__FUNC...
If you are using it for tracing, you can always use typeid(T).name() and just conditionally compile per platform. Certainly not as convenient as the macro, but it could work. Vaguely similar to __CLASS__ macro in C++
7,650,339
7,653,208
Multichannel audio input using Qt/Phonon
My company is currently working on what could be called an audio analysis program which needs to process to multiple audio inputs (8 or so) in real time. This means that we need a framework that can handle multichannel audio interface devices that have up to 8 input channels. On top of this, the framework should be as ...
Phonon as no input function. it's for playback only if i'm right. but if you want to process input audio you can use QAudioInput. I've used it with just one audio input but I think this constructor with the right QAudioDeviceInfo could do what you want.
7,650,346
7,650,415
C++ Polymorphism of Comparison Operator by Value and by Reference
I want to compare two objects that are derived from the same base type but are not the same derived class. So I made the == operator virtual and over-ride it in derived classes. When I store all of my objects in an array of the base type, the derived implementation is not called, it goes straight to the base implementa...
A aArray[2]; aArray[0] = b1; aArray[1] = b2; When you do that Object Slicing takes place and the derived part of the object just gets stripped off. The objects now stored inside the array now merely behave as objects of the Base class. And naturally, the Base class version of the operator function gets called. ...
7,650,615
7,650,768
Convert time input to a float to enable math functions in C++
I am asking the user to input a start time and an end time in this format: 15.45 (military time with a decimal instead of a colon) and I need to convert those times to a float to perform calculations on them. I am having trouble wrapping my mind around converting the 60 minutes of an hour to a decimal value. e.g. - U...
As soon as one of the values is double, then the arithmetic will be done in double, with double results. So you can convert the minutes to double, using any of the three C++ syntaxes: static_cast<double>(minutes), double(minutes) or (double)minutes, or just divide by 60.0, rather than the integer 60. (I like to be e...
7,650,769
7,650,906
Preferred parameter passing for constructors
Is there a preferred practice for passing constructor parameters? In particular if those constructor parameters are used to initialize member variables. A simplified example. class Example { public: Example( /*type-1*/ str, /*type-2*/ v ): m_str( str ), m_v( v ) { } /* other methods */ private: ...
Option 1: class Example { public: Example( std::string str, const std::complex<float>& v ): m_str( std::move(str) ), m_v( v ) { } /* other methods */ private: std::string m_str; std::complex<float> m_v; }; This has pretty good performance and is easy to code. The one place it falls a litt...
7,650,931
7,651,427
Different templated class in a set using boost::shared_ptr
I have some design problems, I thought one of you might have some clue to help me. I tried to summarize my problem to this simple example : I have two different class DerivedOne and DerivedTwo which inherit from the same Base class and share the definition of a method. I have a set of shared_ptr pointing to client, whi...
The boost shared template pointers wont perform any magic that you can't do without regular pointers (namely putting two different types into the same collection). Whenever using a template you must explicitly declare the template arguments, because alls a template does is generate duplicate code for you at compile tim...
7,650,978
7,653,559
QNetworkReply emits error signal twice when ContentNotFoundError occures when event loop is started in error slot
Im using QtSDK 4.7.3 I am doing this in (void test()): mgr = new QNetworkAccessManager(); reply = mgr->get(QNetworkRequest(QUrl("http://developer.qt.nokia.com/fileNotExisting.txt"))); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(onError(QNetworkReply::NetworkError)), Qt::ConnectionType::UniqueCo...
There is a bug in Qt < 4.8.0: https://bugreports.qt.io/browse/QTBUG-16333 Modifying the connection with a queued one solves the problem: contentnotfound.h: #include <QNetworkAccessManager> #include <QNetworkReply> #include <QMessageBox> class ContentNotFound : public QObject { Q_OBJECT public slots: void test() { ...
7,651,058
7,651,494
Are there versions of the C++ STL's associative data structures optimized for numerous partial copies?
I have a large tree that grows as my algorithm progresses. Each node contains set, which I suppose is implemented as balanced binary search tree. Each node's set shall remain fixed after that node's creation, before its use in creating that node's children. I fear however that copying each set is prohibitively expens...
I know it's not generally productive to suggest a different language, but Haskell's standard container libraries do exactly this. I remember seeing a video (was it Simon Peyton Jones?) talking about this exact problem, and how a Haskell solution ended up being much faster than a C++ solution for the given programmer e...
7,651,243
7,651,296
C++ : Read a file name from the command line and utilize it in my file
How can I read a filename from the command line and utilize it in my C++ code file? ex: ./cppfile inputFilename outputFilename Any help is greatly appreciated!
int main(int argc, char** argv) { string inFile = ""; string outFile = ""; if( argc == 3 ) { inFile = argv[1]; outFile = argv[2]; } else { cout << "Usage: ./cppfile InputFile OutputFile\n"; return 1; } ... }
7,651,322
7,651,446
VBA object-oriented programming
This question is an extension of a previous question: Return an object in VBA Now, I'd like to know how to declare and initialize the object in VBA. It seems like I'd do it like so: Declare Function ConnectMe Lib "C:\Windows\System32\cm.dll" (ByVal Arg1 As String) As ConnectMe Declare Function login Lib "C:\Windows\Sys...
This code is never going to work as it is. If you want to create a class in C++ under Windows and use it in any other programming language that is not C++, (VB for example) the "normal" approach is to create a COM class or an ActiveX control if you need to draw graphics. You may also find this answer in SO helpful.
7,651,566
7,651,820
Template specialization for a range of values
I wish to write a template structure foo such that foo<N>::value_type is the nearest sized integer (rounding up) to N. For example foo<32>::value_type => uint32_t, foo<33>::value_type => uint64_t and foo<72>::value_type => uint64_t. To do this I need an elegant means of providing partial specializations of foo for a r...
template<size_t N> struct select { typedef uint64_t result; }; template<> struct select<0> { typedef uint8_t result; }; template<> struct select<1> { typedef uint16_t result; }; template<> struct select<2> { typedef uint32_t result; }; template<size_t N> struct foo { enum{D = (N > 32 ? 3 : (N > 16 ? 2 : (N > 8 ? 1...
7,651,601
7,651,736
Can I use templates/macros/both to wrap each function of a C++ class?
Suppose I had this. class A { public: int f1(); int f2(); } Is there any way to use templates/macros/both to generate a class that behaves like the following? class GeneratedClass { public: GeneratedClass(InjectedFunction injected_function) { /* store it */ } int f1() { injected_function(); ...
No, templates cannot generate that code for you automatically. You must write it by hand.
7,651,606
7,652,227
Fast set union of integer
I need to make lots of unions of ordered set of integers (I would like to avoid duplicates, but it is okay if there are). This is the code with the best performance so far : // some code added for better understanding std::vector< std::pair<std::string, std::vector<unsigned int> > vec_map; vec_map.push_back(std::make_p...
A custom merge sort may give a tiny amount of help. #include <string> #include <vector> #include <algorithm> #include <map> #include <iostream> #include <climits> typedef std::multimap<std::string, std::vector<unsigned int> > vec_map_type; vec_map_type vec_map; struct comp { bool operator()(const std::string& lhs,...
7,651,671
7,651,729
How can i set an entrypoint for a dll
First i thought entry point in dlls DLLMain but then when i try to import it in C# i get an error that entrypoint wasn't found Here is my code: #include <Windows.h> int Test(int x,int y) { return x+y; } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, ...
In your example, it seems you intend Test() to be an entry point however you aren't exporting it. Even if you begin exporting it, it might not work properly with C++ name "decoration" (mangling). I'd suggest redefining your function as: extern "C" __declspec(dllexport) int Test(int x,int y) The extern "C" component wi...
7,651,738
7,651,898
Handling key events in SDL and C++
I'm in the process of migrating a program from GLUT to SDL. In my current program pressing the a key results in a different response then pressing the A key. This was pretty straightforward to do in GLUT as it the keyboard function callback passed in the ASCII value of the key that was pressed. void keyPressedFn(uns...
Check the keyboard modifiers that are present when you get a keydown event. For example: while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_KEYDOWN: if(event.key.keysym.sym == SDLK_a) { if(event.key.keysym.mod & KMOD_SHIFT) { // Handle 'A' } else { ...
7,651,756
7,651,770
Does malloc() always work to increase the size of an array?
If I use malloc() to increase the size of an array, would that always work, or would I sometimes get a memory error?
It'll "work" if you have enough memory. If you don't have enough memory, then it will not work. Now, when I say "work", it depends what you mean by "work". malloc does not increase the size of anything other than your program's memory usage. Why aren't you using std::vector?
7,651,954
7,651,999
Overloading operator order
Possible Duplicate: Operator Overloading in C++ as int + obj Operator overloading c++-faq I have a Point object with this operator: Point operator +(float other) const { return Point(x + other, y + other, z + other); } I can perform addition like so: point + 10 But I can't perform it in reverse order: 10 + point ...
You normally want to overload the global operator: Point operator+(Point const &a, float b); Point operator+(float a, Point const &b); Instead of two overloads, you may want to use only one overload: Point operator+(Point const &a, Point const &b); and then have a ctor to create a Point from a float: class Point { ...
7,651,992
7,652,023
Dealing with size of stl containers
I'm rewriting a general purpose library that was written by me before I've learned STL. It uses C-style arrays all the way. In many places there is a code like this: unsigned short maxbuffersize; // Maximum possible size of the buffer. Can be set by user. unsigned short buffersize; // Current size of the buffer. T *buf...
I think the default choice ought to be to get rid of both buffersize and maxbuffersize and use buffer.size() and buffer.capacity() throughout. I would advise against caching the sizes unless you have very specific reasons to do this, backed with hard data from profiler runs. Caching would introduce extra complexity and...
7,652,208
7,653,135
Creating a high-performance network server in C++
I need to create a network server in C++ for a trading application. This network server needs to perform the following tasks: handle authentication of clients and provide session id for each session. handle orders originating from the clients and inform clients about their execution. handle other data request asked fo...
You should also look at Apache Thrift (originated at Facebook) or Apache Etch (initially developed by Cisco). They are RPC frameworks that make it easy to develop both servers and clients meeting your needs (more or less). For a framework developed using protobuf and boost.asio, look at the server1 project.
7,652,818
7,653,723
Calling a Oracle procedure with output variables using OCILIB
I have a procedure with the following signature: procedure countryExists(iCountryName in varchar2, oCount out integer) When I run it using OCILIB, I can't get the right value for oCount. If I register it as integer (using OCI_RegisterInt), I get the error: ORA-03116: invalid buffer length passed to a conversion ro...
You're not coding in Java.... Here is the right way to do it : OCI_Connection *cn; OCI_Statement *st; int count; OCI_Initialize(NULL, NULL, OCI_ENV_DEFAULT|OCI_ENV_CONTEXT); cn = OCI_ConnectionCreate("mydb", "myuser", "mypass", OCI_SESSION_DEFAULT); st = OCI_StatementCreate(cn); OCI_Prepare(st, "begin mypackage.cou...
7,652,998
7,653,296
std::string.append("\r\n\r\n") adds c62;9;c62;9; to end of string?
I am trying to append the sentinel ("\r\n\r\n") for an HTTP response to a std::string in C++. However, when I append the data, I get a whole bunch of extra stuff: ^[[?62;9;c^[[?62;9;c[, followed by my programs termination. Then it writes the following to the command line: 62;9;c62;9;c62;9;c62;9;c62;9;c62;9;c. This only...
You are not managing the file data very well. You really should not be storing binary data into a std::string to begin with. It would be better to calculate the file size ahead of time, send the Content-Length header, then read the file contents into a binary buffer and send the buffer as you are reading the file. If...
7,653,455
9,313,526
Is the GTKMM set_value_vfunc function a lie?
I've been attempting to modify the contents of a custom tree view that inherits from TreeModel and TreeSortable. However, the virtual function set_value_impl contains only an assert. When I tried to look for example implementations, they all quote the GTKMM website which says "You can probably just implement this by ...
As covered in the comments above, the set_value_vfunc() function simply does not exist.
7,653,471
7,653,764
Getting app object pointer in Dialog Message Proc
We can use this as the last argument to CreateWindow and get a pointer to the app object in the WndProc like this: if(message == WM_CREATE) { CREATESTRUCT* cs = (CREATESTRUCT*)lParam; pApp = (DemoApp*)cs->lpCreateParams; return 0; } What is the best way to access this pointer in a Dialog Message Proc? Is t...
You get additional initialization data with WM_INITDIALOG, see WM_INITDIALOG message : lParam Additional initialization data. This data is passed to the system as the lParam parameter in a call to the CreateDialogIndirectParam, CreateDialogParam, DialogBoxIndirectParam, or DialogBoxParam function used to create ...
7,653,712
7,653,763
Best Practice for C++ Function Pointers/Callbacks
I'm looking for some guidance in terms of best practices when dealing with custom callbacks or function pointers. I have two main use cases right now. I have a blocking loop inside my class that loops forever. I want an external user to be able to specify a function that gets called on each iteration of that loop. Ex...
I would recommend you use std::function< void() > instead of pointers. Note that this is a TR1 addition to the standard library, you can use Boost implementation of it to work on older implementations. The benefit of it is that it takes any kind of function that takes no arguments and returns something compatible with ...
7,653,736
7,653,762
C++, ignore exception and continue code?
Is there a way allow execution of a bad block of code after an exception of thrown? Presently, my code has an while loop that runs continuously. The code inside this while loop sometimes throws a vector out of range error. I have been unable to track down the cause of this particular exception, but ultimately, it doe...
You just need to catch the exception inside the while loop: while(true) { try { // your code } catch (Exception e) { /* Please, at least do some logging or other error handling here*/ } }
7,653,910
7,653,939
Vector of pairs - left hand side of operand of comma has no effect
I declared a vector a pairs with: vector <pair <int, int> > args; Then I want to push a pair into the vector like this: args.push_back((1,-1)); It tells me that the left-hand operand of comma has no effect. Where do I go wrong?
Say args.push_back(std::make_pair(1,-1));. Or any number of alternatives: // #1 args.push_back(std::pair<int, int>(1,-1)); // #2 typedef std::vector< std::pair<int, int> > pvector; pvector args; args.push_back(pvector::value_type(1,-1)); // #3 typedef std::pair<int, int> intpair; std::vector<intpair> args; args.push_...
7,653,944
7,654,388
overloading >> for a fraction class C++
I'm trying to overload the instream operator >> for a fraction class. I've created a function that can take a string from the user and parse it into the proper arguments for my Fraction class but I'm unsure how to implement this in my >> overloading function. There are three types of fractions that a user can input: 1...
The standard approach would be to break your custom input operation up into constituents: std::istream & operator>>(std::istream & in, Fraction & input) // not const! { std::string token; if (!(in >> token)) { return in; } // error int num, den; const bool res = parse_token(token, num, den); // write this!...
7,654,198
7,654,648
boost test library: Multiple definition error
I'm trying to test a library that I've done (Calculus), in QTCreator for Windows. I've created a main file, and a class in a separate file for the testing. If I compile the example found in http://www.boost.org/doc/libs/1_47_0/libs/test/doc/html/utf/user-guide/test-organization/manual-test-suite.html it works, and so t...
You cannot include #include in multiple files within the same test module. You either need to switch to library or put everything inside single file
7,654,231
7,668,117
Type issues for $$ in Bison
I am having some type issues that I cant seem to get past in bison I have a grammar rule named program and I am trying to use $$ = new Node("Program"); I have the type defined as %type <Node> program, the Node class is defined in a separate header file which is included in the definition section. I get an error error: ...
The header has to be included in the lexer before the .tab.h
7,654,285
7,654,424
Useful features to learn in boost for immediate use
I know this could be seen as subjective off-the-cuff (thus a poor question), but bear with me. Boost has recently become available on the project on which I'm working, and I don't have much experience with it. Boost has so many parts and features that it's hard to know where to get started in learning it - especially s...
format and lexical_cast are great for string manipulation, I find them invaluable. I use them every day. bind is great for ad hoc functors, you'll find it is reused throughout many of the boost libraries. multi_index fills the gap of when you need the same data in two search structures at once, it is very handy at tim...
7,654,358
7,654,544
unexpected exceptions
I am trying to use the following code to test "set_unexpected()". I expect the code will generate an output like: In function f(), throw const char* object Call to my_unexpected Exception in main(): Exception thrown from my_unexpected But I got a run-time error: "This application has requested the Runtime to terminate...
Visual C++ does not implement correctly exception specifications. As stated here, Visual C++ departs from the ANSI Standard in its implementation of exception specifications. and in particular throw(type) - The function can throw an exception of type type. However, in Visual C++ .NET, this is interpreted as throw(.....
7,654,403
7,654,550
Using local Variables in _asm block in C
I am writing a program in 16 bit Turbo C++ version 3.0 based on partial Assembly and C code. I have to use the local variables of C code in assembly block. I have debug the following code in Borland C++ 5 and MS VC++ 6. It works fine but these compilers are 32 bit therefore I have to do this in Turbo C. In Turbo C++ it...
You can't do these most likely because the sizes of the registers and variables don't match (8-bit vs 16-bit): mov al, R mov al, G mov al, B And here the assembler probably expects different syntax: mov cx, X mov dx, Y Try these instead: mov al, byte ptr [R] ; I don't remember if the brackets are required here mov cx...
7,654,688
7,655,113
Why these memory values never change in GDB?
Once again, thank you for the great help so far. The source code: int main() { int a = 20; int b = 10; int c; c = a + b; return 0; } Reading symbols from /home/jwxie/a.out...done. (gdb) start Temporary breakpoint 1 at 0x80483fa: file demoo.cpp, line 3. Starting program: /home/jwxie/a.out Temporary b...
There is no guarantee that variable values, before initialization, will always be the same. Some debuggers will initialize memory to fixed values, e.g. 0xDEADBEEF, some will clear to zero, others will not do anything and you get what was in memory.
7,654,753
7,654,824
Will this lead to a race condition in event-driven programming?
I am writing a small agent-based interaction simulation in a discrete simulator and am beginning to write some code that looks like the following. I have not some event-driven programming before but did not really observe this situation. I am wondering if the following piece of code will lead to a race condition while ...
The answer depends on the implementation of your event transport and is not language agnostic in that sense. In all systems I have worked with, each message would be placed separately into an event queue and the receiving agent would take events off of that queue in order. Assuming you have one thread generating messa...
7,654,814
7,654,832
Is there a way to design two classes that privately manipulate each other's data?
Background: I'm writing a C++ wrapper interface for a C library not written by me. My wrapper classes mimic the library structs, and in this library, some members of struct b point to members of struct a. The documentation for this library says, "Don't destroy a variable of struct a before one of struct b." There are a...
Yes, look into C++ friends. class B; class A { friend class B; // ... }; class B { friend class A; // ... }; The C++ FAQ has a nice explanation of friendship.