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,319,772 | 2,319,836 | What is the preference of function/method/template name resolving in C++? | How does the C++ compiler decide which function/method to call if there are multiple possibilities?
In my specific case I have the standard free function of the C++ Run time and I also have a templated free variant, like this:
// The definitions of the C++ Run Time Library (from memory.h)
extern malloc(size_t s);
exter... | Overload resolution is quite complicated in general.
In your case, it is quite easy: a function template is not considered if there is an exact match. For free it is the case (the standard free takes a void*), for malloc it isn't (the standard malloc takes a size_t, you are passing an int and size_t can't be a typedef... |
2,319,924 | 2,319,962 | What is process and thread? | Yes, I have read many materials related to operating system. And I am still reading. But it seems all of them are describing the process and thread in a "abstract" way, which makes a lot of high level elabration on their behavior and logic orgnization. I am wondering what are they physically? In my opinion, they are ju... | Normally when you run an executable like notepad.exe, this creates a single process. These process could spawn other processes, but in most cases there is a single process for each executable that you run. Within the process, there can be many threads. Usually at first there is one thread, which usually starts at th... |
2,319,927 | 2,320,055 | How can I define a "Do-Nothing" sort? | I'm working on a system where I need to be able to sort a vector by a given predicate, which my classes shouldn't have control over. Basically, I pass them a derived class and they blindly sort on it.
As one of the "delightful quirks", one of the sort patterns is order of entry.
Here's what I've got so far.
struct Stra... | Personally, I think your strategy class should have a "sort" method. That way, it can either call std::sort or not, as it sees fit. Whether as well as how becomes part of the sorting strategy.
Darios stable_sort answer is very good, if you can use it.
It is possible to do sorting based on item position in a vector, but... |
2,320,105 | 2,320,120 | Tracking down the origin of a VS2k8 error message? | I have several maps containing a multitude of classes in my VC++ project, some of them default constructable, others not. When trying to build, I get a "no appropriate default constructor available" error. The problem is that the error is listed to occur in line 173 of map.cpp, which is the code for operator[]. It woul... | You're probably looking inside the error list window. Which I don't use that often for C++ projects.
Go to the output window and check a little further down, you should be able to double click the line that will bring you to the type in question.
Doing a search for : error inside the output window is very common fo... |
2,320,426 | 2,320,450 | Errors while compiling a test program using Qt | I am pretty new to C++/Qt
I am following the book 'C++ GUI Programming with Qt 4' by Jasmin Blanchette and Mark Summerfield.
I was working on an example program and got stuck up with some compilation errors which I was not able to resolve. Code and Errors below. Any help is appreciated.
Thanks.
finddialog.h
#ifndef FIND... | You should inherit publically from QWidget or QDialog:
class FindDialog : public QDialog {
// ...
show() is actually implemented by a base of FindDialog, QWidget - but you are not inheriting publically from it and thus can't access it.
Inheritance for classes is by default private, i.e.
class A : B {};
and... |
2,320,433 | 2,320,605 | Why is my DCOM client locking on a call to SendMessage? | Running on XP. I have a client that calls calls CoInitializeEx(NULL, COINIT_MULTITHREADED), loads a (local) DCOM object, and attaches an event interface so the DCOM object can send back events. The client looks a lot like notepad with a multi-line textbox covering the client area to display event messages. Here are the... | It would appear that the window was created by the main thread. So that is the only thread that can call the window proc. When you SendMessage from the other thread, what it actually does it to put the message into the main thread's queue and then wait for the main thread to call GetMessage or PeekMessage. Inside th... |
2,320,595 | 2,320,726 | Finding the spread of each cluster from Kmeans | I'm trying to detect how well an input vector fits a given cluster centre. I can find the best match quite easily (the centre with the minimum euclidean distance to the input vector is the best), however, I now need to work how good a match that is.
To do this I need to find the spread (standard deviation?) of the vect... | Use the distance function and calculate the distance from your center point to each labeled point, then figure out the mean of those distances. That should give you the standard deviation.
|
2,320,665 | 2,320,758 | What are custom calling conventions? | What are these? And how am I affected by these as a developer?
Related:
What are the different calling conventions in C/C++ and what do each mean?
| A calling convention describes how something may call another function. This requires parameters and state to be passed to the other function, so that it can execute and return control correctly. The way in which this is done has to be standardized and specified, so that the compiler knows how to order parameters for c... |
2,320,846 | 2,320,912 | Find if QTreeWidgetItem is top level | Is there a way I can find out if the QTreeWidgetItem I'm looking at is top level or not? I have a program crashing when I try to take the text of a parent if the item is top level (no parent).
| Quoting the documentation:
The main difference between top-level
items and those in lower levels of the
tree is that a top-level item has no
parent(). This information can be used
to tell the difference between items,
and is useful to know when inserting
and removing items from the tree.
if (!node.parent(... |
2,320,847 | 2,320,876 | Class design suggestions: extending a class and code reuse | The gist of this question is about extending a class, minimizing jam-packing everything into a single class, and maximizing code re-use. After reading this question, please feel free to edit the title or description to make it more succinct. Though the post looks long, I am just trying to be thorough by using a lot of ... | Especially if the methods are specific to your departments use of the class you should implement them as in: Create a single Helper class, with all the methods inside.
There are several reasons for this:
The single helper class can be
located in another logical project
structure
If your new methods don't require acce... |
2,320,901 | 2,321,005 | Design Question: How can I maintain a stack of object | I have a struct call 'A', which has an attribute 'i', like this:
typedef struct a {
a() { i = 0;}
int i;
} A;
And I would like to maintain a stack of A in my Main class:
class Main {
public:
void save();
void doSomethingToModifyCurrentA();
void restore();
private:
A currentA;
... | You don't need to do anything to reserve memory on the stack. The underlying container (deque by default) manages memory for you.
The three important methods are...
mystack.push (myvalue);
mystack.top ();
mystack.pop ();
The pop doesn't read the top value - just discards it. The top method returns a reference to the c... |
2,321,070 | 2,321,222 | replace _asm nop in 64-bit, VS2008, C++ | How to replace _asm nop instructions in 64-bit. compiles and works in 32-bit.
| I believe that you can use the __nop intrinsic function. This should compile into the appropriate machine instruction for the processor that you are building.
http://msdn.microsoft.com/en-us/library/aa983381(VS.80).aspx
UPDATE:
Here is an example that I just created with VS2008. It compiles for both Win32 and x64 con... |
2,321,305 | 2,327,178 | Only include certain items in CComboBox type ahead? | I have a dropdown-list style CComboBox on a form. The nice thing about this style is it allows for type ahead--that is, you can type a character and it will jump to the first item in the list matching that character. However, there are certain items which need to be excluded from this behavior. How might this be accomp... | Just as a simple (and maybe ugly) "trick" idea: Can you mask the items you want to exclude from type ahead search by any special character, like * as first character for instance? (So you would add to the ComboBox *MyItemText instead of MyItemText.) If your item list needs to be sorted you have to switch off the autoso... |
2,321,515 | 2,321,832 | Using expat to parse xml | I need to get attributes name and values of an xml file with many elements.
what is the best way to capture the attribute values in a class?
I have to following code for the startelement handler:
start(void *data, const char *el, const char **attr)
{
int i;
// Skip the ParameterList element
if(strcmp(el, "Parame... | I would recommend an STL vector of STL pairs of strings. first is the attribute name, second is the value.
std::vector<std::pair<std::string,std::string> >
Some would suggest an std::map.
|
2,321,578 | 2,321,596 | C++: why can't we have references to references or array of references? | I noticed that there is no reference to reference but there is pointer to pointer, and also there is no an array of references but an array of pointers.
Could anybody give me any reason?
| Pointers are mutable (if non-const), references never. Thus there is no point having a pointer or reference to a reference.
Also, a reference must always refer to something - there is no such thing as a null reference. This is why there can be no arrays of references, as there is no way to default instantiate reference... |
2,321,663 | 2,321,725 | Why do I get warning C4081 on this #pragma? | I am in the habit of removing all warning reported in my code. I just like a clean build if possible. I used
#pragma comment(lib,"some.lib");
I get this warning:
warning c4081: expected 'newline'; found ';'
I am uncertain why that would create a warning. Could I get help on removing it?
| Its the semi-colon at the end of the line. Its not needed for #pragma.
edit: The warning says it all: Expected a newline at the end of the pragma, but found a semi-colon instead.
Tested with VS2008
|
2,321,713 | 2,321,731 | How do I avoid name collision with macros defined in Windows header files? | I have some C++ code that includes a method called CreateDirectory(). Previously the code only used STL and Boost, but I recently had to include <windows.h> so I could look-up CSIDL_LOCAL_APPDATA.
Now, this code:
filesystem.CreateDirectory(p->Pathname()); // Actually create it...
No longer compiles:
error C2039: 'Cr... | You will be better off if you just rename your CreateDirectory method. If you need to use windows APIs, fighting with Windows.h is a losing battle.
Incidently, if you were consistent in including windows.h, this will still be compiling. (although you might have problems in other places).
|
2,321,790 | 2,322,056 | How do I layout my C++ program? (where should I put the .h and .cpp files?) | Currently, I program in Java and use Maven quite a bit. As so I've become accustom to the naming schemes and folder structures that I've used over the past 4 or 5 years.
As I have recently started to learn C++, I'm realizing that I have no idea where to put all my files. Should I keep everything broken down by name... | The following is fairly typical...
third-party library
release
obj
debug
obj
include
src
sublib 1
sublib 2
mylibrary
release
obj
debug
obj
include
src
sublib 1
sublib 2
myapp
release
obj
debug
obj
subapp 1
subapp 2
mylittleapp
release
obj
debug
... |
2,321,908 | 2,321,986 | Issue with using std::copy | I am getting warning when using the std copy function.
I have a byte array that I declare.
byte *tstArray = new byte[length];
Then I have a couple other byte arrays that are declared and initialized with some hex values that i would like to use depending on some initial user input.
I have a series of if statements t... | C4996 means you're using a function that was marked as __declspec(deprecated). Probably using D_SCL_SECURE_NO_WARNINGS will just #ifdef out the deprecation. You could go read the header file to know for sure.
But the question is why is it deprecated? MSDN doesn't seem to say anything about it on the std::copy() page... |
2,321,924 | 2,322,107 | Forward declaration of 'const struct list::SingleList' , Invalid use of incomplete type 'list::SingleList' (Compilation errors) | SingleList.h
#include "ListBase.h"
#include "DataNode.h"
#include "SingleListIterator.h"
namespace list
{
class SingleListIterator;
class SingleList : public ListBase
{
private:
DataNode *head;
DataNode *tail;
public:
SingleList();
SingleList(... | You use forward declarations, but you anyway include the .h files recursively. The point of the forward declarations is that you don't need to include the headers of the
forward declared class, thereby breaking the mutual dependency.
Also it should be enough to use a forward declaration for one of the classes, not for... |
2,321,972 | 2,322,163 | Argument order for mixed const and non-const pass-by-reference | In keeping with the practice of using non-member functions where possible to improve encapsulation, I've written a number of classes that have declarations which look something like:
void auxiliaryFunction(
const Class& c,
std::vector< double >& out);
Its purpose is to do something with c's public memb... | The STL algorithms places output (non-const) values last. There you have a precedent for C++ that everyone should be aware of.
I also tend to order arguments from important, to less important. (i.e. size of box goes before box-margin tweak value.)
(Note though: Whatever you do, be consistent! That's infinitely more imp... |
2,321,981 | 2,322,082 | Is there a way to know if the user has enabled "single click to open an item" in the control panel? | My program needs to know when the user has enabled "Single-click to open an item (point to select)" in the folder options window in file explorer. I have a mouse aid program and I need to know what this setting is set to programmatically? Is this available in the registry or something?
| I think it's SHGetSettings when fDoubleClickInWebView is false
|
2,322,095 | 2,322,280 | Why does this program crash: passing of std::string between DLLs | I have some trouble figuring out why the following crashes (MSVC9):
//// the following compiles to A.dll with release runtime linked dynamically
//A.h
class A {
__declspec(dllexport) std::string getString();
};
//A.cpp
#include "A.h"
std::string A::getString() {
return "I am a string.";
}
//// the following compi... | This isn't actually being caused by differing heap implementations - the MSVC std::string implementation doesn't use dynamically allocated memory for strings that small (it uses the small string optimization). The CRTs do need to match, but that isn't what bit you this time.
What's happening is that you're invoking und... |
2,322,255 | 2,326,485 | 64-bit version of Boost for 64-bit windows | Is there a version of 64-bit Boost library for VS2008 ?
Or do I have to compile one myself? if, so, does anyone have experience with it?
| As a short answer:
bjam --toolset=msvc-9.0 address-model=64 --build-type=complete
As a longer answer, here are my build notes for having VS .NET 2008 32-bit and 64-bit boost libraries in the same hierarchy (which is I suspect a common use case):
Build the win32 binaries
bjam --toolset=msvc-9.0 --build-type=complete s... |
2,322,266 | 2,322,283 | What should I know about multithreading and when to use it, mainly in c++ | I have never come across multithreading but I hear about it everywhere. What should I know about it and when should I use it? I code mainly in c++.
| Mostly, you will need to learn about MT libraries on OS on which your application needs to run. Until and unless C++0x becomes a reality (which is a long way as it looks now), there is no support from the language proper or the standard library for threads. I suggest you take a look at the POSIX standard pthreads libra... |
2,322,357 | 2,322,598 | C++ ">>" and "<<" IO in C#? | Is there a C# library that provides the functionality of ">>" and "<<" for IO in C++? It was really convenient for console apps. Granted not a lot of console apps are in C#, but some of us use it for them.
I know about Console.Read[Line]|Write[Line] and Streams|FileStream|StreamReader|StreamWriter thats not part of the... | I think I get what you are after: simple, default formatted input. I think the reason there is no TextReader.ReadXXX() is that this is parsing, and parsing is hard: for example: should ReadFloat():
ignore leading whitespace
require decimal point
require trailing whitespace (123abc)
handle exponentials (12.3a3 parses d... |
2,322,402 | 2,322,477 | Are there delimiter bytes for UTF8 characters? | If I have a byte array that contains UTF8 content, how would I go about parsing it? Are there delimiter bytes that I can split off to get each character?
| Take a look here...
http://en.wikipedia.org/wiki/UTF-8
If you're looking to identify the boundary between characters, what you need is in the table in "Description".
The only way to get a high bit zero is the ASCII subset 0..127, encoded in a single byte. All the non-ASCII codepoints have 2nd byte onwards with "10" in ... |
2,322,446 | 2,322,502 | Pimpl idiom used with a class member variable | Whats the correct way of implementing this class?
//Header
#include <boost/shared_ptr.hh>
class MyClass
{
public:
static foo()
static foobar();
private:
class pimpl;
static boost::shared_ptr<pimpl> m_handle;
static bool initialized;
};
//source
namespace
{
bool init()
{
//...
// i... | MyClass is a singleton -- some call it a glorified global. An oft-abused pattern. Use private ctors and a public static accessor:
MyClass {
public:
static MyClass& Instance() {
static MyClass obj;
return obj;
}
// ...
private:
M... |
2,322,533 | 2,322,641 | Thread-safe variables in Linux programming | I am writing a shared library that will allow linked applications to query a resource.
The resource class is implemented with only static methods (see below). It also uses a global object (well scoped in an anonymous namespace). The reason for the global variable is that I do not want to expose users of the library to ... | Wrap your objects to be operated upon in re-entrant locks wherever you access it :) There's some code in C++ here which allows you to implement a locking mechanism. Needs Boost though:
http://the-lazy-programmer.com/blog/?p=39
Seems quite cool :)
LOCK (myObject) {
do something with myObject
}
Make sure you look a... |
2,322,736 | 2,323,005 | what is the difference between function declaration and signature? | In C or C++ what is the difference between function declaration and function signature?
I know something of function declaration but function signature is totally new to me. What is the point of having the concept of function signature? What are the two concepts used for actually?
Thanks!
| A function declaration is the prototype for a function (or it can come from the function definition if no prototype has been seen by the compiler at that point) - it includes the return type, the name of the function and the types of the parameters (optionally in C).
A function signature is the parts of the function de... |
2,322,742 | 2,326,635 | How do you declare and use an overloaded pool operator delete? | I would like to know how to adapt section 11.14 of the C++-FAQ-lite to arrays.
Basically, I would want something like this:
class Pool {
public:
void* allocate(size_t size) {...}
void deallocate(void* p, size_t size) {...}
};
void* operator new[](size_t size, Pool& pool) { return pool.allocate(size); }
void operat... | It is impossible. Bjarne reasons that you'll never get it right figuring out the correct pool. His solution is: you must manually call all destructors and then figure out the correct pool to be able to deallocate the memory manually.
References:
Bjarne's FAQ: Is there a placement delete?
Relevant C++ standard sections:... |
2,322,748 | 2,322,852 | help with set & map on STL for c++ | I am taking a CS class, and most of the assignments were in java. in the last java assignment we learned collections. This assignment we are using c++ and i need to learn the STL
The required book is all in java. We were given this webpage http://www.cplusplus.com/
however, that and google is not going to get me throug... | Okay, the key question is which operations you need to support. The operations dictate which data structure you should use.
For example, for books you've got:
const Item* addBook(const string& title, const string& author, int const nPages);
const ItemSet* booksByAuthor(const string& author) const;
const ItemSet* books(... |
2,322,831 | 2,322,874 | load XML from variable, not File | I'm trying to parse XML data stored in a variable, not a file. The reason for this is that program x replies to program y in XML, so it would seem to be best to directly parse the XML from the variable.
So far I have tried to do this in TinyXML, but I don't see an interface to load from a variable.
It's basically the ... | If you already have the document in a string why not simply call the TiXmlDocument::Parse method and be done?
|
2,322,876 | 2,322,910 | debugging information cannot be found or does not match visual studio's | I copied an existing project and renamed the folder. Now I get this error when I try to compile the application
debugging information cannot be found or does not match. No symbols loaded.
Do you want to continue debugging ?
If I click yes, it compiles and runs fine. But now I have to deal with that message. Just c... | The main reason is that you don't have a matching pdb and exe.
Some possible solutions:
You are compiling in release instead of debug
You need to clean/build or rebuild
You don't have your pdb files being generated in the same directory as the exe
You have a mismatching pdb, maybe the copied source is newer than today... |
2,322,931 | 2,323,727 | dylib on Snow Leopard "file is not of required architecture" | I have compiled opencv on snow leopard and it says it compiled correctly, however when I try to compile my sample program against it, I get output like:
g++ -o tm_scons template.o -L/opencv/opencv/build/lib -lcxcore -lcv -lcvaux -lhighgui -lml
ld: warning: in /opencv/opencv/build/lib/libcxcore.dylib, file is not of req... | As it turns out the magic was using -m32 and switching to the /usr/bin/g++-4.0 compiler.
Ugh....
|
2,322,934 | 2,322,950 | How to make a console program doesn't have console window | I'm writing a console program.
The program doesn't print anything.
So, it doesn't need to a console window.
I tried to call FreeConsole() function at program starting point.
When I execute the program from windows explorer, a console window appears and then disappears.
But I wish the console window never appears.
How c... | If you are using Visual Studio .Net then create a normal console application and change the output type to Windows application.
|
2,323,189 | 2,323,224 | How is a reference different from a pointer in implementation? |
Possible Duplicate:
Difference between pointer variable and reference variable in C++
I am reading about the book "Inside the C++ Object Model" by Stanley Lippman. What puzzles me is the difference between a "reference" of an object and a "pointer" to an object. I know that a reference must be initialized when declar... | Most references are implemented using a pointer variable i.e. a reference usually takes up one word of memory. However, a reference that is used purely locally can - and often is - eliminated by the optimizer. For example:
struct S { int a, int b[100]; };
void do_something(const vector<S>& v)
{
for (int i=0... |
2,323,225 | 2,323,241 | C++ Copy constructor, temporaries and copy semantics | For this program
#include <iostream>
using std::cout;
struct C
{
C() { cout << "Default C called!\n"; }
C(const C &rhs) { cout << "CC called!\n"; }
};
const C f()
{
cout << "Entered f()!\n";
return C();
}
int main()
{
C a = f();
C b = a;
return 0;
}
the output I get is:
Entered f()!
De... |
Since f() is returning by value, it should return a temporary. As T a = x; is T a(x);, wouldn't it call the copy constructor for the construction of a, with the temporary passed-in as its argument?
Look up Return Value Optimization. This is turned on by default. If you are on Windows using MSVC 2005+ you can use /Od ... |
2,323,239 | 2,323,252 | How about defining a class but not make any instance of it? | I am learning some COM code and the following code puzzled me.
STDMETHODIMP _(ULONG) ComCar::Release()
{
if(--m_refCount==0)
{
delete this; // how could this "suicide" deletion be possible?
return 0;
}
return m_refCount;
}
Yes. this is the similar code from ... |
1- If I define a class without making an instance of it. Would this type exist in runtime?
Edit post OP's edit and gnud's comment:
A class is an user defined type. The type will be available as will be a float type even if you don't use any float in your code. The type information will be present. Particularly as gn... |
2,323,413 | 2,323,461 | Accessing member variables through boost lambda placeholder | I'm trying to print the second member variable of all items in an stl map using a lambda expression
map<int, int> theMap;
for_each(theMap.begin(), theMap.end(),
cout << bind(&pair<int, int>::second, _1) << constant(" "));
but this is not compiling. I essentially want to de-reference the placeholder. Any idea... | std::map will add const to its key; this is to prevent messing up the ordering. Your pair should be:
std::pair<const int, int>
Like dirkgently suggests, use the value_type to always get the correct type. The verbosity is alleviated with a typedef:
typedef std::map<int, int> int_map;
int_map::value_type::second
|
2,323,490 | 2,323,518 | Non-recursive mutex ownership | I read this answer on SO:
Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the m... | Non-recursive mutex
Most mutexes are (or at least should be) non-recursive. A mutex is an object which can be acquired or released atomically, which allows data which is shared between multiple threads to be protected against race conditions, data corruption, and other nasty things.
A single mutex should only ever b... |
2,323,516 | 2,323,605 | Unsigned modulos: alternative approach? | I'm in a need to optimize this really tiny, but pesky function.
unsigned umod(int a, unsigned b)
{
while(a < 0)
a += b;
return a % b;
}
Before you cry out "You don't need to optimize it", please keep in mind that this function is called 50% of the entire program lifetime, as it's being called 21495808... | This should do it:
unsigned umod(int a, unsigned b)
{
if (a < 0)
{
unsigned r = (-a % b);
if (r)
return b - r;
else
return 0;
}
else
return a % b;
}
Tested to match original. Limitation is that a > INT_MIN on 2s complement machines.
|
2,323,591 | 2,323,611 | The method used in 3rd-party garbage collector | I am writing to clarify some comments on this website.
1) I know that C++ has no garbage collector. One said that C++ was invented before the idea of garbage collector, so that's the reason. Is that true? I think it makes sense.
2) Whenever garbage collector was discussed, smart point(such as boost::share_ptr) was bro... |
no, garbage collection is far older than C++ (many Lisp versions had it in the '60s, in particular).
reference counting is a way to implement garbage collection, but it's quite poor performance-wise (the new Unladen Swallow project, to accelerate the CPython interpreter, includes moving from reference counting to a be... |
2,323,613 | 2,340,250 | What are good online introductions to testing and Test Driven Development? | I'm looking for an online introduction to unit testing and TDD. I have virtually no experience with TDD, unit testing, or any other agile methodology. My development environment is C++ on Linux. If there's a quality introduction to unit testing and TDD that uses C++ as the example language, that'd be great. If not ... | For the introduction to TDD, the bowling game episode is very nice, as it demonstrate how the tests drive the design. Then, here are tutorials focusing on C++ frameworks for CppUnit, Boot::Test and CppCheck.
To help choosing a framework, Noel LLopis explored this jungle, albeit a long time ago, especially it dosen't m... |
2,323,627 | 2,323,639 | C++ functions taking values, where they should be taking references | I'm just learning c++, and coming from c, some function calls I'm seeing in the book confuse me:
char a;
cin.get(a);
In C, this couldn't possibly work, if you did that, there would be no way to get the output, because you are passing by value, and not by reference, why does this work in c++? Is referencing and derefer... | C++
This would work in C++ because the function signature for get() is probably this:
void get(char& a); // pass-by-reference
The & symbol after char denotes to the compiler than when you pass in a char value, it should pass in a reference to the char rather than making a copy of it.
What this essentially means is tha... |
2,323,736 | 2,324,127 | Remove dependancy constants from enum definition | I am trying to safely remove a dependency from my project by using opaque structures and forward declarations but like most I am still stuck on my enums.
The header file dependency I am trying to remove from my header files has defined constants that I want to set my enumeration's values to. Something like this
// dep... | How about removing the include of the depends header, hard code the values, and comment the dependency:
// my_header.h
// NOTE: Enumerands must be in sync with symbols defined in depends.h
enum TYPES
{
T_ONE = 1, // DEP_TYPE_ONE
T_TWO = 2, // DEP_TYPE_TWO
T_THREE = 3 // DEP_TYPE_THREE
};
To all... |
2,323,751 | 2,323,870 | Eliminate repetition in C++ code? | Given the following:
StreamLogger& operator<<(const char* s) {
elements.push_back(String(s));
return *this;
}
StreamLogger& operator<<(int val) {
elements.push_back(String(asString<int>(val)));
return *this;
}
StreamLogger& operator<<(unsigned val) {
elements.push_back(String(asString<unsigned>(val)));
re... | Really, in "vanilla" C++ you either write the by hand, for specific types, or you use a template like dirkgently suggested.
That said, if you can use Boost this does what you want:
template <class T>
StreamLogger& operator<<(T val)
{
typedef boost::mpl::vector<const char*, int,
unsig... |
2,323,927 | 2,323,935 | Why can't I initialize my static data member in my constructor | I read the answer in parashift but I need bit details as to why compiler won't allow to define static member variable in constructor.
| static member variables are not associated with each object of the class. It is shared by all objects. If you initialize in ctor then it means that you are trying to associate with a particular instance of class. Since this is not possible, it is not allowed.
|
2,323,929 | 2,323,967 | istringstream - how to do this? | I have a file:
a 0 0
b 1 1
c 3 4
d 5 6
Using istringstream, I need to get a, then b, then c, etc. But I don't know how to do it because there are no good examples online or in my book.
Code so far:
ifstream file;
file.open("file.txt");
string line;
getline(file,line);
istringstream iss(line);
iss >> id;
getline(file... | ifstream file;
file.open("file.txt");
string line;
getline(file,line);
istringstream iss(line);
iss >> id;
getline(file,line);
istringstream iss2(line);
iss2 >> id;
getline(file,line);
iss.str(line);
iss >> id;
istringstream copies the string that you give it. It can't see changes to line. Either construct a new ... |
2,323,940 | 2,323,969 | Does "Return value optimization" cause undefined behavior? | Reading this Wikipedia article pointed by one of the repliers to the following question:
C++ Copy constructor, temporaries and copy semantics
I came across this line
Depending on the compiler, and the compiler's settings, the resulting program may display any of the following outputs:
Doesn't this qualify for undefin... | No, it's not undefined behavior. Undefined behavior has a specific definition in the standard (mostly: "behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements.") In this case, the behavior is unspecified, but not undefine... |
2,324,325 | 2,324,376 | linked list and Red/Black tree in c# - reference problem? | I'm pretty new to c#, and i'm trying to understand something pretty basic.
I want to implement a RBTree and a linked list , so i create :
public class RBTreeNode
{
// PROPERTIES
public RBTreeNode left;
public RBTreeNode right;
public RBTreeNode parent;
public String Color;
... | No, you're fine. X.left is just a variable. Setting it to null just sets the value of that variable to null, it does nothing to the object that it used to refer to.
There's really no such concept as setting an object to null in C#.
I have an article about value and reference types in C# that you may find useful.
|
2,324,602 | 2,340,194 | "No source available for main()" error when debugging simple C++ in Eclipse with gdb | I'm having trouble debugging a C++ program in Eclipse (the latest RC of Helios, updated with latest CDT from within itself) on OSX.
The program is very simple (esentially Lesson 2 from NeHe's OpenGL tutorials), consisting of one cpp file and, using OpenGL and Cocoa frameworks, and linking with libSDL.a and libSDLmain.a... | I found the answer! And it's embarrassingly simple.
The problem was that I was using the Release version of SDL instead of the Debug version! (I had 'libsdl' from MacPorts whereas I should have had 'libsdl-devel'.)
So my generic answer is: make sure the libs you're linking against were compiled with debug flags set too... |
2,324,658 | 2,324,855 | How to determine the version of the C++ standard used by the compiler? | How do you determine what version of the C++ standard is implemented by your compiler? As far as I know, below are the standards I've known:
C++03
C++98
| By my knowledge there is no overall way to do this. If you look at the headers of cross platform/multiple compiler supporting libraries you'll always find a lot of defines that use compiler specific constructs to determine such things:
/*Define Microsoft Visual C++ .NET (32-bit) compiler */
#if (defined(_M_IX86) && def... |
2,324,851 | 2,324,884 | Use rspec to test C/C++ program | Is Rspec ruby/rails specific? Is it possible to use it as a test framework for C/C++ program?
| Description of Rspec says:
RSpec is the original Behaviour Driven Development framework for Ruby.
I think that means this tool is Ruby specific. For c++ you could use Boost Test Library or other tools.
|
2,325,002 | 2,329,891 | Advantage of SQL_TXN_SERIALIZABLE over SQL_TXN_REPEATABLE_READ in DB2 and C++ | We are facing a problem in our application. We have two instances of our monitoring application. The application behaviour is as follows:
Step 1. Monitor the ftp folder in a loop
Step 2. If files are present, insert the file details to DB for the all files
Step 3. Read the file details from the DB and process it
Step 4... | You probably want to use SQL_TXN_READ_COMMITTED, not SQL_TXN_REPEATABLE_READ or SQL_TXN_SERIALIZABLE, as it offers better concurrency than the other two methods.
See the DB2 documentation on isolation levels, keeping in mind the following mapping:
CLI Name DB2 Isolation Level
------------------... |
2,325,043 | 2,369,497 | boost::asio: thread local asynchronous events | I will be creating x amount of threads in my server-app. x will be the amount of cores on the machine, and these threads will be (non-hyperthread) core-bound. Naturally with this scheme I would like to distribute incoming connections across the threads with the aim of ensuring that once a connection is assigned to a th... | Yes, your reasoning is basically correct. You would create a thread per core, an io_service instance per thread, and call io_service.run() in each thread.
However, the question is whether you'd really do it that way. These are the problems I see:
You can end up with very busy cores and idling cores depending on how ... |
2,325,121 | 2,325,170 | casting operator - const vs non-const | I have this code sample:
class Number
{
int i;
public:
Number(int i1): i(i1) {}
operator int() const {return i;}
};
What are the implications of removing the const modifier from the casting operator?
Does it affect auto casting, and why?
| If the conversion operator is not const, you can't convert const objects:
const Number n(5);
int x = n; // error: cannot call non-const conversion operator
|
2,325,146 | 2,346,937 | Using GDB with external libs | I'm currently debugging a project that uses an external library (LibFirm). When i call library functions, I can't really see what's going on there with gdb (i.e. I can't inspect local variables and such).
The library is open source and I compiled it myself, so I think it should be possible to let gdb look into it too. ... | I had to use ./configure --enable-debug (CFLAGS="-g" was on by default, but it may not be in other projects, so remind this one). Furthermore, you may want to use CFLAGS="-g -O0" (instead of only -g) to keep the code readable.
|
2,325,148 | 2,327,721 | When to use signals and slots and when not to | We're using Qt that offers signals and slots which I find really convenient. However, with great power comes great responsibility and I think it's very easy too misuse this feature.
Are there any best-practices for signal-slot usage? I'm having a hard time to find some general guidelines in this manner. Some questions... |
Is it ok to use signals to report
errors?
Yes, for instance, see QFtp, where the done signal carries a status. It does not carry the actual error, just information that an error has occured.
Is it ok to assume that a signal will
be handled?
No. The sender can never assume that, however, your particular applicat... |
2,325,472 | 2,325,531 | Generate random numbers following a normal distribution in C/C++ | How can I easily generate random numbers following a normal distribution in C or C++?
I don't want any use of Boost.
I know that Knuth talks about this at length but I don't have his books at hand right now.
| There are many methods to generate Gaussian-distributed numbers from a regular RNG.
The Box-Muller transform is commonly used. It correctly produces values with a normal distribution. The math is easy. You generate two (uniform) random numbers, and by applying an formula to them, you get two normally distributed ran... |
2,325,616 | 4,331,392 | ReadFile, COM and NULL characters in c++ | I have a problem with ReadFile function in a virtual serial port:
char tmp[128];
int multiplo=0;
DWORD err;
COMSTAT stt;
ClearCommError(hcom, &err, &stt);
do{
if(ReadFile(hcom, tmp, stt.cbInQue, &err, NULL)){
tmp[err] = '\0';
memcpy(bfIn+multiplo, tmp, err);
multiplo = multiplo + err;
}... | The problem seems to be not in ReadFile() but rather in your use of tmp[] as the terminating '\0' happens to be 0x00, too.
What do you mean by "doesn't read like I expected"? Can you describe the symptoms in more detail?
|
2,325,617 | 2,325,660 | How to define NULL using #define | I want to redefine NULL in my program such as
#define MYNULL ((void*)0)
But this definition is not working in the following statement:
char *ch = MYNULL;
Error : can not convert from void* to char *
What would be the best way to define NULL?
| #ifdef __cplusplus
#define MYNULL 0
#else
#define MYNULL ((void*)0)
#endif
will work in both of them.
|
2,325,686 | 2,326,092 | How to change the default *.exe icon in C/C++? | I want to change the default .exe icon to some other icon in C/C++. Does anybody know how to do that?
| Already answered.
Change app icon in Visual Studio 2005?
You have to place your .ico file in the resources folder first of course.
|
2,325,756 | 2,325,784 | generating a 3d graphics c++ | I have found an interesting application on the net and i am using it for my end year study project.
http://www.cl.cam.ac.uk/~sjeh3/wii/ the video in the link explains my goal.
But i am having issue using it. the example of rendering the trajectory on a 3d axis is using Corba (omniorb) and i believe open inventor. but t... | You might also look at SDL (which uses OpenGL).
Edit (re: comments)
For the plotting aspect, you could look at VTK and/or MayaVI (which puts a Python scripting wrapper around VTK).
|
2,325,830 | 2,371,818 | CMake compile C++ file in custom command | I'm trying to precompile a header file in GCC with the following command:
ADD_CUSTOM_COMMAND(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/all.hpp.gch
COMMAND ${CMAKE_CXX_COMPILER} ${CMAKE_CXX_FLAGS} -o ${CMAKE_BINARY_DIR}/all.hpp.gch ${CMAKE_CURRENT_SOURCE_DIR}/all.hpp
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/all.hpp
... | I don't believe that add_definitions() adds its arguments to CMAKE_CXX_FLAGS. In fact, as far as I can tell they aren't saved anywhere (apart from arguments beginning with -D or /D which get added to COMPILE_DEFINITIONS).
The simplest way to solve that would be to, whenever calling add_definitions(), to also manually a... |
2,325,894 | 2,328,013 | Difference between InvalidateRect and RedrawWindow | When I want to redraw a window, is there any preferred function to call between InvalidateRect and RedrawWindow?
For instance, are these two calls equal: (win would be a HWND)
RedrawWindow(win, NULL, NULL, RDW_INVALIDATE);
InvalidateRect(win, NULL, NULL);
The main question(s): When should I use one or the other? Are ... | InvalidateRect does not immediately redraw the window. It simply "schedules" a future redraw for a specific rectangular area of the window. Using InvalidateRect you may schedule as many areas as you want, making them accumulate in some internal buffer. The actual redrawing for all accumulated scheduled areas will take ... |
2,325,951 | 2,325,973 | How to handle signals when a Qt object isn't created through Designer? | Hi I've got a spare moment so decided to look at Qt and how easily I can port my windows applications to Qt.
My only real problem is a couple of controls that will need re-implementing under Qt. I've already handled the basic drawing of the control but my control creates a child scroll bar. The problem is that this ... | connect( myScrollbar, SIGNAL( <signal signature>), this, SLOT( <slot signature>));
Call connect after creating the scroll bar (I presume that you need this signal handling immediately after creating the scroll bar).
I assumed myScrollbar is of type QScrollBar* and that the slot is defined as a member in your class.
Wh... |
2,325,960 | 2,326,197 | Class with pass-by-reference object gives compile error | I've got a class A defined in a separate header file. I want class B to have a reference to a object of class A stored as a variable.
Like this:
File: A.h
class A {
//Header for class A...
};
File: B.h
#include "A.h"
class B {
private:
(24) A &variableName;
public:
(36) B(A &varName);
};
Whe... | By me it compiles fine (as expected). I'm guessing A.h isn't being included properly. Is there another file with the same name that gets included instead? Perhaps there are #ifdefs or some such that prevent the definition of A from being seen by the compiler. To check this, I would put some sort of syntax error int... |
2,326,157 | 2,326,283 | make a charater follow an uneven terrain (2D) | I'd like to make a game where the terrain is not even and is based on a png. How s this done in theory, given the object's vec2 and its angle, because if for instance there is a hill, the character will rotate based on the angle of the hill. Thanks
2d like mario
| I think you are talking about a heightmap which is you PNG which is then converted to a 3D triangle mesh. You need to use the information from the mesh (or PNG color value) to calculate the current height where you should place your character.
If this is a flying character your pretty much done here, but in your case ... |
2,326,236 | 2,326,272 | Can objects be unwinded before they are created on stack? | We have been debugging a strange case for some days now, and have somewhat isolated the bug, but it still doesn't make any sense. Perhaps anyone here can give me a clue about what is going on.
The problem is an access violation that occur in a part of the code.
Basically we have something like this:
void aclass::somefu... | With the information you have provided, and if everything is as you state, the only possible answer is a bug in the compiler/optimizer. Just add the extra scope with a comment (This is, again, if everything is exactly as you have stated).
|
2,326,376 | 2,326,397 | Deque of user-defined structures | I've got a user-defined structure struct theName and I want to make a deque of these structures (deque<theName> theVar). However when I try to compile I get this error:
In file included from main.cpp:2:
Logger.h:31: error: ISO C++ forbids declaration of ‘deque’ with no type
Logger.h:31: error: expected ‘;’ before ‘<’ t... | The namespace of deque is not defined:
std::deque<MotorPoint> motorPlotData;
or
using namespace std;
// ...
deque<MotorPoint> motorPlotData;
|
2,326,460 | 2,326,554 | Can I ask VC++ linker to ignore unresolved externals? | I'm trying to build a very complex open-source project with VC++. The project consists of dozens of libraries and one executable depending on those libraries.
For some reasons VC++ linker doesn't want to see about 40 functions implemented in one of those libraries and reports "unresolved external reference" on each, so... | You can use the /FORCE:UNRESOLVED linker option.
The documentation for that contains the rather understated warning:
A file created with this option may
not run as expected.
In pratice, there'll be no error handling - just a crash.
|
2,326,586 | 2,326,707 | How to force template function overload for boost::bind? | I'm trying to create predicate for std::find_if by using boost::bind together with boost::contains (from boost/algoritm/string library).
Following snippet shows two ways how I'm trying to accomplish this.
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>... | You need to write static_cast<bool(*)(const std::string&, const std::string&)>(&boost::contains<..>) to resolve the overload.
Yes, this is a royal pain with templates and overloading. Libs written with OOP and overloading in mind are difficult to use with templates and boost::bind.
We all wait for C++0x lambda expressi... |
2,326,588 | 2,326,670 | Boost asio io_service dispatch vs post | Can anyone tell me the difference between io_service dispatch and post? It was not clear to me what is more suitable for my problem.
I need to invoke a handler inside another handler and I don't know what invoker to use.
| Well, it depends on the context of the call, i.e. is it run from within the io_service or without:
post will not call the function directly, ever, but postpone the call.
dispatch will call it rightaway if the dispatch-caller was called from io_service itself, but queue it otherwise.
So, it depends on the function c... |
2,326,704 | 2,326,969 | Isn't a pointer just a reference when you don't dereference it? | Isn't a pointer just a reference when you don't de-reference it?
#include "stdafx.h"
#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
std::list<int>* user_defined_func( ) {
std::cout << "BEGIN: user_defined_func" << std::endl;
std::list<int>* l = new std::list<int>;
l->push_... |
Isn't a pointer just a reference when
you don't de-reference it?
No, a pointer contains a value that is interpreted as a memory address. (Whether it contains a value that is actually a valid memory address is another question)
A reference is an alias, another way of referring to an existing value.
int i = 5;
int* ... |
2,326,747 | 2,326,766 | Need a cache which is shared between C++, Java and .Net Applications | Is there a caching solution which works with C++, .Net and Java all accessing and populating same data in cache? (Data is composed of simple strings only)
Longer version:
I have 4 applications which work on different areas of a problem. Two of them are developed in C++, one is a java desktop application, and another is... | Memcached works fine across independent applications.
|
2,326,791 | 2,326,924 | Two .c files have identical compilation settings - VC++ reports no error and doesn't compile one of them | I'm trying to compile a set of .c files from an open source project into a static library. I've created a VC++9 project file, set everything up as usual. I add two .c files into the project. They don't have any special compilation settings - all the settings are set at the project level and are set to default except th... | The compiler may think that the object file is up to date with the source. Is the timestamp of one of the object files in the future?
|
2,326,850 | 2,326,922 | long double to string | I'm developping in C++, using the Qt framework.
I need to convert a long double value into a string (ideally a QString, but could be something else).
So far, I always used QString::number() for numerical->string conversion, but there is no overloading for the long doubletype.
Thanks
| QString has a static function to construct a QString from a std::string, so wheaties' answer could be rewritten as:
#include <sstream>
#include <QString>
...
QString qStringFromLongDouble(const long double myLongDouble)
{
std::stringstream ss;
ss << myLongDouble;
return QString::fromStdString(ss.str());
}
|
2,327,099 | 2,327,123 | How to set up C++ Number Formatting to a certain precision? | I understand that you can use iomanip to set a precision flags for floats (e.g. have 2.0000 as opposed to 2.00).
Is there a way possible to do this, for integers?
I would like a hex number to display as 000e8a00 rather than just e8a00 or 00000000 rather than 0.
Is this possible in C++, using the standard libraries?
| With manipulators:
std::cout << std::setfill('0') << std::setw(8) << std::hex << 0 << std::endl;
Without manipulators:
std::cout.fill('0');
std::cout.width(8);
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout << 42 << std::endl;
|
2,327,316 | 2,336,237 | VS2010 RC - only 100 std::map elements in debugger | I have a small problem during debugging my App in VS 2010 RC when I want to see all the elements of std::map container.
When debugger reaches the breakpoint and I want to check the values of the map in element inspector (in 'Locals' windows and in pop-up windows after hovering the variable name with mouse as well) and ... | The display of such information is directed by the autoexp.dat file (usually located in "Program Files*"\"Microsoft Visual Studio*"\Common7\Packages\Debugger).
It seems that Microsoft added a hard coded limitation of 100 elements to the #tree operator, in order to avoid freezing Visual Studio in case of loops in the tr... |
2,327,498 | 2,327,856 | How can I decrease complexity in library without increasing complexity elsewhere? | I am tasked to maintain and update a library which allows a computer to send commands at a hardware device and then receive its response. Currently the code is setup in such a way that every single possible command the device can receive is sent via its own function. Code repetition is everywhere; a DRY advocate's wors... | Well, your question implies that there is a balance between the library's complexity and the client's. When those are the only two choices, one almost always goes with making the client's life easier. However, those are rarely really the only two choices.
Now in the text you talk about a command processing architecture... |
2,327,552 | 2,327,624 | How to introduce boost::shared_ptr into an existing (large) C++ codebase? | I am currently trying to fix a few weaknesses in our code base by introducing the use of smart pointers. The code base is very large, and interlinked like a spider who's had one to many coffee's.
I was wondering if people had tried the before and what their approach was.
My first step has been to typedef classes, as fo... | Don't do this: the typedefs I mean.
Presumably the old code has at least some delete calls in it? Which would certainly fail in the case of a smart pointer.
Smart pointer certain things or not, i.e. chase a specific instance through the code base. Make it work, then move on. Good Luck!
|
2,327,848 | 2,327,867 | How does the delete in C++ know how many memory locations to delete | how does the delete operator work? Is it better then free()?. Also if u do ptr=new char[10], then delete using delete ptr, how does the pointer know how many locations to delete.
| There is only delete operator, free exist only as function. Under C++, you are encouraged to use new/delete over malloc()/free().
There is an internal "magic" in delete operator. When an array is created with new[], the size of array is stored in the metadata at the memory block. delete[] makes use of that information... |
2,327,879 | 2,327,915 | passing more data to std:set Comparison class | I have an std::set with the Compare class which requires additional parameter to compare keys. This variable parameter is determined in run-time and I pack it inside the set's keys just to make it accessible to Compare.
However, the parameter logically belongs to the set rather than the keys so this solution looks awkw... | The definition of std::set is:
template <
class Key,
class Traits=less<Key>,
class Allocator=allocator<Key>
>
class set
So Traits is should be your compare operator, but if would look at constructor, you can see it there again:
explicit set(
const Traits& _Comp
);
So just pass your instance ... |
2,327,953 | 2,327,997 | Unicode - generally working with it in C++ | Suppose we have an arbitrary string, s.
s has the property of being from just about anywhere in the world. People from USA, Japan, Korea, Russia, China and Greece all write into s from time to time. Fortunately we don't have time travellers using Linear A, however.
For the sake of discussion, let's presume we want to ... |
Which encoding is most general
Probably UTF-32, though all three formats can store any character. UTF-32 has the property that every character can be encoded in a single codepoint.
Which encoding is supported by wchar_t
None. That's implementation defined. On most Windows platforms it's UTF-16, on most Unix platforms ... |
2,328,031 | 2,328,526 | g++ fails mysteriously only if a .h is in a certain directory | I'm experiencing an extremely weird problem in a fresh OSX 10.4.11 + Xcode 2.5 installation. I've reduced it to a minimal test case. Here's test.cpp:
#include "macros.h"
int main (void)
{
return 1;
}
And here's macros.h:
#ifndef __JUST_TESTING__
#define __JUST_TESTING__
template<typename T> void swap (T& pT1, T&... | G++ may well indeed be assuming that everything in /usr/include is C. Try compiling your code with -E and studying the line markers in the preprocessor output:
g++ -E test.cpp | grep '^#'
You'll likely see things like
# 1 "/usr/include/gfc2/macros.h" 1 3 4
The 4 is the preprocessor hinting to G++ that it should wrap... |
2,328,092 | 2,328,401 | I'm creating opensource GPL H264 encoding lib/app (based on x264) do I need to pay for the license? | I'm creating opensource GPL H264 encoding lib/app (based on x264) do I need to pay for the license?
| According to this blog article, the MPEG-LA specifically indicated that license fees are required even for open source software:
In response to your specific question, under the Licenses royalties are paid on all MPEG-4 Visual/AVC products of like functionality, and the Licenses do not make any distinction for product... |
2,328,258 | 3,512,564 | Cumulative Normal Distribution Function in C/C++ | I was wondering if there were statistics functions built into math libraries that are part of the standard C++ libraries like cmath. If not, can you guys recommend a good stats library that would have a cumulative normal distribution function? Thanks in advance.
More specifically, I am looking to use/create a cumulativ... | I figured out how to do it using gsl, at the suggestion of the folks who answered before me, but then found a non-library solution (hopefully this helps many people out there who are looking for it like I was):
#ifndef Pi
#define Pi 3.141592653589793238462643
#endif
double cnd_manual(double x)
{
double L, K, w ;
... |
2,328,294 | 2,328,315 | Printing the hex value of an array to a string using C++ | Using standard C++ I/O (such as std::cout), is it possible to "print" the value of an array (however long) into a string?
For example, say I have the following array:
unsigned long C = {0x497fecf2, 0xfa989ea3, 0xd594974e};
I'd like to be able to print those values into a string, and then remove the "0x" from them. Fro... | Create a std::ostringstream, and print them to it just like you could to cout. Retrieve the string with the contents with the stringstream's str() member.
|
2,328,408 | 2,328,573 | default template arguments in c++ | Suppose i have a function template StrCompare
template<typename T=NonCaseSenCompare>//NonCaseSenCompare is a user defined class look at the detailed code below.
int StrCompare(char* str1, char* str2)
{
...
}
now in the main function i write a line
char* str1="Zia";
char* str2="zia";
int result=StrCompare(str1,str2);
... | As gf and AndreyT already wrote, you can't have default template arguments with function templates. However, if you turn your comparators into function objects, you can still use default function arguments:
template<typename Comp>
int StrCompare(char* str1, char* str2, Comp = NonCaseSenCompare())
{
...
}
You can n... |
2,328,423 | 2,351,470 | Convert IDispatch* to a string? | I am converting an old VB COM object (which I didn't write) to C++ using ATL. One of the methods, according to the IDL, takes an IDispatch* as a parameter and the documentation and samples for this method claim that you can pass either a string (which is the progid of an object that will be created and used by the con... | Declare the method so that it takes a VARIANT argument and check the actual type at runtime.
|
2,328,486 | 2,328,643 | Overlapping labels in Qt fridge magnets example | I want to modify the fridge magnets example provided with Qt in a way that when I drag a label and drop it over another, it will push the label beneath the dragged label to the side, so they will never overlap one another.
I've seen how collision is detected in the colliding mice example, where it uses a QGraphicsScene... | You can get the location and size of each QWidget from geometry(), which returns a QRect. QRect has function intersects(), which will tell you if it intersects another QRect. After the drop is complete, iterate through all of the labels and check if any of them do intersect the new position.
(This will be easier if y... |
2,328,666 | 2,328,726 | vim plugin comment blocks | I looked around, but didn't find what I wanted. I need a vim plugin to insert blocks of code and prompt me for values in the comment.
// ********************** BeWee ************************
// *** Creation Date:
// *** Last Modification Date:
// *** File name: BeWee.cpp
// ***************... | Look at SnipMate. Follow the install guide and make a snippet with the layout.
|
2,328,671 | 2,328,715 | constant variables not working in header | if I define my constant varibles in my header like this...
extern const double PI = 3.1415926535;
extern const double PI_under_180 = 180.0f / PI;
extern const double PI_over_180 = PI/180.0f;
I get the following error
1>MyDirectX.obj : error LNK2005: "double const PI" (?PI@@3NB) already defined in main.obj
1>MyDirectX.... | The problem is that you define objects with external linkage in header file. Expectedly, once you include that header file into multiple translation units, you'll get multiple definitions of the same object with external linkage, which is an error.
The proper way to do it depends on your intent.
You can put your defin... |
2,328,732 | 2,328,760 | Pass variable "name" in C++ | I currently use the following template simply as a way to check for NULL pointer and if NULL then print out an error message to a log file and then return false.
template< typename T >
static bool isnull(T * t, std::string name = "")
{
_ASSERTE( t != 0 );
if( !t )
{
if( !(name.length()) ) name = "po... | You could put it all in one macro:
#define IS_NULL(name_) isnull(name_, #name_)
Note that BOOST_STRINGIZE expands its argument if its a macro, which may or may not be what you want:
#define X(x_) std::cout << BOOST_STRINGIZE(x_) << " = " << x_ << std::endl;
X(NULL); // prints: "0 = 0"
|
2,328,960 | 2,328,970 | C++ constructors fun - constructing Foo with a copy of itself | I have:
class Foo;
class Bar {
Foo foo;
Bar(): foo(foo) {};
}
Bar bar;
At this point, is
bar.foo // <--- how is this initialized?
[This question arose from a buggy ref-counted pointer implemntation; I could have sworn that I ensured each pointer was pointing at something non-null; but I ended up with a pointer ... | foo is fully initialized once you've entered the body of the constructor (that's the guaranteed general case; specifically once it has finished initializing in the initialize list.)
In your case, you are copy-constructing from a non-constructed object. This results in undefined behavior, per §12.7/1 (thank you, gf):
F... |
2,328,975 | 2,329,080 | How to modify properties of Bitmaps in C++ | Bitmap bmp(100,100, PixelFormat32bppARGB);
bmp.SetPixel(2,2,Gdiplus::Color::AliceBlue);
int x = bmp.GetHeight();
int y = bmp.GetWidth();
Gdiplus::Color* ccc = new Gdiplus::Color;
Gdiplus::Color* ccc2 = new Gdiplus::Color;
bmp.GetPixel(2,2,ccc);
bmp.GetPixel(0,0,ccc2);
In the past sample... | The constructor you're calling doesn't fill in the pixel data of your bitmap. You need to call a version of bmp.FromX() after construction to fill your bitmap.
Alternately, you can call another constructor that gives you a filled bitmap.
Also, you may want to wrap your SetPixel() call with calls to LockBits() and Unlo... |
2,329,175 | 2,335,088 | MySQL, C++: Need Blob size to read blob data | How do I get the size of data in a BLOB field in the Result Set? (Using C++ and MySQL Connector C++)
In order to read the data from the result set, I have allocate memory for it first. In order to allocate memory, I need to know the size of the blob data in the result set.
Searching the web and StackOverflow, I have... | You could do a select like:
select LENGTH(content),content where id=123;
where content is the BLOB field.
Regards.
see: LENGTH(str)
|
2,329,294 | 2,329,308 | Segmentation fault when using stream extraction into a char pointer | I have a question. I have the following struct:
typedef struct{
int vin;
char* make;
char* model;
int year;
double fee;
}car;
Then I have the following method that asks the user for the make of a car and returns it as a char pointer:
char* askMake(){
char* tempMake = NULL;
cout << "Enter Ma... | You have to allocate memory for tempMake.
Try this:
char* askMake(){
char* tempMake = new char[1024]; //Arbitrary size
cout << "Enter Make:" << endl;
cin >> tempMake;
return tempMake;
}
Don't forget to free with delete[] the memory that you allocated.
If you don't want memory leaks, you can avoid this ... |
2,329,461 | 2,329,765 | Can't add strings in C++ | #include <iostream>
int main()
{
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
std::cout << message;
return 0;
}
Why does this code not work? Error returned:
error: invalid operands of types `const char[6]' and `const char[8]' to binary `operator+'
Thanks ... | Because in C++, string literals (like "Hello" are not of type std::string. They are plain char arrays, or C-style strings.
So for the line const std::string message = "Hello" + ", world" + exclam;,the types the compiler has to work with are:
const std::string message = const char[6] + const char[8] + std::string;
and g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.