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 |
|---|---|---|---|---|
1,305,947 | 1,306,069 | Why does C++ need a separate header file? | I've never really understood why C++ needs a separate header file with the same functions as in the .cpp file. It makes creating classes and refactoring them very difficult, and it adds unnecessary files to the project. And then there is the problem with having to include header files, but having to explicitly check if... | You seem to be asking about separating definitions from declarations, although there are other uses for header files.
The answer is that C++ doesn't "need" this. If you mark everything inline (which is automatic anyway for member functions defined in a class definition), then there is no need for the separation. You ca... |
1,305,967 | 1,306,428 | How to determine whether output iterator has been modified | I have a template function that takes the following form:
template < class ITER1, class ITER2 >
bool example(ITER1 Input1, ITER1 Input2, ITER2 Output)
{
ITER2 OrigOutput(Output);
// ...
std::copy(Input1, Input2, Output);
return (OrigOutput != Output);
}
And I'm calling example() like this:
std::vect... | Write a wrapper iterator which delgates to another iterator, which you would construct from your insert iterator. Your delegate then can set a modified member to be true in the operator= method.
Something along the lines of this:
template<typename ITER>
class ModifiedIterator : public std::iterator<std::output_iterator... |
1,306,094 | 1,306,127 | Does the memory get released when I throw an exception? | I was debating with some colleagues about what happens when you throw an exception in a dynamically allocated class. I know that malloc gets called, and then the constructor of the class. The constructor never returns, so what happens to the malloc?
Consider the following example:
class B
{
public:
B()
{
... | A call to
new B();
resolves in two things:
allocating with an operator new() (either the global one or a class specific one, potentially a placement one with the syntax new (xxx) B())
calling the constructor.
If the constructor throw, the corresponding operator delete is called. The case where the corresponding del... |
1,306,118 | 1,319,983 | Overhead due to use of Events | I have a custom thread pool class, that creates some threads that each wait on their own event (signal). When a new job is added to the thread pool, it wakes the first free thread so that it executes the job.
The problem is the following : I have around 1000 loops of each around 10'000 iterations do to. These loops mus... | If you are just parallelizing loops and using vs 2008, I'd suggest looking at OpenMP. If you're using visual studio 2010 beta 1, I'd suggesting looking at the parallel pattern library, particularly the "parallel for" / "parallel for each"
apis or the "task group class because these will likely do what you're attemptin... |
1,306,414 | 1,306,445 | What is the meaning and usage of __stdcall? | I've come across __stdcall a lot these days.
MSDN doesn't explain very clearly what it really means, when and why should it be used, if at all.
I would appreciate if someone would provide an explanation, preferably with an example or two.
| All functions in C/C++ have a particular calling convention. The point of a calling convention is to establish how data is passed between the caller and callee and who is responsible for operations such as cleaning out the call stack.
The most popular calling conventions on windows are
__stdcall, Pushes parameters... |
1,306,604 | 1,306,615 | Why i can't declare following function in Visual C++ "string timeToStr(string);"? | When i'm trying to declare a function with a string parameter in .h file an error occurs. I haven't forgot to include string.h =) Everything builds fine when i'm using char[], but the i want the argument to be a string.
| string.h doesn't exist in C++. Did you mean string (without the .h)? Additionally, the string class resides in the std namespace you need to qualify the type usage:
std::string timeToStr(std::string);
It would be helpful if you had posted the exact error message and a code to reproduce the error.
|
1,306,611 | 1,306,683 | How do I implement no-op macro (or template) in C++? | How do I implement no-op macro in C++?
#include <iostream>
#ifdef NOOP
#define conditional_noop(x) what goes here?
#else
#define conditional_noop(x) std::cout << (x)
#endif
int main() {
conditional_noop(123);
}
I want this to do nothing when NOOP is defined and print "1... | As mentioned before - nothing.
Also, there is a misprint in your code.
it should be #else not #elif. if it is #elif it is to be followed by the new condition
#include <iostream>
#ifdef NOOP
#define conditional_noop(x) do {} while(0)
#else
#define conditional_noop(x) std::cout << (x)
#endif ... |
1,306,778 | 1,306,837 | Virtual/pure virtual explained | What exactly does it mean if a function is defined as virtual and is that the same as pure virtual?
| From Wikipedia's Virtual function
...
In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion... |
1,306,823 | 1,306,889 | Can you give an example of a buffer overflow? | I've heard so much about buffer overflows and believe I understand the problem but I still don't see an example of say
char buffer[16];
//code that will over write that buffer and launch notepad.exe
| First, you need a program that will launch other programs. A program that executes OS exec in some form or other. This is highly OS and language-specific.
Second, your program that launches other programs must read from some external source into a buffer.
Third, you must then examine the running program -- as layed o... |
1,307,547 | 1,308,418 | Determine object identity from a reference to a superclass | I have the following pair of functions:
void RegisterSink( ISink & Sink )
void UnregisterSink( ISink & Sink )
Where ISink is an abstract base class. Internally, I would like to store pointers to the sinks in an std::set. When a sink is unregistered, i simply search for the pointer in my set, and remove it. My question... | In case of multiple inheritance the meaning of "same object" sometimes is not obvious.
For example, if ISink is present twice in the list of base classes and wasn't inherited with "virtual", such situation is possible:
class A {};
class B:public A {};
class C:public A {};
class D:public B,public C {};
...
void f(A *a);... |
1,307,642 | 1,310,580 | What is a good way to edit C++ on Mac OS X? | I am a first year Comp. Sci. student and am looking for the best way to develop C++ on a Mac. I have Xcode and Textmate.
What are the benefits/negatives of each? Are there any better ones?
I am not a fan of having to use a whole project to run programs with Xcode. Is this the only way to do it, or am I mistaken?
Also, ... | I almost exclusively use Textmate, but to be fair the decision to switch to Textmate (coming from codewarrior in OS 9 days), was mainly because the XCode editor (then named ProjectBuilder) was annoyingly slow at editing larger files.
I'm sure that changed a lot over the years, but I see no reason to switch so I don't.
... |
1,307,831 | 1,309,207 | what is the result of incrementing an istream_iterator which is already at the end of the stream? | I've looked at the standard and didn't see an obvious answer.
suppose i've done this:
std::istream_iterator<char> is(file);
while(is != std::istream_iterator<char>()) {
++is;
}
now is is at the end of the stream and is equal to std::istream_iterator<char>(). What happens if I increment it one more time? Is it stil... | Table 72 in C++03 about input iterator requirements says that the pre-condition of ++r is that r is de-referenceable. The same pre-conditions holds for r++.
Now, 24.5.1/1 says about istream_iterator
The result of operator* on an end of stream is not defined.
In conclusion, the effects of operator++ on an end-of-stre... |
1,307,876 | 1,308,335 | How do conversion operators work in C++? | Consider this simple example:
template <class Type>
class smartref {
public:
smartref() : data(new Type) { }
operator Type&(){ return *data; }
private:
Type* data;
};
class person {
public:
void think() { std::cout << "I am thinking"; }
};
int main() {
smartref<person> p;
p.think(); // why doe... | Some random situations where conversion functions are used and not used follow.
First, note that conversion functions are never used to convert to the same class type or to a base class type.
Conversion during argument passing
Conversion during argument passing will use the rules for copy initialization. These rules j... |
1,307,883 | 1,307,927 | error C2664 converting from from const std::string to std::string& | I keep receiving a C2664 conversion error in visual studio
It tells me that it can't convert parameter 1 from const std::string to std::string&. I tried adding/removing the const in the stringToWstring prototype and in the function itself and the error still comes up.
wstring hexval = buff.substr(buff.find(L"hex(2... | Looking at the edited question, your error is inside boost/tokenizer.hpp, not at the specified line.
So my guess is that your tokenizer is wrong. Looking at http://www.boost.org/doc/libs/1_34_0/libs/tokenizer/tokenizer.htm it takes three template arguments, and the third one defaults to std::string. Since you want to u... |
1,307,977 | 1,308,025 | Which way to go Web Side ,Mobile Development, Stand alone applications? | I am currently intern at telecominication company which is major one and also undergraduate student.I have lots of options sitting front.By know i know c,c++,c#,java languages on stand alone application side,on mobile side i trying to get into android world and also know php,mysql,asp.net and also java ee,spring on web... | Just find a project that you find interesting (regardless of whether its standalone, mobile or web). And just work at it, you'll gain valuable experience not just in the specifics of whatever the project is aimed at, but also as a programmer in general, these skills will carry over into the other fields.
Really just fi... |
1,308,013 | 1,308,062 | Audio analyzer for finding songs pitch | Is there anyway to analyze the audio pitches programmatically. For example, i know most of the players show a graph or bar & if the songs pitch is high @ time t, the bar goes up at time t .. something like this. Is there any utility/tool/API to determine songs pitch so that we interpolate that to a bar which goes up & ... | Naive but robust: transform a modest length segment into Fourier space and find the peaks. Repeat as necessary.
Speed may be an issue, so choose the segment length as a power of 2 so that you can use the Fast Fourier Transform which is, well, fast.
Lots of related stuff on SO already. Try: https://stackoverflow.com/se... |
1,308,052 | 1,308,108 | Policy with catching std::bad_alloc | So I use Qt a lot with my development and love it. The usual design pattern with Qt objects is to allocate them using new.
Pretty much all of the examples (especially code generated by the Qt designer) do absolutely no checking for the std::bad_alloc exception. Since the objects allocated (usually widgets and such) are... | The problem is not "where to catch" but "what to do when an exception is caught".
If you want to check, instead of wrapping with try catch you'd better use
#include <new>
x = new (std::nothrow) X();
if (x == NULL) {
// allocation failed
}
My usual practice is
in a non-interactive program, ca... |
1,308,472 | 1,308,694 | Visual Studio 2008 sp1 vc++ project works in 32 bit mode, but not 64 bit | I have a project that runs perfectly well under windows 7, x86 installation. On the same machine, but in a different drive, I've installed windows 7, x64, and visual studio 2008 sp1 on both.
The project compiles and runs under win32. When I try to compile the project under x64, I get nothing, and everything gets 'ski... | The solution! Posted because I lost so much time to this, and I'd hope that someone else does not similarly lose time (otherwise, I'd just delete the question).
Apparently, the visual studio 2008 installer declined to install the x64 compiler tools by default on my machine. I don't know if that's because I'm on an AM... |
1,308,899 | 1,308,925 | How to pointer-cast Foo** to const Foo** in C++ | I have
class Fred
{
public:
void inspect() const {};
void modify(){};
};
int main()
{
const Fred x = Fred();
Fred* p1;
const Fred** q1 = reinterpret_cast<const Fred**>(&p1);
*q1 = &x;
p1->inspect();
p1->modify();
}
How would it be possible to do the
const Fred** q1 = &p1
via pointer-casting?
(I have j... | You want const_cast.
|
1,309,129 | 1,309,133 | Convert a pointer to an array in C++ | The CreateFileMapping function returns a pointer to a memory mapped file, and I want to treat that memory mapping as an array.
Here's what I basically want to do:
char Array[] = (char*) CreateFileMapping(...);
Except apparently I can't simply wave my arms and declare that a pointer is now an array.
Do you guys have an... | You do not need to. You can index a pointer as if it was an array:
char* p = (char*)CreateFileMapping(...);
p[123] = 'x';
...
|
1,309,187 | 1,309,221 | Reading binary data with seekg fails | I'm trying to read binary data from a specific offset.
I write the data in the following way:
long RecordIO::writeRecord(Data *record)
{
this->openWrite();
fstream::pos_type offset = file->tellp();
file->write(reinterpret_cast<char*>(record), sizeof(Data));
return (long)offset;
}
The offset returned i... | You do this:
file->write(reinterpret_cast<char*>(record), sizeof(Data));
Do you ever close or flush the file? The data will be buffered in memory to be written to disk later unless you force it.
|
1,309,384 | 1,309,416 | regdeletekey returning file not found | I've been playing with this and I can't understand why the RegDeleteKey function is resulting to a file not found error..
I created this test key and it exists. HKLM\Software\test
I am also the administrator of this computer. OS is Vista 32 bit.
int main()
{
HKEY hReg;
LONG oresult;
LONG dresult;
ores... | According to the MSDN page, the second parameter is a subkey of the key in hKey:
The name of the key to be deleted. It
must be a subkey of the key that hKey
identifies, but it cannot have
subkeys. This parameter cannot be
NULL.
That means your code actually tries to delete HLKM\SOFTWARE\test\SOFTWARE\test.
Yo... |
1,309,432 | 1,309,968 | Selected item in my CListCtrl shows ellipsis, despite having plenty of room! | I have a CListCtrl with plenty of room for all of the items, and they all display correctly --- until selected! As soon as any entry is selected, the end of that entry is truncated and an ellipsis is added:
Click for Image
I have no idea why this is happening. You can't see it in this image, but even very short entri... | I'd try adding
myListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT);
before the InsertColumn line and see if that helps.
|
1,309,509 | 1,309,514 | Correct way to marshal SIZE_T*? | I have the following C++ function definition, which I am trying to call through PInvoke from managed code:
bool FooBar(SIZE_T* arg1);
My managed declaration looked as follows:
[DllImport("mydll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern bool FooBar(ref uint arg1);
Some of you may notice the ... | Using IntPtr and/or UIntPtr is doing it properly - the types are there specifically for this purpose! I do not understand why you consider it an "ugly hack". I'm also not sure what your proposed alternative would be - any kind of attribute to allow values to be mapped to uint would be inherently wrong, because C# uint ... |
1,309,612 | 1,309,734 | How do I unit test a console input class? | In one of my applications I have a class which is responsible for user input. The default method of input is the console (keyboard), and I want to write some unit tests for it to make sure it is correct.
I am considering using the google-test framework for my unit testing, which makes it easy to automate all the tes... | You could use expect.
|
1,309,921 | 1,309,937 | Storing a List of Objects | Let's say I have a generic Object class, and a generic List class. I want to maintain a list of these Objects. Should I store them as List<Object> or List<Object*>?
If I use List<Object> and I have a method like:
if(some_condition) {
Object obj;
myObjectList.append(obj);
}
And my list class only keeps a refere... | EDIT:
As mentioned in a comment boost::ptr_list is even better since it is more efficient and has the same net effect as a std::list<boost::shared_ptr<T> >.
EDIT:
You mention that you are using Qt in your comment. If you are using >= 4.5 you can use Qt's QList and QSharedPointer classes like this:
QList<QSharedPointer... |
1,310,214 | 1,310,392 | Register an object creator in object factory | I have the convenient object factory template that creates objects by their type id names. The implementation is pretty obvious: ObjectFactory contains the map from std::string to object creator function. Then all objects to be created shall be registered in this factory.
I use the following macro to do that:
#define R... | So you want to put variables definitions in header file? There is a portable way: static variables of template classes. So we get:
template <typename T, typename I>
struct AutoRegister: public I
{
// a constructor which use ourRegisterer so that it is instantiated;
// problem catched by bocco
AutoRegiste... |
1,310,272 | 1,322,478 | Difference between use C# and C or C++ on windows mobile | I am new to windows mobile development. I have certain doubts related to windows mobile development which are as follows.
1) What is the major difference between C# and C (C++) as far as selecting language for development. ( not syntactically ) .
2) Which language should i select for development and Why ??
3) If i... | 1) Applications written in native code will run faster. Furthermore, memory footprint is smaller in native applications.
2) It depends on application you are writing. If it does not demand top performance and if it does not require a lot of native functionality, then the code should be managed. If you need a lot of fle... |
1,310,338 | 1,311,700 | Does any C++ Component Framework beyond Corba Components exist? | I'm looking for a C++ Component Framework like EJB3 (sure, it's Java only) or Corba Components. But I'm not looking for Corba Components.
My requirements are
portable (linux, unix, optional Windows)
C++ interfaces (so, it's not a requirement for the framework itself to be written in C++)
optinal well documented or goo... | I'm aware of a few things. I'm only remembering of (I don't have access to my bookmarks file)
ICE
Facebook's Thrift
I know there are other component oriented frameworks in C++.
|
1,310,344 | 1,310,405 | Why use !! when converting int to bool? | What can be a reason for converting an integer to a boolean in this way?
bool booleanValue = !!integerValue;
instead of just
bool booleanValue = integerValue;
All I know is that in VC++7 the latter will cause C4800 warning and the former will not. Is there any other difference between the two?
| The problems with the "!!" idiom are that it's terse, hard to see, easy to mistake for a typo, easy to drop one of the "!'s", and so forth. I put it in the "look how cute we can be with C/C++" category.
Just write bool isNonZero = (integerValue != 0); ... be clear.
|
1,310,473 | 1,312,807 | Regex matching spaces, but not in "strings" | I am looking for a regular exression matching spaces only if thos spaces are not enclosed in double quotes ("). For example, in
Mary had "a little lamb"
it should match the first an the second space, but not the others.
I want to split the string only at the spaces which are not in the double quotes, and not at the qu... | (I know you just posted almost exactly the same answer yourself, but I can't bear to just throw all this away. :-/)
If it's possible to solve your problem with a regex split operation, the regex will have to match even numbers of quotation marks, as MSalters said. However, a split regex should match only the spaces yo... |
1,310,643 | 1,310,774 | const reference binding to an rvalue | Working on this question, I found an inconsistent behavior.
Why reference binding behave different in a constructor from a common function?
struct A {
};
struct B : public A {
B(){}
private:
B(const B&);
};
void f( const B& b ) {}
int main() {
A a( B() ); // works
A const & a2 = B(); // C++0x: works, C++03... | A a(B());
is the declaration of a function named a returning an A and taking a pointer to a function without argument returning a B. See
here.
Add parenthesis and you'll get the error you expect:
A a((B()));
|
1,310,790 | 1,310,911 | Bad Re-throw compiles but crash at runtime | Following code will compile but crash at run time:
int main() {
try {
throw;
}
catch(...){
cout<<"In catch";
}
return 0;
}
Result: “Unhandled exception at 0x7c812a5b in hello.exe: Microsoft C++ exception: [rethrow] @ 0x00000000”
Why compiler allows the code to compile? it looks n... | From C++ Standard (15.1.8)
If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate()
As standard allows it and gives clear semantics, a compiler can only conform to it.
|
1,310,853 | 1,310,905 | Uses of std::basic_string | The basic_string class was apparently designed as a general purpose container, as I cannot find any text-specific function in its specification except for the c_str() function. Just out of curiosity, have you ever used the std::basic_string container class for anything else than storing human-readable character data?
T... | It was designed as a string class (hence, for example, length() and all those dozens of find functions), but after the introduction of the STL into the std lib it was outfitted to be an STL container, too (hence size() and the iterators, with <algorithm> making all the find functions redundant).
It's main purpose is t... |
1,310,922 | 1,310,943 | Accessing private class in operator<< in namespace | I have a class CFoo with a private inner class CBar. I want to implement a stream ouput operator for CFoo, which in turn uses a stream output for CBar in it's implementation. I can get this working when CFoo is in the common namespace, but when i place it in a new namespace (namespace foobar), the operator can no longe... | Simply put the code in the .cpp file into the namespace:
namespace foobar {
// your existing code
}
|
1,311,166 | 1,314,452 | How to pinpoint where a long function returns | Suppose there is a function with 1000 code of line named LongFunction, and we used it:
bool bSuccess = LongFunction();
assert(bSuccess);
Here I got an assert when debugging, and I know there is something wrong with LongFunction, so I need to find where the function meet problems and returns:
I could probably debug it... | Obviously you ought to refactor this function, but in C++ you can use this simple expedient to deal with this in five minutes:
class ReturnMarker
{
public:
ReturnMarker() {};
~ReturnMarker()
{
dummy += 1; //<-- put your breakpoint here
}
static int dummy;
}
int ReturnMarker::dummy = 0;
and t... |
1,311,242 | 17,080,640 | Precise floating-point<->string conversion | I am looking for a library function to convert floating point numbers to strings, and back again, in C++. The properties I want are that str2num(num2str(x)) == x and that num2str(str2num(x)) == x (as far as possible). The general property is that num2str should represent the simplest rational number that when rounded t... | I think this does what you want, in combination with the standard library's strtod():
#include <stdio.h>
#include <stdlib.h>
int dtostr(char* buf, size_t size, double n)
{
int prec = 15;
while(1)
{
int ret = snprintf(buf, size, "%.*g", prec, n);
if(prec++ == 18 || n == strtod(buf, 0)) return ret;
}
}
... |
1,311,321 | 1,311,831 | Private members vs temporary variables in C++ | Suppose you have the following code:
int main(int argc, char** argv) {
Foo f;
while (true) {
f.doSomething();
}
}
Which of the following two implementations of Foo are preferred?
Solution 1:
class Foo {
private:
void doIt(Bar& data);
public:
void doSomething() {
... | From a design point of view, using temporaries is cleaner if that data is not part of the object state, and should be preferred.
Never make design choices on performance grounds before actually profiling the application. You might just discover that you end up with a worse design that is actually not any better than th... |
1,311,953 | 1,311,971 | Starting a new Windows app: Should I use _TCHAR or wchar_t for text? | I'm coding up a new (personal hobby) app for Windows in c++.
In previous low-level Windows stuff I've used _TCHAR (or just TCHAR) arrays/basic_strings for string manipulation.
Is there any advantage to using _TCHAR over straight up Unicode with wchar_t, if I don't care about Windows platforms pre Win2k?
edit: after su... | No there is not. Just go with wchar_t.
TCHAR is only useful if you want to be able to use a conditional compilation switch to convert your program to operate in ASCII mode. Since Win2K and up are unicode platforms this switch does not provide any value. You'd instead be implying to other developers in your project... |
1,312,056 | 1,314,436 | Can I call a Win32 API from the Visual Studio Immediate Window? | I'm debugging a C++ Win32 application and I'd like to call an arbitrary Win32 API from the context of that process, as though the program had run this line of code:
DestroyWindow(0x00021c0e);
But entering that into the Immediate Window gives:
CXX0017: Error: symbol "DestroyWindow" not found
Edit: Using the full name ... | Once you have the function address (as you've done in the updated question), you can try casting it to a function pointer and calling it:
(*(BOOL (*)(HWND))0x76600454)((HWND)0x00021c0e)
The first part of that casts the address to BOOL (*)(HWND), which is a pointer to a function taking an HWND parameter and returning B... |
1,312,132 | 1,312,152 | Boolean in ifdef: is "#ifdef A && B" the same as "#if defined(A) && defined(B)"? | In C++, is this:
#ifdef A && B
the same as:
#if defined(A) && defined(B)
?
I was thinking it wasn't, but I haven't been able to find a difference with my compiler (VS2005).
| They are not the same. The first one doesn't work (I tested in gcc 4.4.1). Error message was:
test.cc:1:15: warning: extra tokens at
end of #ifdef directive
If you want to check if multiple things are defined, use the second one.
|
1,312,241 | 1,312,267 | using a static const int in a struct/class | struct A {
static const int a = 5;
struct B {
static const int b = a;
};
};
int main() {
return A::B::b;
}
The above code compiles. However if you go by Effective C++ book by Scott Myers(pg 14);
We need a definition for a in addition to the declaration.
Can anyone explain why this is an exc... | C++ compilers allow static const integers (and integers only) to have their value specified at the location they are declared. This is because the variable is essentially not needed, and lives only in the code (it is typically compiled out).
Other variable types (such as static const char*) cannot typically be defin... |
1,312,439 | 1,313,543 | What is the major authority (ies) for big C++ projects? | For many years, I have been re-reading John Lakos's classic Large-Scale C++ Software Design. Not only it was the first guidebook of this kind, but it also revolutionized how to develop a project in C++, in an efficient fashion to this day!
Do you feel his ideas are outdated now? Some C++ techniques in the book are ... | Interestingly, his next book, Scalable C++: Component-Based Development, is anticipated in 2006.
I don't think it has ever came to fruition... one day it may!
Also, Agile Principles and patterns are widespread and effective software developing paradigm. I am shifting my gears in that directions.
Check out this book: A... |
1,312,540 | 1,312,628 | How to implement smart pointer which can be instantiated with void? | Some smart pointer templates, such as boost::shared_ptr, may be instantiated with void to hold an arbitrary object:
http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/sp_techniques.html#pvoid
Below is a minimal scoped_ptr implementation. When instantiated with void, the compiler complains about an illegal "reference t... | You could use a type trait for the reference type:
template<typename T>
struct type_trait
{
typedef T& reference;
};
template<>
struct type_trait<void>
{
typedef void reference;
};
then in your scoped_ptr_impl :
typename type_trait<T>::reference operator*()
{
return *m_ptr;
}
Not sure if void is the righ... |
1,312,672 | 1,314,991 | Simple client/server, TCP/IP encrypting the message stream, SSL (C++) | Basically my question is the exact same one as this:
Simple client/server, TCP/IP encrypting the message stream, SSL
The difference is that I need this for pure C++, not .NET. I cannot use 3rd party libraries, so unless it's a Windows system component (like the above) I need something with source so I can get the gene... | Writing your own encryption code is "not recommended". It's easy enough to make a simple mistake when using one of these libraries, let alone when you try to write one yourself.
What you really want to use is OpenSSL with Boost.ASIO on top of it. If you can't do that then your next best alternative is to use the Intern... |
1,312,922 | 1,312,957 | Detect if stdin is a terminal or pipe? | When I execute "python" from the terminal with no arguments it brings up the Python interactive shell.
When I execute "cat | python" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe.
How would I do a similar detection in C or C+... | Use isatty:
#include <stdio.h>
#include <io.h>
...
if (isatty(fileno(stdin)))
printf( "stdin is a terminal\n" );
else
printf( "stdin is a file or a pipe\n");
(On windows they're prefixed with underscores: _isatty, _fileno)
|
1,313,001 | 1,317,867 | Intel C++ Compiler for Windows CE | Two years ago I used eMbedded Visual Studio for Windows CE based application development. I had about 40% app performance acceleration with Intel C++ Compiler(v1.2 or v2.0) in comparison with default MS compiler (floating point issues, ARM). It was looked really helpful for me.
I do remember that downloaded it from of... | Well, this is not too surprising. Since Intel intends to get to the embedded market with Atom they sold the XSCALE department to Marvell along with all other related products. I just checkd Marvell's extranet and they have a C++ compiler for Windows CE V2.2, dedicated for the XSCALE technology. You need to register to ... |
1,313,005 | 1,313,023 | How to get a Windows Service custom Status? [C++/C#] | I have a created a C# windows service (Serv.exe) which is responsible for performing various tasks at the request of a running application (A.exe), some of these can take long periods of time and I need a way to know the status of my requested operation (running on the service) from the calling application (A.exe).
Cur... | In the past, when I've had to handle more complex communication, I usually switch from QueryServiceStatus to having the service actually provide a means of communication via IPC.
Sockets and Pipes both work very well for this. The client and service can have pretty much an unlimited freedom in terms of what is communi... |
1,313,063 | 1,313,162 | request for member `...' is ambiguous in g++ | I'm getting the following compile error in one of my classes, using gcc 3.4.5 (mingw):
src/ModelTester/CModelTesterGui.cpp:1308: error: request for member `addListener' is ambiguous
include/utility/ISource.h:26: error: candidates are: void utility::ISource<T>::addListener(utility::IListener<T>*) [with T = const SConso... | Looks like your situation is like this:
struct A {
void f();
};
struct B {
void f(int);
};
struct C : A, B { };
int main() {
C c;
c.B::f(1); // not ambiguous
c.f(1); // ambiguous
}
The second call to f is ambiguous, because in looking up the name, it finds functions in two different base class scopes... |
1,313,073 | 1,313,284 | boost:thread crashes microsoft C++ compiler | Brief version of my question:
This code crashes the compiler.
pThread[0] = new boost::thread(
boost::bind(
&cGridAnimator::DoJob, // member function
this ), // instance of class
0 ); // job number
The compiler crashes when attempting to compile this code. ( It is not... | Change the code into:
pThread[0] = new boost::thread(boost::bind(&cGridAnimator::DoJob, this, 0 ));
This code gives a void (void) function to the thread instead of a void (int) function and an extra argument.
|
1,313,157 | 1,313,188 | Multiplying and adding images with CImg In C++ | I am trying to find C in the following function in CImg
C=B*L+(1-B)S
Where C, L and S are all RGB images of the same size (and B is a single channel grayscale matte)
I cannot figure out how to loop over the pixels. I've seen code like:
cimg_forXYZ(S,x,y,z) {... }
But I have never see than kind of syntax before, could... | If you look into the CImg header, you'll see that that code is, in fact, a macro that thunks down into:
#define cimg_forXY(img,x,y) cimg_forY(img,y) cimg_forX(img,x)
#define cimg_forX(img,x) for (int x=0; x<(int)((img).width); ++x)
#define cimg_forY(img,y) for (int y=0; y<(int)((img).height); ++... |
1,313,246 | 1,313,291 | is it possible to have getline() function accept wistream& | Just for clarification, I'm referring to the global getline() function in the string class.
What I want to do is to have something like this:
int main()
{
wifstream in(L"textfile.txt");
someFunc(in);
return 0;
}
void someFunc(const wistream& read)
{
wstring buff;
while(getline(read, buff))
{
... | It does accept a wistream, but getline() demands a non-const argument because it modifies the stream. Try changing it to:
...
void someFunc(wistream& read)
...
|
1,313,259 | 10,354,776 | Tiling Simplex Noise? | I've been interested (as a hobbyist) in pseudo-random noise generation, specifically the Perlin and Simplex algorithms. The advantage to Simplex is speed (especially at higher dimensions), but Perlin can be tiled relatively easily. I was wondering if anyone was aware of a tiling simplex algorithm? Fixed-dimension is fi... | It would seem this question has been reasonably solved here, with a detailed description of the idea behind the working solution here. A fantastic answer to a long-standing problem!
|
1,313,727 | 1,314,022 | return by value inline functions | I'm implementing some math types and I want to optimize the operators to minimize the amount of memory created, destroyed, and copied. To demonstrate I'll show you part of my Quaternion implementation.
class Quaternion
{
public:
double w,x,y,z;
...
Quaternion operator+(const Quaternion &other) const;
}
... | Your first example allows the compiler to potentially use somehting called "Return Value Optimization" (RVO).
The second example allows the compiler to potentially use something called "Named Return Value Optimization" (NRVO). These 2 optimizations are clearly closely related.
Some details of Microsoft's implementatio... |
1,313,988 | 1,314,025 | C++: what is the optimal way to convert a double to a string? | What is the most optimal way to achieve the same as this?
void foo(double floatValue, char* stringResult)
{
sprintf(stringResult, "%f", floatValue);
}
| I'd probably go with what you suggested in your question, since there's no built-in ftoa() function and sprintf gives you control over the format. A google search for "ftoa asm" yields some possibly useful results, but I'm not sure you want to go that far.
|
1,314,432 | 1,314,459 | c++ template problem in cross-platform code | I'm having some trouble getting this code to compile on Linux but it works perfectly in Windows.
Windows compiler: Visual Studio 2005
Linux compiler: gcc version 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)
class DoSomething
{
public:
template <class DataType>
bool Execute()
{
//do something here
}
};... | The problem is that when the compiler encounters Op.Execute<char>(); and tries to parse it, it gets confused.
Op is a dependant name, so the compiler doesn't know much about its members. So it doesn't know that Execute is a template function. Instead, it assumes that the < means less than.
That you're trying to compar... |
1,314,526 | 1,314,539 | What is a pseudo-virtual function in C++? | What is a pseudo-virtual function in C++?
| AFAIK it's not a term that appears anywhere with an official definition.
Perhaps someone is talking about simulated dynamic binding?
Edit: a swift web search suggests that someone might have implemented their own dynamic polymorphism, so they perhaps have their own vtables. "Pseudo-virtual" functions would then be func... |
1,314,717 | 1,314,877 | how do I get the non-flag and non-option tokens after boost::program_options parses my command line args | In python, I can construct my optparse instance such that it will automatically filter out the options and non-option/flags into two different buckets:
(options, args) = parser.parse_args()
With boost::program_options, how do I retrieve a list of tokens which are the remaining non-option and non-flag tokens?
e.g. If m... | IIRC, you have to use a combination of positional_options_description and hidden options. The idea is to (1) add a normal option and give it a name, maybe something like --positional=ARG, (2) don't include that option in the help description, (3) configure command_line_parser to treat all positional arguments as if --... |
1,314,775 | 1,314,803 | Socket send question | Is there any reason why this shouldn't work?
[PseudoCode]
main() {
for (int i = 0; i < 10000; ++i) {
send(i, "abc", 3, 0);
}
}
I mean, to send "abc" through every number from 0 to 10000, aren't we passing in theory by a lot of different sockets? Most numbers between 0 and 10000 will not... | That will never work. File descriptors are useful only within the same process (and its children).
You have to create a socket (this will get you a file descriptor you own and can use), connect it to an end point (which of course has to be open and listening) and only then you can send something through it.
For exampl... |
1,314,821 | 1,315,543 | accessing element of boost sparse_matrix seems to stall program | I've got a strange bug that I'm hoping a more experience programmer might have some insight into. I'm using the boost ublas sparse matrices, specifically mapped_matrix, and there is an intermittent bug that occurs eventually, but not in the initial phases of the program. This is a large program, so I cannot post all th... | Some things to try to debug the code (not necessarily permanent changes):
Change the bool to an int in the matrix type for c, to see if the matrix expects numeric types.
Change the matrix type to another with a similar interface, possibly plain old matrix.
Valgrind the app (if you're on linux) to check you're not corr... |
1,314,824 | 1,314,891 | Implementing Smart Pointer - Dynamic Allocation with templates | I'm in the process of writing a smart pointer countedptr and I've hit a speed bump. The basic function of countedptr is to work like any other smart pointer and also have a count of how many pointers are pointing to a single object. So far, the code is:
[SOLVED]
#include "std_lib_facilities.h"
template <class T>
class... | Old Solution
What about another assignment operator?
counted_ptr& counted_ptr::operator=(T* p)
{
if (! --*count) { delete count; }
pointer = p;
count = new int(1);
return *this;
}
...
one = new double(5);
Also, your destructor always deletes a shared pointer, which is probably what caused *one to be ... |
1,314,916 | 1,314,934 | What really is the SOCKET type? | I can see it looks like an alias for an unsigned int pointer, right? Is it just like a pointer in memory? To what would it be actually pointing? Is it pointing to a struct? If yes, how is that struct defined? Is it just a number that is used by socket functions and does not map to a memory address?
| In Win32, a SOCKET data type is the same as a HANDLE, which is an integer used to refer to a kernel data structure of some kind. This kernel data structure is "opaque", which means that application programs do not need to (and in fact cannot) see the internals of the structure. All access to Win32 SOCKETs is done throu... |
1,315,041 | 1,315,072 | How can I iterate through a string and also know the index (current position)? | Often when iterating through a string (or any enumerable object), we are not only interested in the current value, but also the position (index). To accomplish this by using string::iterator we have to maintain a separate index:
string str ("Test string");
string::iterator it;
int index = 0;
for ( it = str.begin() ; it... | I've never heard of a best practice for this specific question. However, one best practice in general is to use the simplest solution that solves the problem. In this case the array-style access (or c-style if you want to call it that) is the simplest way to iterate while having the index value available. So I would ce... |
1,315,250 | 1,315,289 | Using ALSA's function snd_pcm_writei can I free the sample buffer right away? | Using ALSA to play audio, after calling snd__pcm__writei, can I free the sound sample buffer right away or do I need to wait until the sound is finished playing before I can free the sample buffer?
For example:
unsigned short *buffer;
buffer = malloc(size of sample to play);
...load data into buffer...
snd_pcm_writei ... | Easiest way to find out would be to start writing backwards from the end of the buffer and see if you affect the audio playback. If you do then you definitely can't free the buffer. If it makes no difference then you can safely free the buffer as the sound card is not reading from that particular block of memory.
|
1,315,263 | 1,315,285 | LinkedList "node jump" | Trying to figure out why my list() class pointers are being overwritten with the third node. What happens in the insert function (below) is that the third time the insert function is called my headByName->nextByName node pointer is overwritten by the third node, when it should point to the second. So as you can guess t... | I think that problem is here:
headByName->nextByName = next_node;
headByRating->nextByRating = next_node;
You're always override second node. As I understand you should find last one by iterating through whole list and insert after last node.
|
1,315,266 | 1,315,309 | Displaying another app in my form | I remember I had some app the launched other applications and placed them in tabs in it's form without the titlebars.
I wonder how can that be done?
Preferably with C# but if it's not possible/too hard within .NET C++ is fine too.
Thanks.
| Applications like Excel and Internet Explorer provide specific support (OLE) for being embedded in other windows, so third-party application can run an instance of them within their own window easily.
If the application you wish to embed doesn't supply specific support for it, it would be much harder to achieve. It's e... |
1,315,475 | 1,315,504 | Is it possible to use 'using' declaration on the static class function [C++]? | Is it legal?
class SomeClass {
public:
static void f();
};
using SomeClass::f;
Edit: I forgot to qualify function. Sorry.
| No, it is not. The using keyword is used to bring one or all members from a namespace into the global namespace, so that they can be accessed without specifying the name of the namespace everytime we use the members.
In the using statement you have given, the name of the namespace is not provided. Even if you had provi... |
1,315,534 | 1,315,551 | Why is my destructor never called? | I have a base class A and a derived class B:
class A
{
public:
virtual f();
};
class B : public A
{
public:
B()
{
p = new char [100];
}
~B()
{
delete [] p;
}
f();
private:
char *p;
};
For any reason the destructor is never called - why? I dont understand th... | Your base class needs a virtual destructor. Otherwise the destructor of the derived class will not be called, if only a pointer of type A* is used.
Add
virtual ~A() {};
to class A.
|
1,315,826 | 1,315,832 | Sharing objects between C# and C++ code | Is it possible to share references to C# objects between C# and C++ code without massive complexity? Or is this generally considered a bad idea?
| The best solution for sharing a C# object between native and managed code is to use COM interop. This allows you to essentially share an interface of an object between managed code and it's equivalent signature in C++.
As for the complexity side of things. The majority of COM interop scenarios are straight forward ... |
1,315,831 | 1,315,862 | Line-breaking algorithm | Where can I find an efficient algorithm for breaking lines of text for formatted display?
| One approach to this very problem is addressed in the book Introduction to Algorithms (Cormen, Leiserson, Rivest, Stein) as problem 15-2.
It takes the approach that a nicely broken block of text has as even spacing at the end as possible, punishing large differences.
This problem is solvable using dynamic programming.... |
1,315,926 | 1,316,016 | GCC: Empty program == 23202 bytes? | test.c:
int main()
{
return 0;
}
I haven't used any flags (I am a newb to gcc) , just the command:
gcc test.c
I have used the latest TDM build of GCC on win32.
The resulting executable is almost 23KB, way too big for an empty program.
How can I reduce the size of the executable?
| Don't follow its suggestions, but for amusement sake, read this 'story' about making the smallest possible ELF binary.
|
1,316,092 | 1,316,275 | Updating Boost Wave from SVN | I have run into some bugs into one of the boost components that I am using. After analyzing the problem a bit, I've found that I was not the only one, and the author had already issued a fix that is available in the boost SVN trunk.
What would be the best approach if I wanted to update just this component and reuse the... | Here's what I ended up doing:
First I checked out the version of the wave lib where the issue was fixed (53230). After diffing it to my local copy, I have found the following changes:
- wave was reusing a boost.iterator implementation instead of providing its own
- the flex_string implementation was updated
- a ref co... |
1,316,170 | 1,316,650 | Having an image file buffer in memory, what is the fastest way to create its thumbnail? | Trying to create a an image acquiring application optimized for a fast scanner (which can provide up to 6 compressed images [color+gray+binary][front+rear] for each paper at speed of 150 ppm) I have some speed issues.
Using TWAIN technology and memory buffer transfer mode (TWSX_MEMORY) I receive image buffer (as JPEG... | If it's a JPEG image, you can simply discard most of the DCT data, and create a thumbnail at a power of two size, using only the DCT coefficients.
If you can find the sources for it, take a look at EPEG from the Enlightenment project. It does exactly what you're looking for with JPEG files, entirely without decoding or... |
1,316,320 | 1,321,004 | A C++ code generator from an XML spec | I'd like to know if there's a tool which allows you to do class definition based on an XML format. I'm not looking for data binding. Anyone can help ?
Thanks
| I know of two tools both of them are commercial products
http://www.codesynthesis.com/products/xsd/
Is open source GPL - commercial licence is avalable for commercial use
I think this is/was used by gSOAP
http://www.artima.com/cppsource/xml_data_binding.html
http://www.codalogic.com/lmx/
don't know any more than th... |
1,316,439 | 1,316,450 | rand() doesn't obey srand() in Qt Creator | I've written a program in Qt Creator 1.0.0 (Qt version 4.5.0) where at the beginning of main() function I've put
srand(time(0));
Then I'm calling rand() from another thread (subclass of QThread). In that function, rand() is producing same sequence of numbers each time I'm running the program. I'm not running the prog... | You need to call srand in each thread, because the seed is stored in a thread-specific block.
|
1,316,601 | 1,316,620 | Implementing Smart Pointer - storing template class in vector | I'm having trouble storing instances of my smart pointer into a container. Here is the code for the pointer.
#include "std_lib_facilities.h"
template <class T>
class counted_ptr{
private:
T* pointer;
int* count;
public:
counted_ptr(T* p = 0, int* c = new int(1)) : pointer(p), count(c) {} // default con... | You may want to try this:
test.push_back(counted_ptr<double>(one));
You copy constructor is explicit which means that the compiler won't implicitly invoke it.
Personally, I would make the raw pointer constructor explicit and the copy ctor not explicit. That would be closer to usual behavior.
EDIT: I also recommend tha... |
1,316,699 | 1,316,775 | c++ return if invalid input | I have done up a program which requires the following:
prompts user input account no
prompts user input account type
if account type == a, prompts some input and does a certain formula [if]
if account type == b, prompts some input and does another formula [else if]
if account type is wrong(not a or b), prompts erro... | You have to use a loop to keep asking for an account type if the type is wrong:
do
{
//1
do
{
//2
if (type =="a")
//2.1
else if(type=="b")
//2.2
else
//2.3
}
while (type != "a" and type != "b");
//3
if(input == "y")
... |
1,316,747 | 1,316,763 | How is the C++ standard library linked to my application? | When I usually use code (include headers) from 3rd party (non-standard) C++ libraries, a pre-built binary file is linked to (or included in) the target executable that represents my application, but what happens with C++ standard library?, as far as I have seen I don't have to ship a library with an application that us... | No, the standard libraries by default are dynamically linked at runtime.
When running the dynamic loader will look in a couple of standard places for dynamic libraries if it finds it loads and runs otherwise the application quits.
On Unix Systems:
/usr/lib: look for: libstdc++*
On Windows:
c:\windows\system32 look f... |
1,316,809 | 1,316,829 | Recursive function with static variable | I have a recursive function with a static variable "count". The function increments count recursively and since it has file scope, when I call foo() a second time, count is still equal to 5. Is there a technique to reset count to 0 before the second time foo() is called?
Basically, I don't want count to have file scope... | A more idiomatic way is to split it into two functions:
void foo() {
foo_recursive(0);
}
void foo_recursive(int count) {
if (count < 5) {
count++;
cout << count << endl;
foo_recursive(count);
} else {
cout << "count > 5" << endl;
}
}
Which has the benefit of not requirin... |
1,316,924 | 1,317,061 | Are return values going to be passed by rvalue reference in c++0x? | Let's say I have a function:
typedef std::vector<int> VecType;
VecType randomVector();
int processing()
{
VecType v = randomVector();
return std::accumulate(v.begin(), v.end(), 0);
}
Does C++0x specifically say the spurious copy will be averted from the return value of randomVector? Or would a compiler need t... | The rule is the following
If the compiler can do RVO, then it is allowed to do it, and no copy and no move is made.
Otherwise, the appropriate constructor is taken.
Like you say, the temporary is an rvalue, and thus the move constructor is selected, because of a rule in 13.3.3.2/3, which says that a rvalue referenc... |
1,317,123 | 1,317,661 | How to Avoid DOS Attack using Berkeley Sockets in C++ | I'm working my way through UNIX Network Programming Volume 1 by Richard Stevens and attempting to write a TCP Echo Client that uses the Telnet protocol. I'm still in the early stages and attempting to write the read and write functions.
I'd like to write it to use I/O Multiplexing and the Select function, because it... |
... are there any other ways of avoiding such an attack?
Yes, asynchronous I/O is another general approach.
If the problem is that a blocking read() may suspend your execution indefinitely, your general countermeasures are then:
Have multiple threads of executionmulti-threaded, multi-process, both.
Time-limit the bl... |
1,317,130 | 1,317,143 | Random segfaults in C++ | I'm new to C++ and I haven't a clue where to start, so I uploaded the code to a pastebin because there is a lot of it.
This code compiles fine, and doesn't give off a warning, even with gcc's -Wall option.
It's supposed to generate all prime numbers up to a number given as a command line parameter.
On smaller numbers (... | int primes[max];
prime = primes;
while(*prime) {
*prime = 0;
prime++;
}
In the preceding code you can easily run randomly through a memory, Essentially you are going through RAM until you find a 0. If there are no 0s in your array then it will run into memory that doesn't not belong to the process and a... |
1,317,238 | 1,317,242 | C++ : error: invalid operands of types ‘String*’ and ‘const char [7]’ to binary ‘operator+’ | I'm learning cpp and In my last assignment I am rewriting the std::string class.
so here is an outline of my code:
string class:
class String {
public:
String(const char* sInput) {
string = const_cast<char*> (sInput);
}
const String operator+(const char* str) ... | You probably don't want to use a pointer to your String class. Try this code:
int main(int argc, char* argv[]) {
String testing = String("Hello, "); //works
testing.print();//works
String a = testing+"World!";
return 0;
}
When defining new operators for C++ types, you generally will work with the actua... |
1,317,295 | 1,317,408 | Checking if DWM/Aero is enabled, and having that code live in the same binary for 2000/XP/Vista/7 | I know the title makes little sense, mostly because it's hard to explain in just one line. So here's the situation:
I have a program who's binary is targeted at Windows 2000 and newer. Now, I went ahead and added some code to check if the user is running under Vista/7, and if so then check if Aero/DWM is enabled. Based... | Turns out I can just tell the linker to delayload the dwmapi.dll.
I'd like to thank ewanm89 because something he said sort of resonated and led me down the path to finding the actual answer.
|
1,317,424 | 1,317,471 | How to cope with extraneous characters left on the input stream? (cin skipped) | Sorry for the noobish question here, but I am just learning C++ and I am looking for the standard way of dealing with this problem. I am using VS2005.
Given a program:
#include <iostream>
using namespace std;
int main( )
{
while ( true )
{
cout << "enter anything but an integer and watch me ... | Alright, I found the answer. The answer is...
Don't do this. Do not mix formatted and unformatted input using operator >>. Here is a good article on the subject:
http://www.cplusplus.com/forum/articles/6046/
Basically, the code changes to:
#include <iostream>
#include <string>
#include <stream>
using namespace std;... |
1,317,871 | 1,317,883 | finished writing a poker hand evaluator looking for a new project | just finished writing a five card poker hand evaluator in C++. now im looking for a new project about the same level of difficulty. maybe a very simple DOS command parser?
| It sounds like you might be interested in the type of problems Project Euler offers. In particular, it sounds like you have a solution for Problem 54 already.
|
1,317,948 | 1,318,433 | Any built-in function to test if 4 is in [1,2,3,4] (vector) | In Ruby I can do:
[1,2,3,4].include?(4) #=>True
In Haskell I can do :
4 `elem` [1,2,3,4] #=> True
What should I do in C++?
| There isn't a built-in function doing exactly that.
There is std::find which comes close, but since it doesn't return a bool it is a bit more awkward to use.
You could always roll your own, to get syntax similar to JIa3ep's suggestion, but without using count (which always traverses the entire sequence):
template <typ... |
1,318,025 | 1,318,062 | How to declate a wide char constant in an IDL | We are migrating our C++ COM application to be unicode, and as part of this migration we want to migrate the constant strings in our IDL to unicode as well.
The problem is that at the moment, we still compile it both in ANSI and in UNICODE, which means that we can't use the L"String" construct to declare wide charts.
A... | I wonder why you need to have string constants in the IDL file, anyway. Wouldn't it be sufficient to have them in a header file? I see that Microsoft has wide string literals only in sapiaut.idl (looking at all platform SDK IDL files); as those few constants are never used, this might have been a mistake, as well. Also... |
1,318,458 | 1,318,516 | template specialization of template class | I want to specialize following member function:
class foo {
template<typename T>
T get() const;
};
To other class bar that depends on templates as well.
For example, I would like bar to be std::pair with some template parameters, something like that:
template<>
std::pair<T1,T2> foo::get() const
{
T1 x=...... | You can't partially specialize function templates, sorry but those are the rules. You can do something like:
class foo {
...
};
template<typename T>
struct getter {
static T get(const foo& some_foo);
};
template<typename T1, typename T2>
struct getter< std::pair<T1, T2> > {
static std::pair<T1, T2> get(const fo... |
1,318,525 | 1,319,141 | Policy based design decisions | I have a class called Device that accepts two policies as far as I can see: StatePolicy and BehaviorPolicy.
The StatePolicy holds and manages the state of the device.
The BehaviorPolicy wraps the device driver that is written in C or C++.
Now I have two questions:
How to coordinate between the state and the behavior... | Here is the full design that works and does it's job pretty well at it:
class AbstractState
{
public:
virtual ~AbstractState() {}
};
class AbstractDevice
{
public:
virtual ~AbstractDevice() {}
virtual void performAction() = 0;
virtual const string &getName() const = 0;
virtual void changeState(const Abstrac... |
1,318,533 | 1,318,566 | Threads using visual stdio2008 | I want to implement threading in c++.I am using visual stdio2008 and wish to implement threading using pthreads.can any one guide me about pthreads and also about there implementations in vs2008.Thanking in anticipation
| Why do you want to use a plain C API (pthreads) usually used in *nix (pthreads) use in C++ on Windows? Any other reason than ... Whatever.
Use boost.thread. It uses windows threads on windows, pthread on posix platforms. It works well, and is portable.
If you really want to use pthread, you will use something like ... |
1,319,132 | 1,319,162 | Comprehesive information on serial ports and programming? | What are some comprehesive sources on serial programming?
Ideally they would cover things like:
history of devices
current and future uses
how serial devices work
protocols
and, of course, how to program, preferably in C/C++
| This Wikipedia article covers a lot of it, and has links to other information, including
programming for Linux and WIN32
and
Serial Port Communication in VB.NET Programming
In addition to that, Wikibooks has a free book on Serial Programming
|
1,319,160 | 1,319,300 | Can a pointer be stored in std::mbstate_t type? | I'm writing an implementation of std::codecvt facet that uses iconv. This implementation stores a pointer to heap-allocated data in std::mbstate_t state argument.
Everything works fine, but is this code 64-bit compatible?
Is there a platform where a pointer size exceeds the size of std::mbstate_t?
| Doesn't the codecvt template take the state type as a parameter? Can you just use a pointer type there instead? I can't remember whether the various classes that use a codecvt place requirements on the state type.
Assuming that you can't just change the state type... on MSVC 2008, mbstate_t is typedefd as an int. Th... |
1,319,165 | 1,319,174 | Different destructor behavior between vc9 and gcc | The following code gives a different number of destructors when compiled on GCC and vc9. AFAIK when run on vc9 i get 5 destructors showing, which I understand. The + overloaded operator is called, and two object are created, when returned a temporary object is created. This makes destruction of 3 objects possible. When... | GCC is implementing the "return value optimization" to skip temporaries. Set VC9 to Release mode and it'll probably do the same.
If GCC is really good, it is seeing that temp inside operator+ will be default-initialized, just like somewhereDark, and can just use a reference to somewhereDark directly if it tries to inli... |
1,319,234 | 1,319,284 | Analyzing a crash in Windows: what does the error message tell us? | A small utility of mine that I made for personal use (written in C++) crashed randomly yesterday (I've used it roughly 100+ hours with no issues so far) and while I don't normally do this, I was feeling a bit adventurous and wanted to try and learn more about the problem. I decided to go into the Event Viewer and see w... | The 64-bit time stamp is the time application's primary thread was created in 100-nanosecond intervals since January 1, 1601 (UTC) (this is known as FILETIME). The 32-bit timestamp is indeed in time_t format (it tells the time the module was created and is stored in the module's header).
I'd say 0x0002d160 is an offset... |
1,319,260 | 1,319,323 | Where can I find a reference for the .vcproj file structure? | I looked on MSDN, couldn't find it.
I found an XML Schema for the .vcproj file, which is nice.
But what I really want is an explanation for each of the elements in the vcproj file, a reference.
The immediate question in front of me is, what is the significance of the UniqueIdentifier attribute in the element VisualStud... | I suspect Microsoft is not intending to make the format a documented one. Microsoft has stated in the past that documented features and formats require in some cases an order of magnitude more work.
If the format is not documented, it's because Microsoft wants it that way. Any documentation will be through analysis a... |
1,319,327 | 1,319,454 | Binary Tree Node Fault | Here's the node definition:
struct node{
int data;
stuct node * left;
struct node * right;
};
What I am trying to do is list all the nodes that point to an ancestor node. After posting the wrong solution and taking advice from the answers, my new solution is:
Recursively go through the binary tree. Add the... | Another way to accomplish this kind of check is to do a breadth-first sweep of the nodes, all the while keeping a vector of nodes you have visited already (which you can keep sorted by address). Each time you visit a node, assert it is not in the vector, then add it to the appropriate place to keep the visited list sor... |
1,319,482 | 1,319,601 | Forward-declaring template pointer | Do I really need three statements, i.e. like this
class A;
template<class _T> class B;
typedef B<A> C;
to forward-declare a pointer of template type C, like so:
C* c = 0;
I was hoping to be able to conceal the classes A and B in my forward-declaration, is that even possible?
| Although not exactly the same, you could do this instead:
class C;
C* c = 0;
and then later, in the implementation file, after the header files for "A" and "B" have been included, define "C" like this:
class C : public B<A> {};
Using inheritance instead of a typedef should work if you only need to use the default con... |
1,319,876 | 1,319,884 | Weird C++ templating issues | So basically the assignment was we had to create a doubly linked list that's templated generically instead of locked to a single data type. I've tried compiling both with gcc and msvc and both compilers are giving me roughly the same errors so I'm assuming its just my bad coding and not the quirkyness of one compiler ... | Your forward declaration says llist is a class:
class llist;
Then you say it is a template:
template<typename T>
class llist;
Similarly with iter.
I don't know how you could make it compilable easily. However, you can make node and iter 'inside' of llist.
|
1,320,401 | 1,320,417 | How to get Linux distribution name and version? | In Windows I read the registry key SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName to get the full name and version of the OS.
But in Linux, the code
struct utsname ver;
uname(&ver);
retVal = ver.sysname;
returns the string linux, not Ubuntu 9.04.
How can I get the Linux distribution name and version?
| Try:
cat /etc/lsb-release
You can also try
lsb_release -a
Or:
cat /proc/version
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.