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
2,642,131
2,642,176
Ideas for a C/C++ library
I thought one of the best ways to familiarise myself with C/C++, is to make a helpful library. I was maybe thinking like a geometry library, like to calculate areas, surface area, etc. It would be useful in game programming. Or maybe an algebra library, like for different formulas like the distance formula, quadratic f...
If it is for the sake of an exercise, writing a library to deal with fractions is a good one. http://en.wikipedia.org/wiki/Fraction_(mathematics) Implement the basic operations and a way to print them.
2,642,165
2,642,266
Is it okay to implement reference counting through composition?
Most common re-usable reference counted objects use private inheritance to implement re-use. I'm not a huge fan of private inheritance, and I'm curious if this is an acceptable way of handling things: class ReferenceCounter { std::size_t * referenceCount; public: ReferenceCounter() : referenceCount(NULL...
You have to remember to copy the counter when copying the handle. You might prefer not to pass operating system types into templates, but I think safety here requires inheritance. (Not inheritance from HANDLE, though.) HANDLE might also be something of a special case because it's POD. Essentially you have a pointer of ...
2,642,199
2,642,333
Qt/C++ - confused about caller/callee, object ownership
I am creating a GUI to manipulate a robot arm. The location of the arm can be described by 6 floats (describing the positions of the various arm joints. The interface consists of a QGraphicsView with a diagram of the arm (which can be clicked to change the arm position - adjusting the 6 floats). The interface also has...
Except for really simple cases (e.g. a label that shows the value of a slider) my experience has been to stay away from inter-component signal/slot connections inside Qt Designer. Rather, have the component firing the signal of interest connect to a slog defined in the top level QWidget class you're subclassing (i.e. Q...
2,642,242
2,644,641
Displaying a popup widget in QT over application border
Let's say that I have an application frame, and I want to show a popup QCalendarWidget over on the right side of the frame. Normally, QT will clip the edges of the QCalendarWidget, cutting it in half and not displaying the rest, as it would be over the right side border. Is there a way to work around this limitation ...
If you'd show your Calendar, let's say, after a button click, as QDateTimeEditor does, it's contents will not be clipped, cause it do not belong to frame. It will be just a widget, that shows in a dialog manner. And maybe you should even place it in QDialog, that is modal and provides some convenience methods, rather t...
2,642,321
2,642,341
static function in an abstract class
How to implement a static function in an abstract class?? Where do I implement this? class Item{ public: // // Enable (or disable) debug descriptions. When enabled, the String produced // by descrip() includes the minimum width and maximum weight of the Item. // Initially, debugging is disabled. static enable...
First of all, that function needs a return type. I'll assume it's supposed to be void. You implement it in a source file, just as you would implement any other method: void Item::enableDebug(bool toggle) { // Do whatever } There's nothing special about it being static or the Item class being abstract. The only diffe...
2,642,373
2,642,379
converting an int to char*
This is a very very basic question and I know one way is to do the following: char buffer[33]; itoa(aq_width, buffer,10); where aq_width is the int, but then I can't guarantee what size of buffer I would need in order to do this... I can always allocate a very large buffer size, but that wouldn't be very nice... any o...
std::stringstream ss; ss << 3; std::string s = ss.str(); assert(!strcmp("3", s.c_str()));
2,642,385
27,619,955
Throwing a C++ exception after an inline-asm jump
I have some odd self modifying code, but at the root of it is a pretty simple problem: I want to be able to execute a jmp (or a call) and then from that arbitrary point throw an exception and have it caught by the try/catch block that contained the jmp/call. But when I do this (in gcc 4.4.1 x86_64) the exception resu...
If you are using gcc 4.4.7(and above) on x86-64 linux, with dwarf exception handle mechanism (which might be the default one), I have a way to work this out. Suppose your inline assembly code is a function inline_add. It'll call another function add, which might throw a exception. Here's code: extern "C" int add(int a,...
2,642,424
2,642,440
Is VERIFY(...) a good practice in C++ coding?
Also, how does it compare to throwing an exception when something goes wrong ?
VERIFY() serves the same purpose as ASSERT() (or the standard library assert()) - to let you catch things that really shouldn't ever™ be happening (i.e. a true code bug, something that should be fixed before release). The kinds of things that if for some reason the expression is false, there's no point to continuing be...
2,642,509
2,642,525
Removing elements from C++ std::vector
What is the proper way to remove elements from a C++ vector while iterating through it? I am iterating over an array and want to remove some elements that match a certain condition. I've been told that it's a bad thing to modify it during traversal. I guess I should also mention that this is an array of pointers that I...
bool IsEven (int i) { return (i%2) == 0; } //... std::vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.erase(std::remove_if(v.begin(),v.end(),IsEven), v.end()); //v now contains 1 and 3
2,642,511
2,642,538
Is the old vector get cleared? If yes, how and when?
I have the following code: void foo() { vector<double> v(100,1); // line 1 // some code v = vector<double>(200,2); // line 2 // some code } what happened to the vector of size 100 after the second line? Is it gets cleared by itself? If the answer is yes, how and when it is cleared? By the way...
In the assignment, first a temporary vector object is created that contains 200 times the element 2. Then this temporary object is assigned to v: The vector v removes all the elements it currently contains and copies the contents of the temporary vector object. At the end of the statement the temporary vector object is...
2,642,535
2,642,547
Using a constructor for return
Just a quick question. I've written some code that returns a custom class Command, and the code I've written seems to work fine. I was wondering if there are any reasons that I shouldn't be doing it this way. It's something like this: Command Behavior::getCommand () { char input = 'x'; return Command (input, -1, -...
The constructor itself doesn't have a return value. What this does is constructs a temporary Command object and returns the constructed objet to the caller. It's effectively the same as if you said: Command temp(input, -1, -1); return temp; It will work on any C++ compiler.
2,642,579
2,642,600
Who can give me a link for the operator= of vector in MSDN?
Who can give me a link for the operator= of vector in MSDN? Why I can only find operator[]? If operator= is just something default, like copy everything in A to B, how this following code works? vector<double> v(100,1); v = vector<double>(200,2); // if operator= is just a trivail version, how to make sure the old v ...
std::vector is part of the STL, so any description of std::vector will do. The underlying implementation may differ slightly, but all conformant versions of STL must provide the same interface and the same guarantees for std::vector. I can't find in quickly on MSDN, but here are two such descriptions of operator=: htt...
2,642,618
2,642,636
'??' is getting converted into '^' in Visual C++. Why is it happening and what is the way out?
'??' gets converted into '^' if I compile mn VC++ program and run it e.g. sprintf( ch, "??") prints out ^ But if I run the same code in Turbo C/C++, there is no such problem. Why is it happening on VC++ on Windows?
?? alone is not a trigraph, although ??' corresponds to ^. Perhaps you typed it here different from what you have in code and you can't see the trailing single quote in your string because it's too close to the closing quote. So in code you probably have: sprintf( ch, "??'");
2,642,671
2,642,682
C++ compilation error when passing a function into remove_if
So here's a snippet of my code. void RoutingProtocolImpl::removeAllInfinity() { dv.erase(std::remove_if(dv.begin(), dv.end(), hasInfCost), dv.end()); } bool RoutingProtocolImpl::hasInfCost(RoutingProtocolImpl::dv_entry *entry) { if (entry->link_cost == INFINITY_COST) { free(entry); return true; } e...
The problem is that this: bool RoutingProtocolImpl::hasInfCost(...) is a nonstatic member function. It requires an instance of the class to invoke on, ala: obj->hasInfCost(...). However, remove_if cares not and tries to call it as hasInfCost(...). These are incompatible. What you can do is make it static: static bool R...
2,642,691
2,642,702
Call a non member function on an instance before is constructed
I'm writing a class, and this doubt came up. Is this undef. behaviour? On the other hand, I'm not sure its recommended, or if its a good practice. Is it one if I ensure no exceptions to be thrown in the init function? //c.h class C{ float vx,vy; friend void init(C& c); public: C(); }; //c.cpp C::C() { ...
It's completely fine. Once you enter the body of the constructor, all the members have been initialized and they are ready to use. (The body is then to finish up any more work that needs to be done to create a fully constructed object.) But it is poor style. Better is just: C::C() : vx(), vy() // or vx(0), vy(0) if you...
2,642,809
2,642,851
Is there a better way than #if DebugMode for logging
I'm making a c++ library thats going to be P/Invoked from c#, so i am unable to breakpoint/debug the c++ side of things. So i decided to add logging so i can see if anything goes wrong and where it happens. I add a #define DebugMode 1 in order to determine if i am to log or not. First of all i'm not very good at c++ bu...
One simple way is to just define a macro that does nothing if you're not in debug mode. That way you don't have to wrap every call in an #ifdef. A simple implementation might be: #if DebugMode #define MY_LOG(string, ...) printf(string, __VA_ARGS__) #else #define MY_LOG(string, ...) #endif There are other ways and l...
2,642,825
2,644,887
the choice for video capture in Mac OSX?
What is the best choice for webcam video/image capture under Mac OSX with C/C++? It seems that Apple recommended QTKit, but it is a Objective-C library. Any sample code to do the job?
You can use the Objective-C library from your C++ program indirectly. Just create a C interface to the Objective-C functions and compile it with your Objective-C compiler.
2,642,863
2,643,017
C++ boost wave, scoped macro
Is it possible to have scoped macros using custom defined macros through boost wave? I know it should a possible with C++0x however I am working with regular C++. If it is possible, can you provide link or reference how to accomplish this? Thanks
I suspect that Wave doesn't support macro scoping anymore. Older documents such as: http://boost-spirit.com/old_docs/wave_v0_9/preliminary_cpp0x_support.html#macro_scoping Discuss support for macro scoping experimentally, but I can't find any mention of it in the newer docs: http://www.boost.org/doc/libs/1_42_0/lib...
2,642,868
2,642,921
Trying to use boost lambda, but my code won't compile
I am trying to use boost lambda to avoid having to write trivial functors. For example, I want to use the lambda to access a member of a struct or call a method of a class, eg: #include <vector> #include <utility> #include <algorithm> #include <boost/lambda/lambda.hpp> using namespace std; using namespace boost::lambd...
What you want is something akin to: #include <boost/lambda/bind.hpp> // new header // typedefs make code easier typedef pair<int,int> pair_type; typedef vector<pair_type> vector_type; vector_type vp; vp.push_back( make_pair(1,1) ); // don't specify template arguments! vp.push_back( make_pair(3,2) ); // the entire po...
2,643,010
2,643,020
Problem with std::map and std::pair
I have a small program I want to execute to test something #include <map> #include <iostream> using namespace std; struct _pos{ float xi; float xf; bool operator<(_pos& other){ return this->xi < other.xi; } }; struct _val{ float f; }; int main() { ma...
The problem is this: bool operator<(_pos& other) Should be this: bool operator<(const _pos& other) const { // ^^^^ ^^^^^ Without the first const, the right-hand side of the comparison (b in a < b) cannot be const, since without const the function may modify its argument. Without the second c...
2,643,264
2,643,313
Getting memory section information
Can somebody explain me how the following code works? # if defined(__ELF__) # define __SECTION_FLAGS ", \"aw\" , @progbits" /* writable flag needed for ld ".[cd]tors" sections bug workaround) */ # elif defined(__COFF__) # define __SECTION_FLAGS ", \"dr\"" /* untested, may be writable flag needed */ # e...
This isn't actually code executed by the CPU but it's added to the metadata of the object files. It tells the linker to create some global variables (__ctors_begin__ in the example above) in the same section (= part) of the final executable where the constructors are stored (that section is called .ctors). To make it w...
2,643,473
2,643,599
Does std::multiset guarantee insertion order?
I have a std::multiset which stores elements of class A. I have provided my own implementation of operator< for this class. My question is if I insert two equivalent objects into this multiset is their order guaranteed? For example, first I insert a object a1 into the set and then I insert an equivalent object a2 into ...
In C++03 you are not guaranteed that insert and erase preserve relative ordering. However, this is changed in C++0x: n3092, §23.2.4/4: An associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. The set and map classes support unique keys; t...
2,643,837
2,661,920
What strategies are efficient to handle concurrent reads on heterogeneous multi-core architectures?
I am tackling the challenge of using both the capabilities of a 8 core machine and a high-end GPU (Tesla 10). I have one big input file, one thread for each core, and one for the the GPU handling. The Gpu thread, to be efficient, needs a big number of lines from the input, while the Cpu thread needs only one line to pr...
You may not need to lock at all if "1 line per thread" is not a strict requirement and you can go up to 2 lines or three lines sometimes. Then you can split the file equally, based on a formula. Suppose you want to read the file in 1024 kbyte blocks in total (this could be gigabytes too): You split it up to the cores w...
2,643,863
2,643,954
Embed a Python persistance layer into a C++ application - good idea?
say I'm about to write an application with a thin GUI layer, a really fat calculation layer (doing computationally heavy calibrations and other long-running stuff) and fairly simple persistance layer. I'm looking at building the GUI + calculation layer in C++ (using Qt for the gui parts). Now - would it be a crazy idea...
I would go with the 'alternative' approach: Write as much as possible in Python (you can use the GUI bindings PyQt or PySide) and then only write the computationally intensive parts (when proven critical for performance) in C++ (have a look at Boost.Python). Developing in Python should be faster, easier and less error-...
2,643,876
2,644,086
Writing controls like a button in C++\Win32 (not MFC or CLI)?
I have several questions concerning the controls like a button, if You could answer i would be very much pleased. Questions: Is there any way to create a control like a button, but not-standard, i mean, not that strict-rectangled button How do I handle mouse hover events within the control Regards, Galymzhan Sh
It's relatively easy. If you want the same behaviour as a button (click, hover etc etc), then the best bet is to subclass the button control. Have a read of the following MSDN articles: http://msdn.microsoft.com/en-us/library/bb773183.aspx http://msdn.microsoft.com/en-us/library/ms997565.aspx http://msdn.microsoft.com/...
2,643,963
6,124,717
Can I use Win32 FreeType without the .dll file?
I'm teaching myself OpenGL and I'm implementing ttf text rendering using FreeType 2. I downloaded the library from http://gnuwin32.sourceforge.net/packages/freetype.htm and after a couple of minor issues I got it running properly. The thing that's bothering me is that I have to place a copy of freetype6.dll in the di...
Check out this link. See the section Optional: Installing FreeType (by compiling it yourself) Follow the instructions and you'll be good to go.
2,644,979
2,644,988
OpenCL or CUDA Which way to go?
I'm investigating ways of using GPU in order to process streaming data. I had two choices but couldn't decide which way to go? My criterias are as follows: Ease of use (good API) Community and Documentation Performance Future I'll code in C and C++ under linux.
OpenCL interfaced from your production code portable between different graphics hardware limited operations but preprepared shortcuts CUDA separate language (CUDA C) nVidia hardware only almost full control over the code (coding in a C-like language) lot of profiling and debugging tools Bottom line -- OpenCL is por...
2,645,347
2,645,360
Number of digits for N**K
For given integers N and K (1 <= N, K <= 2000000000) you have to find the number of digits of N^K. Is there any formula or something ? Because I tried solving it by simply powering N**K but it's not working for large values and the program simply freezes because of the calculations. I am looking for some fast way maybe...
The 10 base log of N should give you the number of digits in it. This must be enough as a hint :-)
2,645,383
2,645,406
Problem with Initializing Consts
This code, when compiled in xlC 8.0 (on AIX 5.3), produces the wrong result. It should print 12345, but instead prints 804399880. Removing the const in front of result makes the code work correctly. Where is the bug? #include <stdio.h> #include <stdlib.h> #include <string> long int foo(std::string input) { ret...
xlC 10.0 works fine, seems to be a compiler bug
2,645,394
2,753,663
Cannot enter input with gdb. Help!
I've been having a tough time entering input with gdb using XCode or Eclipse. Every time the debugger hits std::cin, it looks like its waiting for input, but fails to accept it. I've scoured the internet for more information, but am having trouble finding anything. What do I need to do to get cin to work with gdb? For...
I guess there is a bug in GCC related to the usage of std::cin and setting/unsetting breakpoints. I did a minimal example: #include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { string option = "x"; while (option != "q") { cout << endl << "0 = Stop" <...
2,645,758
2,645,795
Problem with passing vector of pointers to objects to member function of another object
I have a vector of pointers to Mouse objects called 'mice'. I'm passing the mice to the cat by reference. vector <Mouse*> mice; Cat * c; c->lookForMouse(&mice); And here's my lookForMouse() member function void Cat::lookForMouse(vector <Mouse*> *mice) { ... } And now to the problem! Within the function above, I c...
The problem is that you are not passing a reference, but a pointer. A reference would be passed like an object: c->lookForMouse(mice); and the function taking it would look like this: void Cat::lookForMouse(vector <Mouse*> &mice) Note that containers of dumb pointers are prone to leaking. For example: void f() { ...
2,646,094
2,646,276
Is there a way to serialize automatically enums as int?
Is there a way to serialize enums automatically as int? Every time I define a new enum and write std::stringstream stream; stream << myenum1; stream >> myenum2; the compiler complains that the operators << and >> are not defined. Do you know a way to tell the compiler to treat enums as plain int's? What makes the pro...
You can find out if the type is enum with boost's TypeTraits (is_enum). Then you can combine this with enable_if / disable_if: template <class T> typename boost::disable_if<boost::is_enum<T> >::type serialize(const T&); template <class T> typename boost::enable_if<boost::is_enum<T> >::type serialize(const T&); //use c...
2,646,121
2,646,182
Quaternion Cameras and projectile vectors
In our software we have a camera based on mouse movement, and a quarternion at its heart. We want to fire projectiles from this position, which we can do, however we want to use the camera to aim. The projectile takes a vector which it will add to its position each game frame. How do we acquire such a vector from a giv...
The quaternion doesn't represent a direction, it represents a rotation. You can define a vector that points in the direction that your camera is pointing initially (e.g. (0,0,1)) and transform it using the rotation represented by the quaternion.
2,646,234
2,646,269
How to share a static variable between C++ source files?
I don't know if it is possible to do this, but I have tried several ways and nothing seems to work. Basically I need to access the same static member from several files which include the same class definition. // Filename: S.h class S { public: static int foo; static void change(int new_foo) { foo = n...
This line: int S::foo = 0; needs to be in exactly one source file, not in the header. So move it from S.h to S.cpp.
2,646,304
2,670,516
Is there an API to map 'touch' input to a different monitors?
I am trying to achieve the same functionality as multidigimon.exe, that is mapping an input digitizer to a given monitor, I was wondering if there is an API I can access or if the multidigimon.exe supports any parameters I can call it with to automate the mapping process. So far I have found that multidigimon.exe write...
I did not find an API; however, I think I know how to do it: Find the monitor that you want to map the input to via EnumDisplayDevices, we are interestded in the DeviceID, Find the correct instance of the input device Write to the following registry key: HKLM\SOFTWARE\Microsoft\Wisp\Pen\Digimon key = [you input...
2,646,704
2,647,765
Using Doxygen Correctly
I have been trying to document my C++ project using Doxygen, with little success: Doxygen to fails recognize certain macros, and consequently entire functions are misinterpreted and most of time does not generate docs even though they have special comment blocks. Case in point: /** * \def __MYLIB_FUNCTION_ATTRIBU...
Two things: 1) The Doxygen parser does not "see" the "IN" in doNothing (since it is removed in the preprocessing phase), so the \fn should not include it: const char* doNothing(const char* s). BTW, this \fn is not necessary: Doxygen automatically associates the comment if it is immediately before the documented entity...
2,646,721
2,646,812
Array not returned correctly
I am trying to return a simple array, but I am not getting the correct result. I am getting the following arr1[0] = 1 arr1[1] = 32767 result while the result should have been arr1[0] = 1 arr1[1] = 15 Please suggest. int *sum(int a, int b){ int arr[2]; int *a1; int result = a+b; arr[0]= 1; arr[1]= re...
Try this... #include <vector> #include <iostream> std::vector<int> sum(int a, int b) { std::vector<int> rv(2); rv[0]= 1; rv[1]= a+b; return rv; } int main() { std::vector<int> arr1 = sum(5,10); std::cout << "arr1[0] = " << arr1[0] << std::endl; std::cout << "arr1[1] = " << arr1[1] << std::end...
2,647,052
2,648,150
timing of reads from serial port on windows
I'm trying to implement a protocol over serial port on a windows(xp) machine. The problem is that message synchronization in the protocol is done via a gap in the messages, i.e., x millisecond gap between sent bytes signifies a new message. Now, I don't know if it is even possible to accurately detect this gap. I'm us...
I've had to do something similar in the past. Although the protocol in question did not use any delimiter bytes, it did have a crc and a few fixed value bytes at certain positions so I could speculatively decode the message to determine if it was a complete individual message. It always amazes me when I encounter thes...
2,647,320
2,648,520
struct bitfield max size (C99, C++)
What is maximal bit width for bit struct field? struct i { long long i:127;} Can I define a bit field inside struct, with size of bitfield up to 128 bit, or 256 bit, or larger? There are some extra-wide vector types, like sse2 (128-bit), avx1/avx2 (256-bit), avx-512 (512-bit for next Xeon Phis) registers; and also ext...
C99 §6.7.2.1, paragraph 3: The expression that specifies the width of a bit-field shall be an integer constant expression that has nonnegative value that shall not exceed the number of bits in an object of the type that is specified if the colon and expression are omitted. If the value is zero, the decla...
2,647,362
24,620,652
Is the c-dev@axis.apache.org mailing list, um, dead?
c-dev@axis.apache.org I've successfully subscribed to it, but nobody seems to be answering any questions there.
Technically, no. However, according to the archives, there has been a severe drop off that started around this time (April 2010) and it only broke 100 messages once since then (Dec 2012). So in practical terms, kinda, yeah. Archive stats can be seen here: http://mail-archives.apache.org/mod_mbox/axis-c-dev/
2,647,376
2,647,427
Correct flip/mirror of pixels of an image?
http://tinypic.com/r/fwubzc/5 That shows what a flip should be and what a mirror should be. Code for both types of mirrors: void mirrorLeftRight() { for (int x = 0; x < width/2; x++) { for (int y = 0; y < height; y++) { int temp = pixelData[x][y]; pixelData[x][y]=pixelDat...
The code above seems more like the correct way to Flip, not mirror. Mirror I would guess that you not switch the pixels, but rather copy from one side to the other. With mirror I would guess that you need to change int temp = pixelData[x][y]; pixelData[x][y]=pixelData[width-x][y] pixelData[width-x][y]=temp; to somet...
2,647,429
2,647,446
C++ [Windows] Path to the folder where the executable is located
I need to access some files with fstream in my C++ app on Windows. Those files are all located in subfolders of the folder where my exe file is located. What is the easiest and more important: safest way to get the path to the folder of the current executable?
Use GetModuleFileName to find out where your exe is running from. WCHAR path[MAX_PATH]; GetModuleFileNameW(NULL, path, MAX_PATH); Then strip the exe name from path.
2,647,455
2,647,710
C/C++ library for seekable movie format
I'm doing some processing on some very large video files (often up to 16MP), and I need a way to store these videos in a format that allows seeking to specific frames (rather than to times, like ffmpeg). I was planning on just rolling my own format that concatenates all of the individually zlib compressed frames togeth...
The reason it is hard to seek to a specific frame in most video codecs is that most frames depend on another frame or frames, so frames must be decoded as a group. For this reason, most libraries will only let you seek to the closest I-frame (Intra-frame - independently decodable frame). To actually produce an image ...
2,647,660
2,647,682
Creation of an object in C++
Isn't A a = new A(); // A is a class name supposed to work in C++? I am getting: conversion from 'A*' to non-scalar type 'A' requested Whats wrong with that line of code? This works in Java, right? Also, what is the correct way to create a new object of type A in C++, then?
No, it isn't. The new operation returns a pointer to the newly created object, so you need: A * a = new A(); You will also need to manage the deletion of the object somewhere else in your code: delete a; However, unlike Java, there is normally no need to create objects dynamically in C++, and whenever possible you s...
2,647,796
2,647,825
Syntax for const accessor by reference
Right now my implementation returns the thing by value. The member m_MyObj itself is not const - its value changes depending on what the user selects with a Combo Box. I am no C++ guru, but I want to do this right. If I simply stick a & in front of GetChosenSourceSystem in both decl. and impl., I get one sort of compil...
The returned object will have to be const, so you cant change it from outside; // In header file const MyObj& GetChosenThingy() const; // In Implementation file. const MyObj& MyDlg::GetChosenThingy() const { return m_MyObj; }
2,647,853
2,657,514
How do I forward `<Ctrl>-<Tab>` in Konsole?
I want to use intelligent tabbing in Emacs in C++ mode, but I also want to be able to insert a tab character when necessary. From other posts, I gather that the easiest way is to bind <Ctrl>-<Tab> to indent. However, it appears that Konsole in KUbuntu won't forward the <Ctrl>? My current .emacs file contains: (defun ...
You can use Control-Q (quote, is what I think of in order to remember this), and then press your Tab key, and you'll insert a tab character. You can use Control-Q to insert any character sequence you need to. Hope this helps. :)
2,647,858
2,647,920
Multiplying complex with constant in C++
The following code fails to compile #include <iostream> #include <cmath> #include <complex> using namespace std; int main(void) { const double b=3; complex <double> i(0, 1), comp; comp = b*i; comp = 3*i; return 0; } with error: no match for ‘operator*’ in ‘3 * i’ What is wrong here, why ca...
In the first line: comp = b*i; The compiler calls: template<class T> complex<T> operator*(const T& val, const complex<T>& rhs); Which is instanced as: template<> complex<double> operator*(const double& val, const complex<double>& rhs); In the second case, there is no appropriate template int, so the instancing fails...
2,647,988
2,648,003
Question on breakpoints in VS2010 C++
I'm using VS2010 Ultimate. Having code: //file IntSet.h #include "stdafx.h" #pragma once /*Class representing set of integers*/ template<class T> class IntSet { private: T** myData_; std::size_t mySize_; std::size_t myIndex_; public: #pragma region ctor/dtor explicit IntSet(); virtual ~IntSet(); #pragma endregion ...
If you change the code while the program is running, the code no longer matches what was compiled, so the debugger is (usually) unable to manage breakpoints until the program is stopped and rebuilt with the new source. Under some circumstances, Visual Studio supports edit-and-continue debugging where you can edit a fil...
2,647,999
2,654,638
How to change the toolbar button's Bitmap in win32?
I have created a toolbar with some controls on it using ReBar within a window. Can anyone please tell me, How to get the HWND of a buttons/combobox/etc (not normal buttons in a window) if I know (only) the Id of it ? How to obtain the HBITMAP if I know the id of the resource ? How to set the bitmap to the controlle...
You could download ControlSpy and try it in there to get a feel for it. I checked the Rebar and saw that RB_SETBANDINFO (under Messages) could be what you are looking for.
2,648,086
2,648,111
Out of Core Implementation of a Quadtree
I am trying to build a Quadtree data structure(or let's just say a tree) on the secondary memory(Hard Disk). I have a C++ program to do so and I use fopen to create the files. Also, I am using tesseral coding to store each cell in a file named with its corresponding code to store it on the disk in one directory. The pr...
Whats the errno value of the failed fopen() call? Do you keep the files you have created open? If yes you are most probably exceeding the maximum number of open files per process.
2,648,112
2,648,142
include and using namespace in C++
for using cout, I need to specify both: #include<iostream> and using namespace std; Where is cout defined? in iostream, correct? So, it is that iostream itself is there in namespace std? What is the meaning of both the statements with respect to using cout? I am confused why we need to include them both.
iostream is the name of the file where cout is defined. On the other hand, std is a namespace, equivalent (in some sense) to java's package. cout is an instance defined in the iostream file, inside the std namespace. There could exist another cout instance, in another namespace. So to indicate that you want to use the ...
2,648,163
2,653,046
Accessing a database using visual c++ and OLEDB
Does anybody have an example of working with database using Visual C++ and OLEDB? What should I include on top of my code? I have searched the internet and most examples are using C# or VB. Examples written by C++ are usually not complete. I really appreciate your help. Best, Shadi.
You probably want to use ADO to do this. Writing code directly to OLE DB from C/C++ is a fair bit of work (understatement). If you google for c++ ado, there are a number of hits. The top two are this one on codeguru and one on codersource. They both look like good examples.
2,648,176
2,648,548
Boost MultiIndex - objects or pointers (and how to use them?)?
I'm programming an agent-based simulation and have decided that Boost's MultiIndex is probably the most efficient container for my agents. I'm not a professional programmer, and my background is very spotty. I've two questions: Is it better to have the container contain the agents (of class Host) themselves, or is it...
If Host contains lot of data you could use shared_ptr to avoid copying. You could use MultiIndex with shared_ptr in it: #include <boost/multi_index_container.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/mem_fun.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/shared_ptr.hpp...
2,648,364
2,648,579
How to print a number with a space as thousand separator?
I've got a simple class Currency with overloaded operator<<. I don't know how can i separate the number with spaces every 3 digits, so it looks like: "1 234 567 ISK". #include <cstdlib> #include <iostream> using namespace std; class Currency { int val; char curr[4]; public: Currency(int _val, const c...
This can be done with facets struct myseps : numpunct<char> { /* use space as separator */ char do_thousands_sep() const { return ' '; } /* digits are grouped by 3 digits each */ string do_grouping() const { return "\3"; } }; int main() { std::cout.imbue(std::locale(std::locale(), new myseps)); std:...
2,648,367
2,650,001
DLL dependant on curllib.dll - How can I fix this?
I'm new to developing in C++. I've developed a dll where I'm using curllib to make HTTP requests. When running the dll via depend.exe it notifies me that my dll now depends on the curllib.dll. This simply doesn't work for me. My dll is set as a static library not shared and will be distributed on its own. I cannot rely...
You can compile curl as a lib instead of a dll by opening the solution file in visual studio and changing the build project to "lib release". Thus you wont need the dll at all and you can just include the lib in the linker.
2,648,382
2,664,524
How to determine if a C++ usertype has been registered with tolua
We use tolua++ to generate Lua bindings for C++ classes. Assume I have a C++ class: class Foo { //Some methods in Foo, irrelevant to question. }; and a tolua .pkg file with the following contents class Foo { }; Consider the following function: void call_some_lua_function(lua_State* luaState) { Foo* myFoo = ne...
I am using tolua, not tolua++, but let's hope it is somehow similar. In tolua, you can test if the class is registered with it like this: tolua_getmetatable(L, "ClassName"); if (lua_isnil(L, -1)) { // the class wasn't found } Hint: check how tolua.cast is implemented and checks its arguments. It takes a type name a...
2,648,396
2,649,565
Methods for implementing and using graphs of nodes in C++?
I am working on a research project that deals with social networks. I have done most of the backbone of the program in C++ and am now wanting to implement a way to create the graph of nodes and the connections as well as a way to visualize the connections between people. I have looked a little into Lemon and the Boost ...
If you use the BGL then you should also be able to make use of the Graph Toolkit for Algorithms and Drawings (GTAD). The GTAD is meant to be compatible with BGL and adds a number of graph algorithms not in BGL as well as algorithms for layouts. For visualization the BGL allows you to read and write some common graph fi...
2,648,559
2,655,029
C++: Need to make an HTTP request from a dll - where do I start?
I've tried using curllib, but find my dll becomes dependent on curllib.dll. Is there another method I can investigate and use? I simply want to make a request to a web page. My dll has to be independant so it can be distributed on its own. Thanks
For anyone in a similar situation I managed to compile the libcurl visual studio project in the latest curl distribution with Runtime library set to Multi-threaded dll. I think I left everything else the same apart from the output files (debug/release respectfully). Once the lib compiled with my dll I noticed now my dl...
2,648,562
2,648,868
How to output floating point numbers with a custom output format in C++?
The problem is that I want to output Mathematica compatible floating point numbers. The only difference with the standard IOStream or printf output format is that the exponential e is replaced by *^: Standard C/C++ output format: 1.23e-4 Mathematica format: 1.23*^-4 Is there a way to manipulate streams to achieve this...
Your idea should work out easily: std::string FloatToStringMathematica(float x) { std::stringstream a; a << x; std::string u = a.str(); size_t pos = u.find("e"); if(pos != std::string::npos) { u.replace(p, 1, "*^"); } return u; }
2,648,577
2,653,041
What is the difference between Inversion of Control and Dependency injection in C++?
I've been reading recently about DI and IoC in C++. I am a little confused (even after reading related questions here on SO) and was hoping for some clarification. It seems to me that being familiar with the STL and Boost leads to use of dependency injection quite a bit. For example, let's say I made a function that fo...
Inversion of Control is a very generic concept, with different meanings depending on the sort of "control" you're talking about. Dependency injection is a specific form. Inversion of Control and iteration In this case "control" means "flow control". I think your first example involving iteration is not really inversion...
2,648,756
2,648,865
From Java Object class to C++
I'm relative new to C++ and my background is in Java. I have to port some code from Java to C++ and some doubts came up relative to the Object Java's class. So, if I want to port this: void setInputParameter(String name, Object object) { ..... } I believe I should use void* type or templates right? I don't know what's...
It depends what you want to do with object. If you use a template, then any methods you call on object will be bound at compile time to objects type. This is type safe, and preferable, as any invalid use of the object will be flagged as compiler errors. You could also pass a void * and cast it to the desired type, ass...
2,648,802
2,649,916
At what point is it worth using a database?
I have a question relating to databases and at what point is worth diving into one. I am primarily an embedded engineer, but I am writing an application using Qt to interface with our controller. We are at an odd point where we have enough data that it would be feasible to implement a database (around 700+ items and ...
A database is worthwhile when: Your application evolves to some form of data driven execution. You're spending time designing and developing external data storage structures. Sharing data between applications or organizations (including individual people) The data is no longer short and simple. Data Duplication Evo...
2,648,877
2,653,123
JNI Stream binary data from C++ to Java
I need help passing binary data into Java. I'm trying to use jbytearray but when the data gets into Java it appears corrupt. Can somebody give me a hand? Here's a snip of some example code. First the native C++ side: printf("Building audio array copy\n"); jbyteArray rawAudioCopy = env->NewByteArray(10); jbyte toCopy[10...
After fixing my above mistake I'm now looking for the most efficient way of copying raw byte arrays back into Java. What I have above seems a little less than ideal since I'm planning on supporting a high number of repeat copies. I experimented with passing the char array directly to the setByteArrayRegion call which a...
2,648,878
2,648,912
Range-based for statement definition redundancy
Looking at n3092, in §6.5.4 we find the equivalency for a range-based for loop. It then goes on to say what __begin and __end are equal to. It differentiates between arrays and other types, and I find this redundant (aka confusing). It says for arrays types that __begin and __end are what you expect: a pointer to the f...
This avoids a corner-case with ADL: namespace other { struct T {}; int begin(T*) { return 42; } } other::T a[3]; for (auto v : a) {} Because ADL finds other::begin when calling begin(a), the equivalent code would break causing a confusing compile error (along the lines of "can't compare int to other::T*" as end(a...
2,649,056
3,781,180
How to write a browser plugin?
I'm curious as to the procedure for writing browser plugins for browsers like Chrome, Safari, and Opera. I'm thinking specifically of Windows here and would prefer working with C++. Are there any tools or tutorials that detail the process? Note: I am not referring to extensions or 'addons'. I'm referring to a plugin ...
As others point out, plugins for those browser are written using the NPAPI. Note: Both Firefox and Chrome will default most plugins to click-to-play soon, with Chrome planning to phase out NPAPI entirely. NPAPI for new projects is discouraged at this point. Resources for getting started with NPAPI: MDC plugin section ...
2,649,068
2,649,576
Has anyone found the need to declare the return parameter of a copy assignment operator const?
The copy assignment operator has the usual signature: my_class & operator = (my_class const & rhs); Does the following signature have any practical use? my_class const & operator = (my_class const & rhs); You can only define one or the other, but not both.
The principle reason to make the return type of copy-assignment a non-const reference is that it is a requirement for "Assignable" in the standard. If you make the return type a const reference then your class won't meet the requirements for use in any of the standard library containers.
2,649,122
2,649,362
Problem in Building mplsh-run in lshkit
been trying out this for quite some time but I'm still unable to built mplsh-run from lshkit Not sure if this would help to explain my situation during the building process /tmp/cc17kth4.o: In function `lshkit::MultiProbeLshRecallTable::reset(lshkit::MultiProbeLshModel, unsigned int, double, double)': mplsh-run.cpp:...
Put the .cpp file as the first argument. g++ mplsh-run.cpp -I./lshkit/include -lm -lgsl -lgslcblas -lboost_program_options-mt Also try with different permutations of -lm -lgsl and -lgslcblas
2,649,207
2,649,276
Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)?
It seems that a lot of people include example.h instead of cexample in their C++ code. I know that everything in the C++ versions is declared in namespace std, but I'm not aware of any other differences. So why do people use the C headers, and is it okay to do so?
The difference between the two is that the C headers that C++ imported (by prefixing with c and removing the .h suffix) are in namespace std. This so any call or use of a standard facility is prefixed with std::, for uniformity. It's The Standard Way Of Doing Things(tm). Unless of course you already have a bunch of C c...
2,649,334
2,649,430
Difference between static and shared libraries?
What is the difference between static and shared libraries? I use Eclipse and there are several project types including Static Libraries and Shared Libraries? Does one have an advantage over the other?
Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library. Static libraries are .a (or in Window...
2,649,461
2,666,646
Why can't my c++ program find the necessary .dll file?
I am trying to use OpenCV (a computer vision library), which appearently uses a few .dll files, located in C:\OpenCV\bin (which has been added to the system PATH variable). However, if I try to run a simple test program, it gives a system error: The program can't start because highgui.dll is missing from your compute...
I tracked down the executable that was built by Netbeans before running and launched it, and it gave no errors (so Netbeans probably uses its own paths for executing), so tried to find out how I could make Netbeans search the right paths for the DLLs, and after adding an environment variable PATH=C:/OpenCV2.1/bin (Proj...
2,649,634
2,649,688
'dxerr9.h': No such file or directory
I am trying to compile a program I took off a cd from a book that uses directx to render 3d objects. when i press compile I get the following error C1083: Cannot open include file: 'dxerr9.h': No such file or directory I am using VC++ 2008 Express Edition and i am running off of Vista. I went to the following folder ...
It seems your program was written using older version of DirectX SDK. The 'dxerr9.h' is present at least in "Microsoft DirectX 9.0 SDK (December 2004)", but is absent at least in "Microsoft DirectX SDK (August 2009)".
2,649,653
2,649,691
Change an array's value in x86 assembly (embedded in C++)
I am messing around with assembly for the first time, and can't seem to change the index values of an array. Here's the method I am working on int ascending_sort( char arrayOfLetters[], int arraySize ) { char temp; __asm { //??? } } And these are what I tried mov temp, 'X' mov al, temp mov arrayOfL...
The arrayOfLetters value is equivalent to a pointer. So, your assembly code might need to be: mov temp, 'X' mov al, temp mov edx, arrayOfLetters mov [edx], al In the above code, edx is loaded with the address of arrayOfLetters. Then the last instruction stores the al byte into the address pointed to by edx.
2,649,674
2,649,831
How do I use texture-mapping in a simple ray tracer?
I am attempting to add features to a ray tracer in C++. Namely, I am trying to add texture mapping to the spheres. For simplicity, I am using an array to store the texture data. I obtained the texture data by using a hex editor and copying the correct byte values into an array in my code. This was just for my testing p...
It could be that the texture is just washed out because the light is so bright and so close. Notice how in the solid red case, there doesn't seem to be any gradation around the sphere. The red looks like it's saturated. Your u,v mapping looks right, but there could be a mistake there. I'd add some assert statements ...
2,649,676
2,650,431
C++ Win32 API equivalent of CultureInfo.TwoLetterISOLanguageName
The .NET framework makes it easy to get information about various locales; the Win32 C++ APIs are a bit harder to figure out. Is there an equivalent function in Win32 to get the two-letter ISO language name given an integer locale ID? In C# I'd do: System.Globalization.CultureInfo ci = new System.Globalization.CultureI...
Thanks to Trevor for directing me toward this answer in an earlier reply. Call GetLocaleInfo with the LOCALE_SISO639LANGNAME parameter.
2,649,717
2,649,761
C++ function for picking from a list where each element has a distinct probability
I have an array of structs and one of the fields in the struct is a float. I want to pick one of the structs where the probability of picking it is relative to the value of the float. ie struct s{ float probability; ... } s sArray[50]; What is the fastest way to decide which s to pick? Is there a function for ...
float p = (rand() / static_cast<float>(RAND_MAX)) * total_probability; s* current = &sArray[0]; while ( (p -= current->probability) > 0) ++current; // `current` now points to your chosen target
2,650,034
2,650,141
How to use mmap to point to STL type?
I have a mmap typecast to a char pointer char *ptr; ptr = (char *)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); This was my earlier code. But now I want to use a map instead of char * as the requirements changed. Now, my map is declared as map < int, string > i_s_map; How do I change my mmap call to poi...
You don't want to store STL containers in shared memory, at least not share them. The reason is that they rely heavily on heap allocation, so out-of-the-box std::map will hold pointers from virtual address space of a different process. Take a look at boost::interprocess for a way to deal with this situation in C++.
2,650,183
2,650,217
Use auto_ptr in VC6 dll cause crash
// dll #include <memory> __declspec(dllexport) std::auto_ptr<int> get(); __declspec(dllexport) std::auto_ptr<int> get() { return std::auto_ptr<int>(new int()); } // exe #include <iostream> #include <memory> __declspec(dllimport) std::auto_ptr<int> get(); int main() { { std::auto_ptr<int> x = get()...
A DLL has its own heap, so you have to make sure you new and delete from the same context.
2,650,196
2,650,253
Port Win32 DLL hook to Linux
I have a program (NWShader) which hooks into a second program's OpenGL calls (NWN) to do post-processing effects and whatnot. NWShader was originally built for Windows, generally modern versions (win32), and uses both DLL exports (to get Windows to load it and grab some OpenGL functions) and Detours (to hook into othe...
The library preloading can be done through LD_PRELOAD. From there you want to look at the dlopen and dlsym calls to get at the actual functions in the original library. This is all if you want to do things by hand. You can also look at modifying ltrace in a way such that you provide the functions to hook (via the -e fl...
2,650,244
2,650,251
formatting an integer output using ostream
I am trying to find the equivalence of %2d using cout << <<endl format. how can I do that?
The header <iomanip> contains the stream manipuator setw: cout << setw(2) << myint << endl You may also be interested in setfill: cout << setfill('0') << setw(2) << myint << endl will pad with a 0 instead of a space.
2,650,345
2,650,569
ImageMagick vs. Cairo on Vector Graphics rasterization
I am working on a project that needs rasterizing of drawings into image files. I have already got it work using GDI+. Wanting to create a portable solution, I am also looking into other solutions and found two - cairo and imagemagick. I am new to both, but it seems that ImageMagick can do almost all the stuff - drawing...
Cairo by itself can't do very much in the way of bitmap manipulation - at least in the sense that ImageMagick can. It is, however, a very powerful vector imaging library, and can do almost everything that GDI+ can do, up to the point where it's practically a suitable replacement for DirectDraw 2D. It can also produce a...
2,650,374
2,650,432
c++ Initializing a struct with an array as a member
Edited again because it originally wasn't clear that I'm trying to initialize the arrays at compile time, not at run time... I've got the following reduced testcase: typedef struct TestStruct { int length; int values[]; }; TestStruct t = {3, {0, 1, 2}}; TestStruct t2 = {4, {0, 1, 2, 3}}; int main() { ret...
c++ doesn't have the same flexible array member as last element as c99. You should use a std::vector if you don't know how many elements or you should specify how many if you do. EDIT: You have said in your edit that the array is a runtime constant, so specify the size and it should work fine. g++ has no problem with t...
2,650,614
2,650,792
How to use/manipulate return value from nested boost::bind
I have two functions: 1. A & DataSource(); 2. void DataConsumer( A * ); What I want to achieve: Using one statement to assemble them into one functor. I have tried: 1. boost::function< void()> func( boost::bind( DataConsumer, & boost::bind( DataSource ) ) ); certainly it didn't work, compiler says it can not convert 'b...
guys, I just found the answer, like following: boost::function< void()> func( boost::bind( DataConsumer, boost::bind( boost::addressof< A >, boost::bind< A& >( DataSource ) ) ) ); The theory should be: since we call DataSource later, we need a functor that u...
2,650,634
2,650,690
void foo(int &x) -> Ruby? Passing integers by reference?
as a way to spice up my C++ programming homework, I've decided to instead of typing the C++ from the book onto my computer, instead reforming it in Ruby. Yes it's a bit silly, but I'm bored. Anyway, I'm having trouble converting this kind of function to Ruby void swap(int &a,int &b){ int c=b; b=a; a=c } What wo...
Ruby is strictly pass-by-value. Always. But sometimes those values are poointers. Here's a couple of links: Java is Pass-by-Value, Dammit! (Scott "JavaDude" Stanchfield) Parameter passing in Java (Jon Skeet) Does Java pass by reference? Java, pass-by-value, reference variables Note that while all of these say "Java",...
2,650,644
2,651,014
Why does forward declaration not work with classes?
int main() { B bb; //does not compile (neither does class B bb;) C cc; //does not compile struct t tt; //compiles class B {}; //HERE is the class B defination struct s { struct t * pt; }; //compiles s...
Forward declaration works for classes, but other then you have expected. First, you have to write class B; before the code of your main routine. Then you have to write B * bb; instead of B bb;. You can construct an object of type B only after class definition. The reason for this behavior is as follows: The compiler do...
2,650,663
2,650,679
Possible to convert list of #defines into strings
Suppose I have a list of #defines in a header file for an external library. These #defines represent error codes returned from functions. I want to write a conversion function that can take as an input an error code and return as an output a string literal representing the actual #define name. As an example, if I have ...
I normally do it the giant switch case way, although I make it somewhat easier with: #define STR(code) case code: return #code switch (errorCode) { STR(NO_ERROR); STR(ONE_KIND_OF_ERROR); } This is a good question, I'm interested to see what better ways people have
2,650,800
2,650,978
Use one single DLL library to import other libraries at runtime
I am writing a Win32 DLL library that can be redistributed. I am using different versions of the windows API because I want to support Windows 7 functions, but still have support for Windows 2000 (with some function disabled). What I have currently is MyLib2000.dll, MyLibXP.dll, and MyLibVista.dll, and my application c...
Use delayloading and implement the dliNotePreLoadLibrary notification hook to load the correct version of your DLL. The linker-provided delay load logic will then pull in all the functions from whichever DLL you loaded. http://msdn.microsoft.com/en-us/library/z9h1h6ty(v=VS.100).aspx Or use delay-loading and implement ...
2,650,816
2,650,833
C++: Should I use strings or char arrays, in general?
I'm a bit fuzzy on the basic ways in which programmers code differently in C and C++. One thing in particular is the usage of strings in C++ over char arrays, or vice versa. So, should I use strings or char arrays, in general, and why?
In C++ you should in almost all cases use std::string instead of a raw char array. std::string manages the underlying memory for you, which is by itself a good enough reason to prefer it. It also provides a much easier to use and more readable interface for common string operations, e.g. equality testing, concatenati...
2,650,893
2,651,406
What are good RPC frameworks between a Java server and C++ clients?
I am looking for a RPC stack that can be used between a Java Server and C++ clients. My requirements are: Ease of integration (for both C++ and Java) Performance, especially number of concurrent connections and response time. Payload are mostly binaries (8-100kb) I found some like: http://code.google.com/p/protobuf...
Thrift might be worth investigating.
2,651,062
2,651,089
friendship and operator overloading help
I have the following class #ifndef Container_H #define Container_H #include <iostream> using namespace std; class Container{ friend bool operator==(const Container &rhs,const Container &lhs); public: void display(ostream & out) const; private: int sizeC; // size of Container int capaci...
When you declare a function as a friend inside of a class, the function is a non-member function and is as if it was declared in the enclosing namespace. So, in your case, your declaration of a friend operator==, class Container { friend bool operator==(const Container &rhs,const Container &lhs); }; is a non-memb...
2,651,101
3,565,124
C/C++-Library for EEPROM wear-leveling under Linux?
does anybody know of a library for storing data securely in an 8k-EEPROM, which is attached over the I2C-interface? I am especially interested in wear-leveling as I have a write-intensive application where the EEPROM should/must be used as a NVRAM for often-chaning measurement data. Thanks in advance, Martin
The only wear levelling code I've ever come across is in the MTD drivers in the kernel - either in the old JFFS2 filesystem or in the UBI level. These are designed for much larger FLASH devices, with correspondingly larger block sizes (typically 64KB). However, you might get some idea from the code (e.g. see drivers/mt...
2,651,170
2,651,349
Immutable classes in C++
In one of my projects, I have some classes that represent entities that cannot change once created, aka. immutable classes. Example : A class RSAKey that represent a RSA key which only has const methods. There is no point changing the existing instance: if you need another one, you just create one. My objects sometimes...
Looks good to me. Marking every object const from the factory obviates marking every data member const, but in this example there is only one anyway.
2,651,586
2,651,658
boost::dynamic_pointer_cast with const pointer not working?
Let's say I have two classes, A and B, where B is a child class of A. I also have the following function: void foo(boost::shared_ptr<const A> a) { boost::shared_ptr<const B> b = boost::dynamic_pointer_cast<const B>(a); // Error ! } Compilation with gcc gives me the following errors: C:\Boost\include/boost/smart_pt...
dynamic_pointer_cast uses the C++ dynamic_cast internally and dynamic_cast requires your classes to have at least one virtual method. No virtual methods means no vtable and without vtable dynamic_cast would not be able to figure which casts are doable at run-time.
2,651,598
2,651,621
Finding the left-most and right-most points of a list. std::find_if the right way to go?
I have a list of Point objects, (each one with x,y properties) and would like to find the left-most and right-most points. I've been trying to do it with find_if, but i'm not sure its the way to go, because i can't seem to pass a comparator instance. Is find_if the way to go? Seems not. So, is there an algorithm in <al...
Use std::min_element and std::max_element instead. list<Point>::iterator left = std::min_element(points.begin(), points.end(), left); list<Point>::iterator right = std::max_element(points.begin(), points.end(), left); I would also change the signature of left to: bool left(const Point& p1, const Point& p2)
2,651,663
2,652,420
C++: Binding to a base class
EDIT: In the following code container::push takes an object of type T that derives from base as argument and stores in a vector a pointer to the method bool T::test(). container::call calls each of the stored methods in the context of to the member object p, which has type base, not T. It works as long as the called me...
To the updated question: Calling a derived member function on a base object is Undefined Behavior. What you are trying to achieve (code) is wrong. Try to post what you need and people will help with a sensible design.
2,651,730
2,651,745
Equivalent for Java's System.getProperty("java.io.tmpdir") in C?
As the title says, the java.io.tmpdir property in Java is really nice, and I can't find an equivalent for C. I'm writing for Windows and in Visual Studio. I don't want to just use something like C:\Temp because in later versions of windows the appropriate directory could be something like C:\Users\[UserName]\AppData\Lo...
If you're using the Win32 API, you can use GetTempPath().
2,651,850
2,651,859
Can func get the lineno who call itself? (C/C++)
I've a problem , as the following code discribe itself. 1 #include<stdlib.h> 2 #include<stdio.h> 3 void log() 4 { 5 printf("Log [Line:%d]\n",__LINE__); 6 } 7 int main() 8 { 9 log(); 10 log(); 11 } The expected result is Log [Line:9] Log [Line:10] But, the fact is Log [Line:5] Log [Li...
You need to write a macro: #define LOG printf("Log [Line:%d]\n",__LINE__) then use it: int main() { LOG; LOG; } This works because the macro is expanded at its point of use, giving the __LINE__ macro the correct value.
2,651,896
2,651,919
Why doesn't free(p) set p to NULL?
Any reasons why this can not be standard behavior of free()? multiple pointers pointing to the same object: #include <stdlib.h> #include <stdio.h> void safefree(void*& p) { free(p); p = NULL; } int main() { int *p = (int *)malloc(sizeof(int)); *p = 1234; int*& p2 = p; printf("p=%p p2=%p\n", p, p2)...
If it did, you would have to pass a pointer to a pointer to the function: int * p = malloc( sizeof( int )); free( & p ); which I'm sure many people would get wrong.
2,652,034
2,656,438
A simple hello world NPAPI plugin for Google Chrome?
I am trying to make a chrome plugin but Chrome API doesn't give me enough power. I want to use NPAPI but I have no idea how to use it but I do have experience in Visual C++. Can someone show me a 'Hello world' in C++ application so I can get started?
Note: Both Firefox and Chrome will default most plugins to click-to-play soon, with Chrome planning to phase out NPAPI entirely. NPAPI for new projects is discouraged at this point. NPAPI plugins shouldn't be browser specific (at least as far as possible). Seamonkeys npruntime sample can be considered a basic Hello Wor...
2,652,037
3,132,134
How to get the quickfix timestamp?
I've seen in quickfix doxygen documentation that it generates an utc timestamp as soon as it has received a FIX message from a socket file. Have a look in ThreadedSocketConnection::processStream(), it calls then m_pSession->next( msg, UtcTimeStamp() ); I would like to get that timestamp, because I need it to screen n...
FIX::SendingTime st; message.getHeader().getField(st); Try this out.
2,652,164
2,652,639
Compile time Meta-programming, with string literals
I'm writing some code which could really do with some simple compile time metaprogramming. It is common practise to use empty-struct tags as compile time symbols. I need to decorate the tags with some run-time config elements. static variables seem the only way to go (to enable meta-programming), however static variabl...
I've finally understood what the problem was... and your solution does not solve much, if any. The goal of using local static variable is to provide initialization on first use, thus being safe from the "Initialization Order Fiasco" (by the way, it does not solve the "Destruction Order Fiasco"). But with your design, i...