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,837,854 | 2,838,033 | Initializing an object to all zeroes | Oftentimes data structures' valid initialization is to set all members to zero. Even when programming in C++, one may need to interface with an external API for which this is the case.
Is there any practical difference between:
some_struct s;
memset(&s, 0, sizeof(s));
and simply
some_struct s = { 0 };
Do folks find ... | memset is practically never the right way to do it. And yes, there is a practical difference (see below).
In C++ not everything can be initialized with literal 0 (objects of enum types can't be), which is why in C++ the common idiom is
some_struct s = {};
while in C the idiom is
some_struct s = { 0 };
Note, that in C... |
2,838,107 | 2,838,133 | Initializing structs in C++ | As an addendum to this question, what is going on here:
#include <string>
using namespace std;
struct A {
string s;
};
int main() {
A a = {0};
}
Obviously, you can't set a std::string to zero. Can someone provide an explanation (backed with references to the C++ Standard, please) about what is actually suppo... | Your struct is an aggregate, so the ordinary rules for aggregate initialization work for it. The process is described in 8.5.1. Basically the whole 8.5.1 is dedicated to it, so I don't see the reason to copy the whole thing here. The general idea is virtually the same it was in C, just adapted to C++: you take an initi... |
2,838,297 | 2,838,330 | How does calling this function object work? | I have a class
class fobj{
public:
fobj(int i):id(i) {}
void operator()()
{
std::cout<<"Prints"<<std::endl;
}
private:
int id;
};
template<typename T>
void func(T type)
{
type();
}
If I invoke func like
Method 1:
func(fobj(1));
the message I wanted to print is printed.
I was alwa... | One thing to note is that this works because your template class is taking an object by value:
template<typename T>
void func(T type) // this takes a T by value
...
because of this, it can take either an lvalue (such as an actual variable) or an rvalue (such as the temporary).
If for some reason you did want to limi... |
2,838,345 | 2,838,378 | When does code bloat start having a noticeable effect on performance? | I am looking to make a hefty shift towards templates in one of my OpenGL projects, mainly for fun and the learning experience. I plan on watching the size of the executable carefully as I do this, to see just how much of the notorious bloat happens. Currently, the size of my Release build is around 580 KB when I favo... | On most modern processors, locality is going to be more important than size. If you can keep all the currently executing code and a good portion of the data in your L1 cache, you're going to see big wins. If you're jumping all around, you may force code or data out of the cache and then need it again shortly thereaft... |
2,838,542 | 14,391,105 | How can I get the contents of a file at build time into my C++ string? | I have a file I am compiling in C++ in which I wish to have a string whose value is the contents of a file at the time of compilation.
In other words, I'd like to #include the file but have that be inside double quotes.
How can I do this in C++?
Now what if that file contains double quotes as part of its text, how do I... | To correctly create a header with the correct null termination in the string use sed:
xxd -i ${INPUT_FILE_NAME} | sed s/}\;/,0x00}\;/ > ${INPUT_FILE_PATH}.h
See http://gamesfromwithin.com/quick-tip-working-with-shaders-on-ios for details.
|
2,838,608 | 2,849,430 | How to check for cancel button in custom action without doing anything else | I know when I put something in the log using ::MsiProcessMessage(hModule, INSTALLMESSAGE(INSTALLMESSAGE_INFO), ...); that I can check if the return value is IDCANCEL and return ERROR_INSTALL_USEREXIT to Windows installer.
How do I check for that return value without having to put something in the log or alter the progr... | I believe the call you describe will place the info message in the log. But other than that, why would you have to put something in the log or alter the progress bar? If your action takes a long time, it should report progress. If it is short and you never call MsiProcessMesssage, Windows Installer will handle cancel i... |
2,838,720 | 2,838,793 | Is the stack unwound when you stop debugging? | Just curious if my destructors are being called.
(Specifically for Visual Studio, when you hit the red stop button)
| No the process is terminated in VS2005, VS2008 and VS2010 when you press stop debugging.
You can easily check this by making a destructor that writes something to a file (and flushes output).
I'm not sure what standard you mean, but there is no standard that would define this behavior.
|
2,838,790 | 2,838,795 | Efficient update of SQLite table with many records | I am trying to use sqlite (sqlite3) for a project to store hundreds of thousands of records (would like sqlite so users of the program don't have to run a [my]sql server).
I have to update hundreds of thousands of records sometimes to enter left right values (they are hierarchical), but have found the standard
update ... | Create an index on table.id
create index table_id_index on table(id)
|
2,838,972 | 2,839,024 | What is the most efficient way to find missing semicolons in VS with C++? | What are the best strategies for finding that missing semicolon that's causing the error? Are there automated tools that might help.
I'm currently using Visual Studio 2008, but general strategies for any environment would be interesting and more broadly useful.
Background:
Presently I have a particularly elusive missin... | It's unlikely to be a missing semicolon, except (as @Michael suggested) from the end of a class. Generally a missing semicolon causes an error within a line or two.
If it's a scope brace then it's usually not too far away, although sometimes they can be a long way off..
Backtrack from the error line (go backwards up th... |
2,838,980 | 2,838,996 | Error while excuting a simple boost thread program | Could you tell mw what is the problem with the below boost::thread program
#include<iostream>
#include<boost/thread/thread.hpp>
boost::mutex mutex;
class A
{
public:
A() : a(0) {}
void operator()()
{
boost::mutex::scoped_lock lock(mutex);
}
private:
int a;
};
int main()
{
boost::thread thr1(A());
... | You have stumbled on something wonderfully known as the most vexing parse. The quickest way to fix that is to add an extra set of parentheses:
boost::thread thr1((A()));
You can also introduce a temporary:
A tmp1;
boost::thread thr1(tmp1);
In the most vexing parse, what you think is generating a temporary is parsed ... |
2,839,017 | 2,839,035 | Does this have anything to do with endian-ness? | For this code:
#include<stdio.h>
void hello() { printf("hello\n"); }
void bye() { printf("bye\n"); }
int main() {
printf("%p\n", hello);
printf("%p\n", bye);
return 0;
}
output on my machine:
0x80483f4
0x8048408
[second address is bigger in value]
on Codepad
0x8048541
0x8048511
[second address is ... | It has nothing to do with endinanness, but with the C++ standard. C++ isn't required to write functions in the order you see them to disk (and think about cross-file linking and even linking other libraries, that's just not feasable), it can write them in any order it wishes.
About the difference between the actual val... |
2,839,068 | 2,839,115 | template warnings and error help, (gcc) | I'm working on an container class template (for int,bool,strings etc), and I've been stuck with this error
cont.h:56: error: expected initializer before '&' token
for this section
template <typename T>
const Container & Container<T>::operator=(const Container<T> & rightCont){
what exactly have I done wrong there?.
Al... | In the first case you've done things backwards. When you specify the return type, you have to include the template parameter list into the template identifier (Container<T>), but when you specify parameter type, you don't need to do it (just Container is enough)
template <typename T>
const Container<T> & Container<T>::... |
2,839,087 | 2,861,798 | How to test your code on a machine with big-endian architecture? | Both ideone.com and codepad.org have Little-Endian architechtures.
I want to test my code on some machine with Big-Endian architechture (for example - Solaris - which I don't have). Is there some easy way that you know about?
| Googling "big endian online emulator" lead me to PearPC. I assume that if you have the patience you can install Mandrake Linux, get gcc, and go party.
|
2,839,142 | 2,839,206 | creating a vector with references to some of the elements of another vector | I have stored instances of class A in a std:vector, vec_A as vec_A.push_back(A(i)). The code is shown below.
Now, I want to store references some of the instances of class A (in vec_A) in another vector or another array. For example, if the A.getNumber() returns 4, 7, 2 , I want to store a pointer to that instance of ... | I think the safest thing would be to have a second vector that holds indexes into the first vector:
using std::vector;
vector<A> main;
vector<vector<A>::size_type> secondary;
main.push_back(...);
secondary.push_back(main.size() - 1); // add the index of the last item
Now, to look up an item you take the value in se... |
2,839,381 | 2,839,428 | deleting an array that stores pointers to some objects | I am storing pointers to elements of a vec_A in an array A* a_ptrs[3] . Assume that vec_A will not be resized. So, a_ptrs[i] will point to the correct element.
My question is:
Suppose A* a_ptrs[3] is declared in a class B. Since it is not created using 'new' I am guessing I don't need to delete it in the destructor.... | Yep, thats correct. You don't need to use delete. The only issue is if the vector is resized e.g. by calling push_back etc - but you called that out in your post.
|
2,839,390 | 2,839,641 | How do I convert a double into a string in C++(without scientific notation)? | How to convert a double into a floating-point string representation without scientific notation in C++.
"Small" samples (effective numbers may be of any size, such as 1.5E200 or 1e-200) :
0.0000000000000000000000000000000000000000000000000000000023897356978234562
Thank you.
| string doubleToStr(double d)
{
stringstream ss;
ss << fixed << setprecision(400) << d;
return ss.str();
}
|
2,839,470 | 2,839,510 | Class lookup structure array in C++ | I'm trying to create a structure array which links input strings to classes as follows:
struct {string command; CommandPath cPath;} cPathLookup[] = {
{"set an alarm", AlarmCommandPath},
{"send an email", EmailCommandPath},
{"", NULL}
};
which will be used as follows:
CommandPath *cPath = NULL;
string input... | AlarmCommandPath and EmailCommandPath are derived from COmmandPath, correct?
In this case you cannot assign an instance of AlarmCommandPath/EmailCommandPath to CommandPath - it is technically possible, but it won't do what you want. The instance
CommandPath will remain an instance of CommandPath (it will have virtual... |
2,839,551 | 2,839,555 | What's the equivalent of new/delete of C++ in C? | What's the equivalent of new/delete of C++ in C?
Or it's the same in C/C++?
| There's no new/delete expression in C.
The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.
#include <stdlib.h>
int* p = malloc(sizeof(*p)); // int* p = new int;
...
free(p); // delete p;
int* a = malloc(12*sizeof(*a)); // int* ... |
2,839,592 | 2,839,616 | Equivalent of %02d with std::stringstream? | I want to output an integer to a std::stringstream with the equivalent format of printf's %02d. Is there an easier way to achieve this than:
std::stringstream stream;
stream.setfill('0');
stream.setw(2);
stream << value;
Is it possible to stream some sort of format flags to the stringstream, something like (pseudocode... | You can use the standard manipulators from <iomanip> but there isn't a neat one that does both fill and width at once:
stream << std::setfill('0') << std::setw(2) << value;
It wouldn't be hard to write your own object that when inserted into the stream performed both functions:
stream << myfillandw( '0', 2 ) << value;... |
2,839,597 | 2,839,610 | left-hand operand of comma has no effect? | I'm having some trouble with this warning message, it is implemented within a template container class
int k = 0, l = 0;
for ( k =(index+1), l=0; k < sizeC, l < (sizeC-index); k++,l++){
elements[k] = arryCpy[l];
}
delete[] arryCpy;
this is the warning i get
cont.h: In member function `void Containe... | The comma expression a,b,c,d,e is similar to
{
a;
b;
c;
d;
return e;
}
therefore, k<sizeC, l<(sizeC - index) will only return l < (sizeC - index).
To combine conditionals, use && or ||.
k < sizeC && l < (sizeC-index) // both must satisfy
k < sizeC || l < (sizeC-index) // either one is fine.
|
2,839,940 | 2,840,125 | Problem Building dschaefer / android-box2d | I'm trying to build dschaefer android-box2d, and did follow the recipe.
I do get this error when trying to build the TestBox2d with eclipse:
make all
/cygdrive/c/android/android-ndk-r3/build/prebuilt/windows/arm-eabi-4.2.1/bin/arm-eabi-ld \
-nostdlib -shared -Bsymbolic --no-undefined \
-o obj/libtest.so obj/test.o -L.... | The error indicates that the linker cannot find the library box2d.
What I think is the problem is that you have a relative path pointing to the location of the box2d library (-L../box2d/lib/android). If your build directory changes, your build will break. What you might want to do is substitute an absolute path for the... |
2,839,980 | 2,840,022 | Visual Studio Solution: static or shared projects? | When a whole project (solution) consists of multiple subprojects (.vcproj), what is a preferable way to tie them: as static libraries or as shared libraries?
Assuming that those subprojects are not used elsewhere, the shared libraries approach shouldn't decrease memory usage or load time.
| Opinion: Static, in nearly all cases.
Building interfaces across dynamically loaded libraries is much harder in C++ on Windows. For example, unlike with Unix shared objects, you cannot have a standard singleton for all modules, because a DLL would have it's own set of static variables.
Object oriented interfaces are of... |
2,840,026 | 3,092,278 | What grid distributed computing frameworks are currently favoured for trading systems | There seems to a quite a few grid computing frameworks out there, but which ones are actually being used to any great extent by the investment banks for purposes of low latency distributing calculation? I'd be interested to hear answers covering both windows,Linux and cross platform. Also, what RPC mechanisms seem to b... | Some directions (actually used in some corporate investment banks) :
Home made solutions involving PC
farms (traders queue their
computation requests)
GPU
since computationally intensive fiancial operations (eg. Monte Carlo pricing) are usually heavily parallelizable.
|
2,840,079 | 2,840,113 | Statically Init a derived class | With c++, Is there a way to get a derived class to inherit its own static initializer? I am trying to do something like the following:
class Base {
public:
class StaticInit {
public:
virtual StaticInit() =0;
};
};
class Derived: public Base {
public:
virtual... | I use templates to do this, rather than inheritance - something like:
template <typename T>
struct StaticInit {
StaticInit() {
// do whatever with T
}
};
in use:
static StaticInit <SomeClass> init;
|
2,840,193 | 2,840,225 | allocating extra memory for a container class | Hey there, I'm writing a template container class and for the past few hours have been trying to allocate new memory for extra data that comes into the container (...hit a brick wall..:| )
template <typename T>
void Container<T>::insert(T item, int index){
if ( index < 0){
cout<<"Invalid location to insert ... | Several things don't make too much sense to me:
if (index+1 > capacityC){
shouldn't that be:
if (index >= capacityC){
Also, when you grow the array I don't see why you are doing two lots of copying. shouldn't:
delete[] elements;
elements = 0;
be:
delete[] elements;
elements = tmparray2;
|
2,840,305 | 2,840,332 | Including Libraries C++ | How do I properly include libraries in C++? I'm used to doing the standard libraries in C++ and my own .h files.
I'm trying to include wxWidgets or GTK+ in code::blocks and/or netbeans C/C++ plugin. I've included ALL libraries but I constantly get errors such as file not found when it is explicitly in the include!
One... | Firstly, header files are not the same thing as libraries. A header is a C++ text file containing declarations of things, while a library is a container for compiled, binary code.
When you #include a header file, the compiler/IDE needs to know where to find it. There is typically an IDE setting which tells the compile... |
2,840,342 | 2,840,391 | Benefit of using multiple SIMD instruction sets simultaneously | I'm writing a highly parallel application that's multithreaded. I've already got an SSE accelerated thread class written. If I were to write an MMX accelerated thread class, then run both at the same time (one SSE thread and one MMX thread per core) would the performance improve noticeably?
I would think that this set... | The SSE and MMX instruction sets share the same set of vector processing execution units in the CPU. Therefore, running an SSE thread and an MMX thread will have the same resources available each thread as if running two SSE threads (or two MMX threads). The only difference is in instructions which exist in SSE but n... |
2,840,496 | 2,840,512 | Visual studio c++ documentation generator | Is there a way to get documentation(like javadoc) in a visual-c++ project?
I'm using visual studio 2010.
thanks!
| You could use the XML-Documentation format, supported by VS2010, too. http://msdn.microsoft.com/en-us/library/ms177226%28VS.80%29.aspx
After commenting your code, you can use Sandcastle to create a MSDN-like documentation: http://sandcastle.codeplex.com/. (Here is a GUI representation for Sandcastle, which is a lot ea... |
2,840,640 | 2,840,647 | How to loop through a boost::mpl::list? | This is as far as I've gotten,
#include <boost/mpl/list.hpp>
#include <algorithm>
namespace mpl = boost::mpl;
class RunAround {};
class HopUpAndDown {};
class Sleep {};
template<typename Instructions> int doThis();
template<> int doThis<RunAround>() { /* run run run.. */ return 3; }
template<> int doThis<HopUpAndD... | Use mpl::for_each for runtime iteration over type lists. E.g.:
struct do_this_wrapper {
template<typename U> void operator()(U) {
doThis<U>();
}
};
int main() {
typedef boost::mpl::list<RunAround, HopUpAndDown, Sleep> acts;
boost::mpl::for_each<acts>(do_this_wrapper());
};
|
2,840,830 | 2,840,842 | How to call a templated operator overload without using the word 'operator'? | class RunAround;
class HopUpAndDown;
class Sleep;
template<typename Acts> int doThis();
template<> int doThis<RunAround>() { /* run run run.. */ return 3; }
template<> int doThis<HopUpAndDown>() { /* hop hop hop.. */ return 2; }
template<> int doThis<Sleep>() { /* zzz.. */ return -2; }
struct Results
{
... | The most comfortable thing is to let template argument deduction work for you:
struct Results {
template<typename Act> int& operator()(Act) { /* ... */ }
};
results(RunAround()) = /* ... */;
|
2,840,835 | 2,840,917 | Way to get unsigned char into a std::string without reinterpret_cast? | I have an unsigned char array that I need in a std::string, but my current way uses reinterpret_cast which I would like to avoid. Is there a cleaner way to do this?
unsigned char my_txt[] = {
0x52, 0x5f, 0x73, 0x68, 0x7e, 0x29, 0x33, 0x74, 0x74, 0x73, 0x72, 0x55
}
unsigned int my_txt_len = 12;
std::string my_std_st... | Use the iterator constructor:
std::string my_std_string(my_txt, my_txt + my_txt_len);
This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast. That would be perfectly clean, since what you say is exactly what is done.
In your... |
2,840,848 | 2,840,858 | Are tr1 headers available for gcc v3.4.6? | Are tr1 headers available for g++ v3.4.6? If so, how can I locate them at compile time.
The following is failing to compile:
#include <tr1/memory>
With the following error:
myModule.h:20:24: tr1/memory: No such file or directory
Do I need to move to a later compiler or do I have the headers somewhere?
| As an alternative, Boost provides a TR1 implementation too.
|
2,840,878 | 2,916,467 | "Ambiguous template specialization" problem | I'm currently porting a heap of code that has previously only been compiled with Visual Studio 2008.
In this code, there's an arrangement like this:
template <typename T>
T convert( const char * s )
{
// slow catch-all
std::istringstream is( s );
T ret;
is >> ret;
return ret;
}
template <typename... | Apparently return convert<T>( static_cast<const char*>( s )); (or something else I can't see) is inducing the compiler to create a template instantiation of T convert( const char * s ) for T=float. Then when you try to specialize it later, it fails because the template version already exists.
When I moved the inline fl... |
2,840,908 | 2,841,014 | Linker, Libraries & Directories Information | I've finished both my C++ 1/2 classes and we did not cover anything on Linking to libraries or adding additional libraries to C++ code.
I've been having a hay-day trying to figure this out; I've been unable to find basic information linking to objects. Initially I thought the problem was the IDE (Netbeans; and Code::B... | On a Unix-like system, you usually find libraries in /usr/lib. The .a extension indicates that you are dealing with an archive file created for example with ar. They are created from object files with the extension .o. The linker can then resolve references at compile time. They are called static libraries, because the... |
2,840,940 | 2,841,161 | Is it secure to use malloc? | Somebody told me that allocating with malloc is not secure anymore, I'm not a C/C++ guru but I've made some stuff with malloc and C/C++. Does anyone know about what risks I'm into?
Quoting him:
[..] But indeed the weak point of C/C++ it is the security, and the Achilles' heel is indeed malloc and the abuse of pointers... |
[...] C/C++ it is a well known insecure language. [...]
Actually, that's wrong. Actually, "C/C++" doesn't even exist. There's C, and there's C++. They share some (or, if you want, a lot of) syntax, but they are indeed very different languages.
One thing they differ in vastly is their way to manage dynamic memory. T... |
2,841,114 | 2,841,127 | Is there a concurrent container library for C++ |
Possible Duplicate:
Is there a production ready lock-free queue or hash implementation in C++
I'm looking for implementations of lock-free containers:
Queue
Stack
Hash Map
etc...
How about blocking containers:
Blocking Queue
Blocking Stack
Are there any good libraries out there? I would like to refrain from writ... | Have a look at the container classes of Intel TBB. The reference says:
The container classes permit multiple
threads to simultaneously invoke
certain methods on the same container.
|
2,841,204 | 2,841,222 | Use the keyword class as a variable name in C++ | I am having trouble writing C++ code that uses a header file designed for a C file. In particular, the header file used a variable name called class:
int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs);
This works in C as ... | try something like this:
#define class class_variable
// if class is only used in declarations, you can also do
// #define class
#include "c.h"
#undef class
it may cause problems, but maybe worth a shot
alternative (using Makefile):
python_.hpp: /usr/include/python.h
perl -pe 's/\Wclass\W//g' $< > $@
...
#include... |
2,841,332 | 2,859,126 | C++ (g++) Compile Error, Expected "="/etc. Before 'MyWindow" (my class name) | I have a very strange problem and the following code wont compile:
#ifndef MYWINDOW_HPP_INCLUDED
#define MYWINDOW_HPP_INCLUDED
class MyWindow{
private:
WNDCLASSEX window_class;
HWND window_handle;
HDC device_context_handle;
HGLRC open_gl_render_context;
MSG message;
... | Ahh, silly me, I had main saved as a .c file instead of .cpp, resulting in Code::Blocks trying to compile it as in c instead of c++, thanks for your help guys!
|
2,841,353 | 2,842,200 | Example applications and benefits of using C , C++ or Java | Ok, I'm revising for my upcoming year 2 exams on a CS course and its likely something like this will come up. my question is what is an ideal application that would especially benefit from the program features of each of the three languages? I have a vague idea but getting a second opinion could really help.
JavaPortab... |
C: device drivers and other low level things
C++: applications where you don't
want to annoy the user by having to
install a runtime environment
C/C++: realtime applications; or in
cases where the programs runtime is
extremely short (the C/C++ program
terminates before the jvm startup is
done); in cases where memory
f... |
2,841,422 | 2,843,516 | Problem linking SDL_Image against libpng | I'm trying to compile SDL_Image 1.2.10 with MinGW + MSys (gcc 4.5.0) on Windows, I have compiled all the requires libs (zlib 1.2.5, libpng 1.4.2, libjpeg 8a, libtiff 3.9.2). SDL_Image compiles fine, but fails to link to libpng, throwing .libs/IMG_png.o:IMG_png.c:(.text+0x16): undefined reference errors on various png s... | Downgrading my GCC suite to 4.4.0 fixed the problem, it seems 4.5.0 still has a few teething issues.
Unless someone comes up with a better answer as to why I can't link properly with GCC 4.5.0 I shall mark my own answer as correct.
|
2,841,563 | 2,841,681 | testing directory S_ISDIR acts inconsistently | I'm doing simple tests on all files in directory.
But from some reason, sometimes, they behave wrongly?
What's bad with my code?
using namespace std;
int main() {
string s = "/home/";
struct dirent *file;
DIR *dir = opendir(s.c_str());
while ((file = readdir(dir)) != NULL){
struct stat * file_info = ne... | You made some mistakes, the most important being to call stat() without checking its return value. I modified your program to this:
#include <cstdio>
#include <dirent.h>
#include <iostream>
#include <string>
#include <sys/stat.h>
using namespace std;
int main() {
string s = "/home/";
struct dirent *file;
DIR *d... |
2,841,589 | 2,841,724 | What is the proper use of boost::fusion::push_back? | // ... snipped includes for iostream and fusion ...
namespace fusion = boost::fusion;
class Base
{
protected: int x;
public: Base() : x(0) {}
void chug() {
x++;
cout << "I'm a base.. x is now " << x << endl;
}
};
class Alpha : public Base
{
public:
void chug() {
x += 2;
c... |
(Note: I'm only assuming from the overly brief documentation on boost::fusion that I am supposed to create a new vector every time I call push_back.)
You're not creating a new vector. push_back returns a lazily evaluated view on the extended sequence. If you want to create a new vector, then e.g. typedef NewStuff as
... |
2,841,619 | 2,841,824 | Function Composition in C++ | There are a lot of impressive Boost libraries such as Boost.Lambda or Boost.Phoenix which go a long way towards making C++ into a truly functional language. But is there a straightforward way to create a composite function from any 2 or more arbitrary functions or functors?
If I have: int f(int x) and int g(int x), I... | I don't know of anything that supports the syntax you wish for currently. However, it would be a simple matter to create one. Simply override * for functors (boost::function<> for example) so that it returns a composite functor.
template < typename R1, typename R2, typename T1, typename T2 >
boost::function<R1(T2)> ... |
2,841,647 | 2,841,668 | What C++ templates issue is going on with this error? | Running gcc v3.4.6 on the Botan v1.8.8 I get the following compile time error building my application after successfully building Botan and running its self test:
../../src/Botan-1.8.8/build/include/botan/secmem.h: In member function `Botan::MemoryVector<T>& Botan::MemoryVector<T>::operator=(const Botan::MemoryRegion<T... | Change it to this:
{ if(this != &in) this->set(in); return (*this); }
I suspect that the set function is defined in the base-class? Unqualified names are not looked up in a base class that depends on a template parameter. So in this case, the name set is probably associated with the std::set template which requires t... |
2,841,716 | 2,841,739 | Using preprocessor directives to define command line options | If I wanted to add, let's say, a new .lib to the build only if a particular #define was set, how would I do that?
In the MSVC++ 2008 "Property Pages", you would simply add: Config Properties -> Linker -> Input -> Additional Dependencies, but I would like it if something like #define COMPILE_WITH_DETOURS was set, then t... | You can set some linker options by using #pragma comment in one of your source files.
For example, to link against a 'detours.lib' library only if COMPILE_WITH_DETOURS is defined, you can use:
#ifdef COMPILE_WITH_DETOURS
# pragma comment(lib, "detours.lib")
#endif
(this is specific to Microsoft Visual C++ and is ... |
2,841,752 | 2,841,774 | Accessing methods of an object put inside a class | A class A possesses an instance c of a class C. Another class B has to modify c through C::setBlah(); method.
Is it bad to create an accessor C getC(); in A and then use A.getC().setBlah() ?
Or should I create a method A::setBlah(); that would call C::setBlah(); ? Isn't it annoying if there are several methods like tha... | As with most "is it bad to do X?" questions, the answer is that it depends entirely on a given situation.
Sometimes it might be a really bad idea to have a getC() sort of function because it breaks encapsulation. Other times it might be completely fine because encapsulation of that detail might be irrelevant, and wr... |
2,841,757 | 2,841,764 | C++ Template: 'is not derived from type' | Why is this code not valid?
#include <vector>
template <typename T>
class A {
public:
A() { v.clear(); }
std::vector<A<T> *>::const_iterator begin() {
return v.begin();
}
private:
std::vector<A<T> *> v;
};
GCC reports the following errors:
test.cpp:8: error: type 'std::vector<A<T>*, std::a... | In this line, you are missing the typename keyword:
std::vector<A<T> *>::const_iterator begin(){
You need:
typename std::vector<A<T> *>::const_iterator begin(){
This because std::vector<A<T> *> is dependent on the template parameter (T) of the class template (A). To enable correct parsing of the template without havi... |
2,841,849 | 2,841,886 | Using preprocessor directives to define the output path | Using the following pseudo-code:
#define BUILD_PATH "C:/MyBuild/"
#define BUILD_NAME "mydll.dll"
// Set build path here
representing how I would like to build the current project (a dll) into C:/MyBuild/mydll.dll, how would I accomplish this by only using preprocessor directives?
| I may be misunderstanding, but I really cannot understand WHY you want to do this but it is doable:
#pragma comment( linker, "/out:c:\mydll.dll" )
I cannot re-iterate enough exactly how much you don't want to be doing this though ...
If you want to GET the output path via pre-processor info then, I'm afraid ... you ca... |
2,841,941 | 2,841,957 | Constant template parameter class manages to link externally | I have a class foo with an enum template parameter and for some reason it links to two versions of the ctor in the cpp file.
enum Enum
{
bar,
baz
};
template <Enum version = bar>
class foo
{
public:
foo();
};
// CPP File
#include "foo.hpp"
foo<bar>::foo() { cout << "bar"; }
foo<baz>::foo() { cout << "b... | You are specializing both forms of the contstructor. Why are you surprised it links both forms in?
|
2,842,005 | 2,842,096 | Objective-C/C++ - Linker error/Method Signature issue | There is a static class Pipe, defined in C++ header that I'm including.
The static method I'm interested in calling (from Objective-c) is here:
static ERC SendUserGet(const UserId &_idUser,const GUID &_idStyle,const ZoneId &_idZone,const char *_pszMsg);
I have access to an objective-c data structure that appears to s... | (Eh, let's turn that comment into an answer.)
The method signature looks fine; that is, what you're calling matches what is declared in the header. If it was not, you would probably be getting a compilation error rather than a linker error.
The linker's problem is that it doesn't have any corresponding object code to c... |
2,842,012 | 2,842,042 | Template type deduction with a non-copyable class | Suppose I have an autolocker class which looks something like this:
template <T>
class autolocker {
public:
autolocker(T *l) : lock(l) {
lock->lock();
}
~autolocker() {
lock->unlock();
}
private:
autolocker(const autolocker&);
autolocker& operator=(const autolocker&);
private:
... | Yes you can use the scope-guard technique
struct autolocker_base {
autolocker_base() { }
protected:
// ensure users can't copy-as it
autolocker_base(autolocker_base const&)
{ }
autolocker_base &operator=(autolocker_base const&)
{ return *this; }
};
template <T>
class autolocker : public auto... |
2,842,048 | 2,844,913 | How to use boost::fusion::transform on heterogeneous containers? | Boost.org's example given for fusion::transform is as follows:
struct triple
{
typedef int result_type;
int operator()(int t) const
{
return t * 3;
};
};
// ...
assert(transform(make_vector(1,2,3), triple()) == make_vector(3,6,9));
Yet I'm not "getting it." The vector in their example contain... | Usually, fusion::transform is used with a templated (or -as shown above- otherwise overloaded) function operator:
struct triple
{
template <typename Sig>
struct result;
template <typename This, typename T>
struct result<This(T)>
{
typedef /*...figure out return type...*/ type;
};
... |
2,842,215 | 2,866,713 | Where can I find boost::fusion articles, examples, guides, tutorials? | I am going to go ahead and shamelessly duplicate this question because the accepted answer is essentially "nope, no guides" and it's been nearly a year now since it's been asked. Does anyone know of any useful articles, guides, tutorials, etc. for boost::fusion besides the barebones documentation on boost.org? (which ... | Ugh. Still no bites... I did find some helpful examples in the <boostdir>/libs/fusion/test area though.
|
2,842,319 | 2,843,324 | SwapBuffers causes redraw | I'm making a Win32 application with OpenGL in the main window (not using GLUT).
I have my drawing code in WM_PAINT right now when I call swapBuffers it must be invalidating itself because it is constantly rerendering and using lots of cpu resources. How can I make it only render when it honestly receives WM_PAINT like ... | WM_PAINT messages keep on being sent until Windows has validated the dirty region of the window. The API that resets the dirty region is 'EndPaint'.
Calling SwapBuffers should not effect the invalid window region at all.
Your WM_PAINT handler should be something like the following:
case WM_PAINT:
HDC hdc;
PAINTSTRU... |
2,842,387 | 2,891,962 | Where do I put the logic of my MFC program? | I created an application core, in C++, that I've compiled into a static library in Visual Studio. I am now at the process of writing a GUI for it.
I am using MFC to do this. I figured out how to map button presses to execute certain methods of my application core's main class (i.e. buttons to have it start and stop).... | You mentioned "every second or two" while another answer suggested "using an event driven paradigm". How about setting a Timer in the dialog and when the timer fires, sample data from your external source. You indicated you figured out how to map event handlers for buttons, so mapping a handler to the timer should be... |
2,842,471 | 2,842,520 | Is this 2D array initialization a bad idea? | I have something I need a 2D array for, but for better cache performance, I'd rather have it actually be a normal array. Here's the idea I had but I don't know if it's a terrible idea:
const int XWIDTH = 10, YWIDTH = 10;
int main(){
int * tempInts = new int[XWIDTH * YWIDTH];
int ** ints = new int*[XWIDTH];
... | The problem with that kind of approach is that it is error prone. I would tell yout to wrap the allocation and access to individual elements os your 2D array in a class.
class Array2D
{
private:
/* Pointer necessary for the choosen implementation */
public:
Array2D(unsigned int dim1, unsigned int dim2);
~Ar... |
2,842,527 | 2,842,551 | Help C++ifying this C style code | Hey I'm used to developing in C and I would like to use C++ in a project. Can anyone give me an example of how I would translate this C-style code into C++ code. I know it should compile in a c++ complier but I'm talking using c++ techniques(I.e. classes, RAII)
typedef struct Solution Solution;
struct Solution {
... | Here's one way to do it:
class Solution
{
public:
// This is the constructor for this class. Note that the constructor
// must always have the same name as the class. The line following
// the ':' is called the initializer list. It initializes the data
// members to a known state.
Solution(size_t si... |
2,842,560 | 2,842,566 | Quick question regarding Conditional Compilation (ifndef) | This is quite probably a very silly question but I need to be sure. I've been given a class declaration in a header file eg.
#ifndef file_H
#define file_H
class ex{
private:
public:
};
#endif
and I've been required to write the method definitions in the same file, which I have done, my question is does the "#endif"... | At the end of the file.
The goal of this form of this #ifndef pattern is to prevent a situation where the same declaration or definition appears twice in a compilation unit.
This is done because a C file may include several H files, which somewhere up the chain may in turn include the same file. IF you simply ran the ... |
2,842,687 | 2,842,692 | Typecast cross-platform compatibility | what I'm trying to do is append a binary integer into a string object. So far I have this:
int number = 5;
cppstring.append((char*)&number, 4);
It works fine on a x86 system with Windows, but some people are saying its not cross-platform and is unsafe. What is the preferred method to do this?
| The reason it's not portable is that ints are not always 4 bytes. For instance, the ILP64 data model uses 8-bytes ints. C99 only requires that ints are at least 2 bytes. Why do you need to do this, and what is the desired behavior if the size of the int is not 4 bytes?
|
2,842,728 | 2,842,786 | Can someone explain to me why my output is this? And how would I correct my output? | In this slice of code I get an output of
bbb 55 66 77 88
aaa
the output I expect and want is
bbb 55 66 77 88
bbb
because I reassign ss from log[0] to log[1].
So my question is why is the output different from what I expect and how do I
change it to what I want?
int w,x,y,z;
stringstream ss (stringstream:... | When
ss >> w >> x >> y >> z;
was executed, there is no content left to operate on and ss.good() returns false, which expresses the need to call ss.clear() in order to assure everything is ok and we can move on.
However, given that you do
ss.clear();
ss<<log[k];
The content of ss will be
aaa 11 22 33 44bbb 55 66 77 8... |
2,842,837 | 2,842,846 | Pass arguments to a parameter class object | This is undoubtedly a simple question. I used to do this before, but it's been around 10 years since I worked in C++ so I can't remember properly and I can't get a simple constructor call working.
The idea is that instead of parsing the args in main, main would create an object specifically designed to parse the argum... | Use:
Parameters params(argc, argv);
The new operator is generally used when you want dynamic (heap) allocation. It returns a pointer (Parameter *).
|
2,842,902 | 2,842,905 | error C3662: override specifier 'new' only allowed on member functions of managed classes | Okay, so I'm trying to override a function in a parent class, and getting some errors. here's a test case
#include <iostream>
using namespace std;
class A{
public:
int aba;
void printAba();
};
class B: public A{
public:
void printAba() new;
};
void A::printAba(){
cout << "aba1" << endl;
}
void ... | There's no need to put any keywords in the derived class to override a function.
class B: public A{
public:
void printAba();
};
But the base class's method should be virtual, to allow the method be selected depending on the actual identity of the variable.
class A{
public:
int aba;
virtual void printAb... |
2,842,928 | 2,842,942 | Default value of function parameter | 1.
int Add (int a, int b = 3);
int Add (int a, int b)
{
}
2.
int Add (int a, int b);
int Add (int a, int b = 3)
{
}
Both work; which is the standard way and why?
| If you put the declaration in a header file, and the definition in a separate .cpp file, and #include the header from a different .cpp file, you will be able to see the difference.
Specifically, suppose:
lib.h
int Add(int a, int b);
lib.cpp
int Add(int a, int b = 3) {
...
}
test.cpp
#include "lib.h"
int main() {
... |
2,843,030 | 2,843,067 | Seg Fault with malloc'd pointers | I'm making a thread class to use as a wrapper for pthreads. I have a Queue class to use as a queue, but I'm having trouble with it. It seems to allocate and fill the queue struct fine, but when I try to get the data from it, it Seg. faults.
http://pastebin.com/Bquqzxt0 (the printf's are for debugging, both throw seg fa... | C++ provides a built-in queue class for you:
#include <queue>
struct queueset
{
void* ptr;
int index;
queueset(void* p, int i) : ptr(p), index(i) {}
};
class pthreadmutexlock
{
public:
pthreadmutexlock()
{
pthread_mutex_init(&lock, NULL);
pthread_mutex_lock(&lock);
}
~pth... |
2,843,167 | 2,843,270 | How would I create this background effect? | What would you call the effect applied to the backgrounds in the Giygas fight of Earthbound, and the battle backgrounds in Mother 3? This is what I'm talking about.
http://www.youtube.com/watch?v=tcaErqaoWek
http://www.youtube.com/watch?v=ubVnmeTRqhg
Now anyone know how I could go about this without using animated imag... | These are also called demo effects. They are used on demoscene events, beside games.
Check out this effect collection.
|
2,843,248 | 2,843,271 | Launch C# .Net Application from C++ | Is it possible to launch a C#.Net (2.0) application from an application written in C++???
Thanks,
EDIT:
Cool - so I just have to know where the app is:
LPTSTR szCmdline = _tcsdup(TEXT("C:\\Program Files\\MyApp -L -S"));
CreateProcess(NULL, szCmdline, /* ... */);
| You can launch any EXE using CreatePocess or ShellExecute API. ( including C#.Net)
|
2,843,357 | 2,843,361 | Window screenshot using WinAPI | How to make a screenshot of program window using WinAPI & C#?
I sending WM_PAINT (0x000F) message to window, which I want to screenshot, wParam = HDChandle, but no screenshot in my picturebox. If I send a WM_CLOSE message, all waorking (target window closes). What I do wrong with WM_PAINT? May be HDC is not PictureBox ... | pictureBox.Handle is a window handle, not a DC handle. There are several guides online for doing screenshots. One is here. See also @In silico's answer.
|
2,843,421 | 2,843,434 | Custom string class (C++) | I'm trying to write my own C++ String class for educational and need purposes.
The first thing is that I don't know that much about operators and that's why I want to learn them.
I started writing my class but when I run it it blocks the program but does not do any crash.
Take a look at the following code please before... | The line:
cstr=new char[strlen(str)];
should be:
cstr=new char[strlen(str) + 1];
Also, the test for self-assignment does not make sense in the copy constructor - you are creating a new object - it cannot possibly have the same address as any existing object. And the copy constructor should take a const reference as a... |
2,843,478 | 2,843,490 | variables in abstract classes C++ | I have an abstract class CommandPath, and a number of derived classes as below:
class CommandPath {
public:
virtual CommandResponse handleCommand(std::string) = 0;
virtual CommandResponse execute() = 0;
virtual ~CommandPath() {}
};
class GetTimeCommandPath : public CommandPath {
int sta... | Try this:
class CommandPath {
protected:
int stage;
public:
CommandPath(int stage_) : stage(stage_) {}
};
class GetTimeCommandPath : public CommandPath {
public:
GetTimeCommandPath(int stage_) : CommandPath(stage_) {}
};
(Omitted extra code for brevity).
You can't use the initializer list on a parent class' me... |
2,843,552 | 3,009,537 | RESTful interface for C++/Qt? | I want to integrate the RESTful-API in my Qt-Project.
I already read the example on this page, but this is only for receiving data from a RESTful-interface, not for sending new data to the server. In Java, I can use RESTlet for example, is there any possibility to use something like that for Qt, too?
Or is there even a... | Since REST is just normal URL access, there's no reason you can't use the Qt HttpClient interfaces to talk to you backend Java REST interface. You just have to make a determination to use XML or JSON - both have very capable libraries available, and both are just text interfaces.
Odd you ask, I'm in the middle of do... |
2,843,703 | 2,843,727 | Pass a pointer to a proc as an argument | I want to pass a pointer to a procedure in c++. I tried passing this LRESULT(*)(HWND, UINT, WPARAM, LPARAM) prc but it didn't work. How is this done?
Thanks
HWND OGLFRAME::create(HWND parent, LRESULT(*)(HWND, UINT, WPARAM, LPARAM) prc)
{
if(framehWnd != NULL)
{
return framehWnd;
ZeroMemory(&rwc,... | HWND OGLFRAME::create(HWND parent, LRESULT(*prc)(HWND, UINT, WPARAM, LPARAM))
You could also just use the WNDPROC type:
HWND OGLFRAME::create(HWND parent, WNDPROC prc)
|
2,843,796 | 2,844,041 | GCC: visibility of symbols in standalone C++ applications | Because of a strange C++ warning about the visibility of some symbols and an interesting answer, linking to a paper which describes the different visibility types and cases (section 2.2.4 is about C++ classes), I started to wonder if it is needed for a standalone application to export symbols at all (except main - or i... | For applications you do not need this because you do not have API...
The visibility is relevant for shared-objects only.
|
2,843,820 | 2,843,933 | C++ Standard Library Exception List? | Is there a reference about C++ Standard Library Exceptions? I just want to know that which functions may throw an exception or not.
| Actually, most of the standard library function don't throw exceptions themselves. They just pass on exception thrown by user code invoked by them. For example, if you push_back() an element to a vector, this can throw (due to memory allocation errors and) if the object's copy constructor throws.
A few notable excepti... |
2,843,948 | 2,843,971 | map::lower_bound that returns a map | Is there a function that does the same thing as map::lower_bound except it returns a new sub-map and not an iterator?
Edit: The function should return a sub-map which contains all the values for which the key is equal to, or greater than a certain value (which is given as input to the function).
| Something like this?
// Beware, brain-compiled code ahead!
template< typename K, typename V >
std::map<K,V> equal_or_greater(const std::map<K,V>& original, const K& k)
{
return std::map<K,V>( original.lower_bound(k), original.end() );
}
Edit: It seems you actually want upper_bound() instead of lower_bound().
|
2,844,082 | 2,844,120 | Scrollbar moves back after WM_VSCROLL | I have a window with its own H and V scrolling. I'm handling the event like this:
case WM_VSCROLL:
SetScrollPos(hWnd, SB_VERT, (int)HIWORD(wParam), TRUE);
break;
all I want is for the position of the scroll bar to stay once I release my mouse but what it's doing is just going back to the top after. W... | The wParam parameter of the WM_VSCROLL message is either SB_TOP, SB_BOTTOM, SB_PAGEUP, SB_PAGEDOWN, SB_LINEUP, SB_LINEDOWN, SB_THUMBPOSITION, or SB_THUMBTRACK, where the names ought to explain themselves.
SB_TOP and SB_BOTTOM means that the scrolling window is to go to the top or bottom, respectively. These messages c... |
2,844,102 | 2,844,924 | Where is the virtual function call overhead? | I'm trying to benchmark the difference between a function pointer call and a virtual function call. To do this, I have written two pieces of code, that do the same mathematical computation over an array. One variant uses an array of pointers to functions and calls those in a loop. The other variant uses an array of poi... | I think you're seeing the difference, but it's just the function call overhead. Branch misprediction, memory access and the trig functions are the same in both cases. Compared to those, it's just not that big a deal, though the function pointer case was definitely a bit quicker when I tried it.
If this is representativ... |
2,844,199 | 2,844,212 | How do C++ header files work? | When I include some function from a header file in a C++ program, does the entire header file code get copied to the final executable or only the machine code for the specific function is generated. For example, if I call std::sort from the <algorithm> header in C++, is the machine code generated only for the sort() fu... | You're mixing two distinct issues here:
Header files, handled by the preprocessor
Selective linking of code by the C++ linker
Header files
These are simply copied verbatim by the preprocessor into the place that includes them. All the code of algorithm is copied into the .cpp file when you #include <algorithm>.
Sele... |
2,844,339 | 2,844,385 | C++ iterator and const_iterator problem for own container class | I'm writing an own container class and have run into a problem I can't get my head around. Here's the bare-bone sample that shows the problem.
It consists of a container class and two test classes: one test class using a std:vector which compiles nicely and the second test class which tries to use my own container clas... | When you call begin() the compiler by default creates a call to the non-const begin(). Since myc isn't const, it has no way of knowing you mean to use the const begin() rather than the non-const begin().
The STL iterator contains a cast operator which allows an iterator to be silently converted to a const_iterator. If... |
2,844,446 | 2,844,493 | Shall I optimize or let compiler to do that? | What is the preferred method of writing loops according to efficiency:
Way a)
/*here I'm hoping that compiler will optimize this
code and won't be calling size every time it iterates through this loop*/
for (unsigned i = firstString.size(); i < anotherString.size(), ++i)
{
//do something
}
or may... | I usually write this code as:
/* i and size are local to the loop */
for (size_t i = firstString.size(), size = anotherString.size(); i < size; ++i) {
// do something
}
This way I do not pollute the parent scope and avoid calling anotherString.size() for each loop iteration.
It is especially useful with iterators:
f... |
2,844,448 | 2,844,576 | Overinclusion of libraries C++ | I'm reading about how to put a makefile together, but no-one seems to mention what to do if your files require different sets of libraries, they all seem to use the same set of libraries for each file. Since it seems unlikely that every single file has the same libraries, I take it the list they use must amalgamate all... |
If there's any downside to including too many libraries?
Hardly any.
If the compiler works out which ones are needed and ignores the rest?
Almost exactly right: it's the linker that examines each library and pulls only the object code that it needs.
The one downside to including a very large number of libraries is ... |
2,844,466 | 2,844,572 | Can 'iterator' type just subclass 'const_iterator'? | After another question about iterators I'm having some doubts about custom containers. In my container, iterator is a subclass of const_iterator, so that I get conversion from non-const to const "for free". But is this allowed or are there any drawbacks or non-working scenarios for such a setup?
| Yes, this is fine. This is how VC10's implementation of the iterators for vector are structured, for example. See _Vector_iterator and _Vector_const_iterator in <vector>.
By the way, writing iterators is hard. It's worth your time to learn and use the boost::iterator library.
|
2,844,607 | 2,844,618 | What C++0x feature will have the most impact? | What will day to day C++ development be like in a few years? What C++0x features will change C++ development the most?
In what order should I concentrate learning these new features?
| Lambdas, because they finally introduce reasonable means of harnessing the benefits of functional programming.
|
2,844,623 | 3,756,666 | SFML Plasma Sprite Effect? | Is there a way to create a plasma effect in SFML that doesn't slow my framerate to a crawl?
| 1) Manipulate the image bits directly in memory as a byte (or int/whatever depending on your target colour depth) array. Don't use anything which GetsPixel() from an image each time.
2) Minimise your maths. For plasma effects you'll usually be using a lot of trig functions which are fairly slow when you're doing them (... |
2,844,676 | 2,845,242 | typedef and operator overloading in C++ | Suppose I typedef an integer or integer array or any known type:
typedef int int2
Then I overload operator * for int2 pairs, now if I initialize variables a and b as int. Then will my * between a and b be the overloaded * ?
How do I achieve overloading an int and yet also use * for int the way they are. Should I crea... | What you need is a Strong Typedef.
Boost offered version that should work for you, or at least help you resolve your need :
http://www.boost.org/doc/libs/1_42_0/boost/strong_typedef.hpp
|
2,844,817 | 2,845,275 | How do I check if a C++ string is an int? | When I use getline, I would input a bunch of strings or numbers, but I only want the while loop to output the "word" if it is not a number.
So is there any way to check if "word" is a number or not? I know I could use atoi() for
C-strings but how about for strings of the string class?
int main () {
stringstream ss (s... | Another version...
Use strtol, wrapping it inside a simple function to hide its complexity :
inline bool isInteger(const std::string & s)
{
if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false;
char * p;
strtol(s.c_str(), &p, 10);
return (*p == 0);
}
Why strtol ?
As far as I... |
2,844,947 | 2,845,001 | Solve equation from string to result in C | I would like to know if anyone has info or experience on how to do something which sounds simple but doesn't look like it when trying to program it.
The idea is : give a string containing an equation, such as : "2*x = 10" for example (this is simple, but it could get very complex, such as sqrt(54)*35=x^2; and so on....... | This is called "parsing", and although computer science has already solved this problem it isn't simple at all until you understand it thoroughly. There's an entire computer-science discipline that describes how to solve this problem. In C you must define the grammar of your input (possibly with precedence rules in it)... |
2,844,986 | 2,845,116 | CString a = "Hello " + "World!"; Is it possible? | I'm making my own string class and I'd like to ensure that CString a = "Hello " + "World!"; works (i.e. does not give a compiler error such as: cannot add 2 pointers).
My string class automatically converts to char* when needed and thus writing printf(a) would not break the code.
Is there any way to replace the compile... | The right answer
No.
You cannot overload operators for built-ins, such as pointers.
James McNellis already answered the question, so I won't elaborate.
A possible alternative...
(I use std::string because I have no info on your in-house string)
Using a typedef will add some sugar to your syntax:
typedef std::string S_ ... |
2,845,091 | 2,845,104 | Boost ForEach Question | Trying to use something like the below with a char array but it doesn't compile. But the example with short[] works fine. Any idea why? :)
char someChars[] = {'s','h','e','r','r','y'};
BOOST_FOREACH(char& currentChar, someChars)
{
}
short array_short[] = { 1, 2, 3 };
BOOST_FOREACH( short & i, array_s... | If you go to the line in <boost/foreach.hpp> that raises the compilation error, you will see the following comment:
// **** READ THIS IF YOUR COMPILE BREAKS HERE ****
//
// There is an ambiguity about how to iterate over arrays of char and wchar_t.
// Should the last array element be treated as a null terminator to be... |
2,845,372 | 2,845,489 | Is this overly clever or unsafe? | I was working on some code recently and decided to work on my operator overloading in c++, because I've never really implemented it before. So I overloaded the comparison operators for my matrix class using a compare function that returned 0 if LHS was less than RHS, 1 if LHS was greater than RHS and 2 if they were equ... | As far as I can see it's safe, but it does take looking twice for everybody reading the code. Why would you want to do this?
Anyway, for comparison, all you ever need is < and either == or !=, the rest is canonical and I write it mostly by muscle memory. Also, binary operators treating their operands equally (they le... |
2,845,429 | 2,845,555 | calling a function from a set of overloads depending on the dynamic type of an object | I feel like the answer to this question is really simple, but I really am having trouble finding it. So here goes:
Suppose you have the following classes:
class Base;
class Child : public Base;
class Displayer
{
public:
Displayer(Base* element);
Displayer(Child* element);
}
Additionally, I have a Base* object... | It seems a classic scenario for double dispatch. The only way to avoid the double dispatch is switching over types (if( typeid(*object) == typeid(base) ) ...) which you should avoid.
What you can do is to make the callback mechanism generic, so that the application doesn't have to know of the GUI:
class app_callback ... |
2,845,533 | 2,845,620 | How can I know whether my C++ string variable is a number or not | I have a string of class string
string str;
how can I check if it is a number or not, str can only have 3 possible types described below like
abcd
or a number like
123.4
or a number with a parenthesis attach to the end it for example
456)
note the parenthesis at the end of "str" is the only possible combination of ... | The C++ solution for parsing strings manually is string streams. Put your string into a std::istringstream and read from that.
What you could do to parse this is to try to read an (unsigned) int from the string.
If this fails, it is a string not starting with digits.
If it works, peek at the next character. If that's ... |
2,845,537 | 2,845,616 | Union struct produces garbage and general question about struct nomenclature | I read about unions the other day( today ) and tried the sample functions that came with them. Easy enough, but the result was clear and utter garbage.
The first example is:
union Test
{
int Int;
struct
{
char byte1;
char byte2;
char byte3;
char byte4;
} Bytes;
};
wh... | Note that, technically, reading from a member of a union other than the member that was last written to results in undefined behavior, so if you last assigned a value to Int, you cannot read a value from Bytes (there's some discussion of this on StackOverflow, for example, in this answer to another question).
Chris S... |
2,845,596 | 2,846,417 | How to connect/disconnect from a server? | I am using the latest version of boost and boost.asio.
I have this class:
enum IPVersion
{
IPv4,
IPv6
};
template <IPVersion version = IPv4>
class Connection
{
private:
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver;
boost::asio::ip::tcp::resolver::query query;
bo... | Generally, once you've made a call to io_service::run, there's often few reasons to call io_service::stop or io_service::reset.
In your code above, the connect method is not going to actively establish a connection - tcp::resolver::resolve merely turns a query (such as a hostname, or an IP address, etc.) into a TCP e... |
2,845,600 | 2,845,623 | C header file won't compile with C, but will with C++ | I have the following chunk of a header file BKE_mesh.h:
/* Connectivity data */
typedef struct IndexNode {
struct IndexNode *next, *prev;
int index;
} IndexNode;
void create_vert_face_map(ListBase **map, IndexNode **mem, const struct MFace *mface,
const int totvert, const int totface);
void create_ver... | In C++ you can refer to struct names directly but in C you need to prepend the keyword struct.
void create_vert_face_map(struct ListBase **map, ... );
You could get around this by adding a typedef. Then you wouldn't have to modify the function declaration.
typedef struct ListBase ListBase;
|
2,845,704 | 2,845,837 | How to interrupt a waiting C++0x thread? | I'm considering to use C++0x threads in my application instead of Boost threads. However, I'm not sure how to reimplement what I have with standard C++0x threads since they don't seem to have an interrupt() method.
My current setup is:
a master thread that manages work;
several worker threads that carry out master's ... | Unfortunately I don't see another way than polling, instead of using wait use a timed wait and a variable to state the interruption has been done.
void th(Interruptor& interruptor) {
try {
...
while (cnd1.timed_wait(d)==false) {
interruptor.check_interruption_point();
}
...
} catch (interrup... |
2,845,769 | 2,845,774 | Can a std::string contain embedded nulls? | For regular C strings, a null character '\0' signifies the end of data.
What about std::string, can I have a string with embedded null characters?
| Yes you can have embedded nulls in your std::string.
Example:
std::string s;
s.push_back('\0');
s.push_back('a');
assert(s.length() == 2);
Note: std::string's c_str() member will always append a null character to the returned char buffer; However, std::string's data() member may or may not append a null character to... |
2,845,792 | 2,852,168 | c# project cannot find c++ .dll? | I have a working c++ dll that works in one c# project that I am calling via the interop service. I have created another c# project and am trying to call the same .dll but keep getting a generic error message stating that the .dll cannot be found, both project are .net 2.0. What folder, and where do I specify in the p... | Make sure all the DLLs that the DLL in question depends on, are also in the same directory as the exe that uses the DLL.
|
2,845,793 | 2,845,861 | Build OpenGL model in parallel? | I have a program which draws some terrain and simulates water flowing over it (in a cheap and easy way).
Updating the water was easy to parallelize using OpenMP, so I can do ~50 updates per second. The problem is that even with a small amounts of water, my draws per second are very very low (starts at 5 and drops to ar... | Your approach to drawing in parallel is exactly the opposite of what you should be doing.
Graphics hardware is inherently parallel and there isn't much use in trying to make as many calls to it as possible in a very short time. It is important to make single huge calls that send data to the hardware where the parallel ... |
2,845,859 | 2,845,871 | #include <string> adding ~43 KB to my exe | I'm using Code::Blocks to write my program and when I include <string> (or <iostream>) the size of my exe grows. My program is very simple and I need to keep it small <20kb. I'm pretty sure this is happening because of the C++ Standards Committee swapped the old .h versions for many new libraries without the .h. But ho... | If size is your #1 concern (and if you have to keep things < 20KB, then it probably is) then the standard C++ library is probably not the way to go. In fact, any C++ at all (RTTI, exceptions, etc) is probably a bad idea and you would be better off just sticking with straight C.
|
2,845,980 | 2,845,999 | Thread safety with heap-allocated memory | I was reading this: http://en.wikipedia.org/wiki/Thread_safety
Is the following function thread-safe?
void foo(int y){
int * x = new int[50];
/*...do some stuff with the allocated memory...*/
delete [] x;
}
In the article it says that to be thread-safe you can only use variables from the stack. Really? Why... | If you are coding in an environment that supports multi-threading, then you can be pretty sure new is thread safe.
Although the memory is on the heap, the pointer to it is on the stack. Only your thread has the pointer to this memory, and so there is no risk of concurrent modification - no other thread knows where the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.