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 |
|---|---|---|---|---|
5,061,569 | 5,061,576 | Return type of an inline function | This method in Cocos2d:
/** Returns opposite of point.
@return CGPoint
@since v0.7.2
*/
static inline CGPoint
ccpNeg(const CGPoint v)
{
return ccp(-v.x, -v.y);
}
Why does it say 'CGPoint' after inline? Why not
static inline ccpNeg(...
?
| Because the function wants to return a CGPoint.
|
5,061,740 | 5,063,964 | decltype in class template specialization | I am trying to use decltype inside a template class as follows:
#include <functional>
template <typename T>
class A
{
typedef decltype(std::bind(&A::f, std::declval<A>())) some_type;
void f();
};
That works fine, but now I'd like to add an explicit specialization:
template <>
class A<void>
{
typedef declt... | Your order is wrong. Try exchanging it
template <>
class A<void>
{
void f();
typedef decltype(std::bind(&A::f, std::declval<A>())) some_type;
};
In the primary template, the name A::f was dependent and the compiler delayed lookup to a point where f was declared (A::f is not really dependent in C++0x anymor... |
5,061,821 | 5,063,615 | How to debug Cygwin failure? | I am porting from Centos to Cygwin and find that my application is exiting with no error message and exit status zero mid execution during the constructor for Botan::InitializationVector.
If I try to attach with gdb proactively in main() where it is waiting on a spin variable, I don't get a normal stack trace:
(gdb) wh... | Cygwin apps are multithreaded (e.g., one thread is the signal listener thread). Use info threads in gdb to find the thread that really faulted.
|
5,061,877 | 5,061,924 | What is the best library to use when writing GUI applications in C++? |
Possible Duplicate:
Gui toolkits, which should I use?
I've got a fair bit of C/C++ experience - mostly for writing console application for Windows/Linux, and also a fair bit of C# experience - generally for writing WinForms applications etc.
I'm extremely impressed with with ease at which I can create a window in .n... | Qt, hands down.
it's the most complete, most mature, fastest framework available. and on top of it, it's seriously multiplaftorm and your choice of commercially friendly open source or paid support.
|
5,061,906 | 5,065,147 | LAPACK/BLAS versus simple "for" loops | I want to migrate a piece of code that involves a number of vector and matrix calculations to C or C++, the objective being to speed up the code as much as possible.
Are linear algebra calculations with for loops in C code as fast as calculations using LAPACK/BLAS, or there is some unique speedup from using those libra... | Vendor-provided LAPACK / BLAS libraries (Intel's IPP/MKL have been mentioned, but there's also AMD's ACML, and other CPU vendors like IBM/Power or Oracle/SPARC provide equivalents as well) are often highly optimized for specific CPU abilities that'll significantly boost performance on large datasets.
Often, though, you... |
5,061,948 | 5,061,974 | default constructors and object copying | I'm wondering why I need to declare a default constructor in this case. For one thing doesn't the compiler do that automatically if i leave it out? And regardless, I still don't see why its necessary. Also, I get the error even if I omit 'obj_B = origin.obj_B;'
class B
{
public:
bool theArray[5] ;
B(bool x) {t... | The compiler only creates a default constructor if you don't specify an alternate constructor.
Because you made:
B(bool x) {theArray[1] = x;}
The default constructor will not be created for you.
The specific error you're getting is because A(A const &origin) doesn't specify the constructor to use for obj_B explicitly.... |
5,062,132 | 5,062,535 | How to port a PC game to Android written in C++ | I want to create a simple game like Space Invaders. I know that I can use Android NDK, but I have to port the libraries that I use. I can not use third-party proprietary libraries.
I will use OpenGL, but OpenGL API seems different on Android. I have to use jpeg and png textures, and write texts. Can I compile libjpeg, ... |
Can I compile libjpeg, libpng and freetype for Android?
Yes you will have to recompile all the native libraries specifically for Android. Yes, you do need the source code for all 3rd party native libs you plan to use simply because Usually when we compile and link these libraries outside Android they are linked to gl... |
5,062,163 | 5,064,805 | call function between classes | hello
I have 3 classes class A, B, and C
class A is the main class and content the main function also, i call class B and class C in the main as b1,b2 and c1.
in class B there is a vector (V) has list of int. and 3 functions Add, get and delete delete. all the thing in the class is public.
in class C i have function t... | Since play wants to do things that depend on b1 and b2, they are parameters of play.
Like this:
class c
{
public:
void play(const b& oneB, b& otherB)
{
int i = oneB.get();
otherB.add(i * 2);
}
}
int main()
{
b b1, b2;
c c1;
b1.add(10);
b1.add(20);
c1.play(b1, b2);
}
We'... |
5,062,220 | 5,062,248 | Does RTTI mean Dynamic Binding? | In C++, does Run-Time Type Information (RTTI) mean dynamic binding?
| RTTI means additional information is included in the compiler output so that runtime code can know details about the source code classes and types that would normally be thrown away in compilation.
For example, the machine code doesn't need to know the name of a function in order to call a function - calling a functi... |
5,062,236 | 5,062,346 | Expanding control characters in a string | In my application, i'm receiving std::strings like the following
"12\tcout << \"Text\" << endl;\n"
(its output from gdb's machine interface) I want to expand the control characters such that the string becomes
12 cout << "Text" << endl;
Is there some better way to do this other than parsing the string char by char... |
Is there some better way to do this other than parsing the string char by char and replacing each character sequence by the corresponding pretty-printed sequence?
No, and there's no feature of the standard library which does this, but if there was it would simply parse the string char by char.
std::string expand_tabs... |
5,062,335 | 5,062,621 | C++ Weird encoded character added at the end of my char pointer | I have a function to convert infix notation to postfix notation. The only problem that I am having is that the last character of the produced postfix notation string is �
�
Any ideas what is happening? This is the function. If I print the infix char* passed as parameter it's printed correctly. It's when I print the pos... | The gibberish character you're seeing is probably the EMPTY constant you're returning from pop on an empty stack. Stick an assert(!isempty(s)) in your pop function to make sure you're not trying to pop from an empty stack. If you run your program in a debugger, the debugger should show you the context (i.e stack trace)... |
5,062,457 | 5,063,938 | C# DLLImport 'Complex' array in return and parameters | I'm just writing a small test integration between a native C++ DLL called 'fft.dll' and a C# console application.
fft.dll contains a single class called Fourier which contains a single static method:
#include <complex>
using namespace std;
class Fourier
{
public:
static complex<double>* fft(complex<double>*);
};
T... | P/Invoke does not support calling static class functions, nor does it support and understand C++ templates.
As VinayC suggested, write another wrapper method in your C++ dll which is global and which marshals data from simple double array to/from the templated arrays that your C++ static function is using.
|
5,062,471 | 5,062,505 | How can I compile and run programs using graphics.h in code::blocks? | I am new to code::blocks, so I was wondering how could I compile and run my computer graphics animation programs (those that use graphics.h) in Code::Blocks.
Is this possible with the default installation?
| This is impossible. You can't use graphics.h without a time machine, so you're better off forgetting about it altogether. This question gets asked about once a week, and the consensus is always the same.
The graphics.h header is a proprietary graphics library included with Borland compilers back in the early 1980s. It ... |
5,062,488 | 5,063,350 | error C2400: inline assembler syntax error in 'second operand'; found 'register' | I am facing compilation error while working with assembly instructions in VC++ as MACRO inline based assembler blocks.
error C2400: inline assembler syntax error in 'second operand'; found 'register'
Here is the code:
_asm {\
mov esi,dword ptr [pMemBlock]\
sub esp,sizeOfblock\
mov ebx,sizeOfbl... | That blank line after the _asm { line will complete the macro. It should be deleted or have \ on it.
|
5,062,625 | 5,065,195 | Multiple Vertex Buffers per Mesh | I've run into the situation where the size of my mesh with all its vertices and indices, is larger than the (optimal) vertex buffer object upper limit (~8MB). I was wondering if I can sub-divide the mesh across multiple vertex buffers, and somehow retain validity of the indices. Ie a triangle with a indice at the first... | 8MB of vertex data is quite a lot for a single model. I'm pretty sure this model could be split into individual meshes. Good places for splitting a mesh are sharp edges, since vertices along these edges have different normal vectors are thus not identical and cannot be shared.
However more important than the VBO size i... |
5,062,699 | 5,062,741 | Operator overload of << needs const; produces headache | I am trying to overload operator <<, but it always need to be a const function. However, I want to change values inside this overloaded function. How do I do this?
EDIT1: The code stub is something like below:
class Check
{
public:
void operator << (boost::any)
{
// checks weather the given is hre... | You're likely doing something wrong then. Post the relevant bits of your code, along with a better summary of what your trying to do, and you'll get more help.
That being said, if you need to modify some data in a const object, there are a couple things you can do:
Declare the member you want to modify mutable.
Use c... |
5,062,758 | 5,074,431 | LNK2001: unresolved external symbol _MyClass.cpp | I am receiving the previous error with compiling a project in my solution. MyClass is within the project I am trying to compile (with included in project set to true), so I am unsure as to how it is an "external symbol". Does anyone know how to fix this?
Update: I think that this is definitely a Microsoft issue as if I... | I set the entry point to MyClass.cpp when I should have left it blank
|
5,062,991 | 5,063,068 | Linux fork within class on heap | What happens when I have the following situation:
class A: holds on to dynamically allocated object B's. It will create and destroy these.
class B: has an execute function called by A. Execute will fork() and the child will use execvp to run another process. BUT, a flag can be set so that the parent will not wait fo... | The child process is completely separate from the parent, and has a complete copy of the parent's variables. When the child executes (calls execve() or one of its relatives), no C++ destructors are executed. However, this has no effect whatsoever on the parent process.
So, there is no interference between the child a... |
5,063,334 | 29,414,111 | What is the difference between the /Ox and /O2 compiler options? | Microsoft's C++ compiler (cl.exe, as included with Visual Studio) offers several optimization switches. The difference between most of them seems self-explanatory, but it's not clear to me what the difference is between /O2 (which optimizes code for maximum speed) and /Ox (which selects "full optimization").
I've tried... | Asha's answer cites a blog post about Visual Studio 2005, and is rather out of date.
The latest version of the documentation is available here:
/Ox: https://msdn.microsoft.com/en-us/library/59a3b321.aspx
/O2: https://msdn.microsoft.com/en-us/library/8f8h5cxt.aspx
According to those:
/Ox → /Og /Oi /Ot /Oy /Ob2
/O2 → ... |
5,063,388 | 5,063,440 | Difference in execution speeds when run on different machines | I am running the below program on 2 different machines with different architectures. The practice in our organization is to build the executable in New York machine and copy it to Singapore machine.
Below is the architecture in New York and Singapore Machine.
New York:
SunOS pns15a-5203a 5.10 Generic_137111-04 sun4u s... | When benchmarking a function, it is incredibly important to perform the operation a very large number of times, and then divide the overall time by the number of runs. Otherwise, your timing results will just be too noisy to be meaningful. Also, if the machine is being used by other people, the timing can be impacted b... |
5,063,490 | 9,874,541 | How to extend TCL with C++? | Can I write a C++ code that can be compiled and used for extending TCL (I don't mean calling an executable file)? Can I describe some classes, functions and use them for in my TCl code by calling the compiled (.so or .a file) C++ code? If yes, then please explain me schematically how it is being done.
| http://cpptcl.sourceforge.net/ It is a C++ wrapper of Tcl C API and very convenient to use, well documented. I tell this from my personal experience.
C++/Tcl is a library that allows to easily integrate C++ and Tcl.
If you write programs in both languages, you will find it to be extremely helpful.
The C++/Tcl library ... |
5,063,504 | 5,063,516 | How to extend PHP with C++? | Can I write a C++ code that can be compiled and used for extending PHP (I don't mean calling an executable file)? Can I describe some classes, functions and use them for in my PHP code by calling the compiled (.so or .a file) C++ code? If yes, then please explain me schematically how it is being done.
| Yes, you can do so by writing a PHP extension.
See PHP at the Core: A Hacker's Guide to the Zend Engine.
|
5,063,577 | 5,063,829 | ASM/OPcode injection with C++ | I'm trying to inject some ASM code into a Win32 program with C++.
Is there a way to do this, avoiding DLL injection ?
This, for instance :
__asm{}
is only for the current program. Is there something similar used to generate hex code I could inject with WriteProcessMemory ?
Thanks in advance !
| In MSVC it may look like this:
void* shellcodeStart;
void* shellcodeEnd;
__asm {
mov shellcodeStart, offset shellcode_start
mov shellcodeEnd, offset shellcode_end
jmp shellcode_end
shellcode_start:
... // your code
shellcode_end:
... |
5,063,653 | 5,063,667 | 'Cast' an integer to a string | I have a casting problem. I am writing a code to open all the files that are in a folder and have a common name, but with a number that make them different. Let's see this in an easier way with examples. The name of one file will be Table1.txt, another one Table2.txt, another one Table3.txt and so on.
So I'm writing so... | I think that your problem is that the numeric values 0, 1, 2, ..., 9 are not equivalent to the character values for '0', '1', '2', ..., '9'. The digits actually have numeric values 48, 49, , 50, ..., 57. (See the ASCII table for more details). If you want to iterate across the numbers as characters, you can do so us... |
5,063,706 | 5,063,853 | C++ namespace ambiguity | I have both ::tensor::contract and ::tensor::detail::contract
#include "tensor/detail/contract.hpp"
namespace tensor {
template<typename Alpha, class A, class B, typename Beta, class C>
void contract(Alpha alpha, A a, B b, Beta beta, C c) {
detail::contract(alpha, a, b, beta, c);
}
template<... | Through ADL, associated namespaces are considered when resolving an unqualified function call. At least one of the parameters on that line is associated with the detail namespace.
ok, i see. does it matter if those types inherit from detail classes? – aaa
Yes, base classes are associated classes for the purposes of ... |
5,063,924 | 5,063,957 | Is C++ code allowed to call `::operator new()` directly? | According to C++ Standard paragraph 3.7.3/1 objects should be dynamically created with new expression and the C++ runtime should provide an allocation function ::operator new().
Once in a while it is necessary to call ::operator new() directly.
Does the C++ Standard allow such calls to ::operator new() function or is t... | It's perfectly acceptable to call operator new and operator delete directly; they are a part of the global namespace and act like a C++-ier version of malloc and free that interact with set_new_handler and the bad_alloc exceptions a bit nicer. The C++ ISO standard even contains a few examples of this. For example, §1... |
5,064,018 | 5,064,274 | Mangling/Exporting Problem with Mingw | I'm working on a shared C++ DLL using Netbeans and MinGW under Windows.
My first question is: will mangling be different between MinGW and Microsoft Visual C++?
I read that mangling is compiler specific - is it true? I need to obtain using MinGW the same mangling which I would have with MVC++, will this ever be possi... | Yes, name mangling is compiler-specific. It could even change between versions of the same compiler.
You should never expect anything about mangling and should treat it as a black box - never rely on it to be the same or different.
If you need inter-compiler linkage use extern "C".
|
5,064,377 | 5,064,413 | c++ comparing two floating point values | I'm wondering what is the difference for comparing two double between this two manner :
double a1 = ...;
double a2 = ....;
fabs(a1-a2) < epsilon
(fabs(a1-a2)/a2) < epsilon
Is there a prefering way to do that ?
thanks
| This article answers your question quite thoroughly, I think. You might want to skip ahead to the section "Epsilon comparisons".
|
5,064,580 | 5,064,849 | Lambda and bind not working together in VS2010 | This code fails to compile under VS2010:
#include <functional>
using namespace std;
void test()
{
auto f = [] (int) {};
bind(f, 10);
}
It gives a long error pointing to the internals of bind implementation.
If I switch to a normal function instead of a lambda, the bind works fine, so I believe this is a bug ... | It seems VC10 cannot cope with lambdas as arguments to std::bind. It seems to expect either a function pointer or a function object. I don't know whether this is a bug, but I suspect it is, since lambda function should become function objects during compilation.
Anyway, if you are in need of a workaround, this compile... |
5,064,614 | 5,067,992 | C++: Pointer to monomorphic version of virtual member function? | In C++, it's possible to get a pointer to a (non-static) member function of a class, and then later invoke it on an object. If the function was virtual, the call is dispatched dynamically depending on the dynamic type of the object. It's also possible (not using a member pointer) to call virtual member functions of obj... | It's possible in GCC, but the way it's documented in C++ language extensions section suggests there's no portable way to do it.
You can do two things:
If you control the class, create a non-virtual function and a virtual wrapper for it and when you know you don't need virtual dispatch, just take address of the non-vir... |
5,065,091 | 5,065,136 | C++what is the type of the __FILE__ macro | I am trying to create an exception class. For this I overloaded the << operator. So the code is something like this
class RunAndCheck
{
opearator << (boost::any given)
{
//Here goes the value of the "given"
}
};
The usage is like this
RunAndCheck s;
s << file->open() << __FILE__ << __LINE_... | __FILE__ expands into a string literal, just as if you had written "/path/to/current/file.cpp" directly. String literals are non-modifiable char array lvalues.
You want to template that << instead of using boost::any:
class RunAndCheck {
public:
template<class T>
RunAndCheck& operator<<(const T& value) {
... |
5,065,171 | 5,065,363 | What the heck does std::bind(x, y) do? | I'm stuck reading the description of std::bind in N3225, in subsection 20.8.10.1. It says the following should print 1, but I thought that bind is supposed to copy its arguments and therefor it should print 0. If one wants to refer to the passed argument, one needs to use std::ref, right?
void f(int &a) { a = 1; }
int... | Wow, this is confusing beyond belief. It defines v1 as tid and it as the following (ti is the i-th perfect forwarding bind parameter, and TiD is the decayed type of that parameter - i.e an array becomes a pointer etc).
tid is an lvalue of type TiD constructed from std::forward<Ti>(ti)
Alright, I did say, this tid is... |
5,065,914 | 5,065,927 | C++ real method overloading? | I have the classes A and B. B derives from A and overloads the method WhoAreYou(), when I now create a variable of type A and set the value to a B object and then call WhoAreYou(), the method of A is called. Look at this:
class A{
public:
virtual void WhoAreYou(){
cout << "I am A!"<<endl;
}
};
class B: ... | Your "a" variable is an A, not a B. A a = B(); creates a new temporary B, then creates an A by copying the A part of B.
Try this:
B b;
A * a = &b;
a->WhoAreYou();
|
5,066,057 | 5,066,094 | Keeping console window open when debugging | When I start a program without debugging (Ctrl+F5), I have to press a key to close the console window when the program is finished. When I start the program with debugging (F5), the console window closes immediately. Is there an option in Visual Studio that will keep the window open when debugging?
(I know of a thousan... | Add a break point to the ending bracket of the main() method. That way if the program finishes (unless it crashes in the process - which will trigger a break anyway) it will break no matter which return statement in the main was used.
|
5,066,375 | 5,067,587 | Analyzing Windows crash dumps generated on XP/32 machines with Win7/64? | We have a problem with analyzing our Windows crash-dumps that were created on customer Windows XP/32 boxes on our development machines.
Many of our development machines are now Win7/64 boxes, but it appears that the crash-dumps generated under Windows XP cannot full resolve their binary dependency, thereby leading to w... | I think WinDbg should be used in this case to analyze the dumps. Then you can get rid of such roadblockers. But just remember to use x86 build of WinDbg (part of Debugging Tools for Windows).
|
5,066,878 | 5,067,056 | What are good cases for using __if_exists? | When do I use __if_exists without writing tons of crappy code?
Looks like this keyword is like C preprocessor directive, but is processed after preprocessor. And IntelliSense doesn't parse it and highlight code as dead or alive. These together make analysis of code written with __if_exists really non-trivial.
So far I ... | I think you can use it to distinguish unions and classes, since classes do have constructors and unions don't.
You'd want this in e.g. boost::type_traits::is_class<T> and boost::type_traits::is_union<T>
|
5,067,174 | 5,068,364 | Need Help Regarding Classes | Its my first Object Oriented Program(I have been programming in C).I have to make a program which marks the attendance of the user when he signs in to the software.
Here is some details of the program:
The program starts and asks the user
to enter his ID and password.If the
user has entered the correct
password,... | At first glance, you'd find the following classes useful:
Student: Each user object should have a username and a password, and a way to validate an entered password. This might look like:
class Student
{
private:
string username;
string password;
public:
bool isPasswordCorrect(const string& passwordAttempt) cons... |
5,067,178 | 5,067,271 | How do I send UDP packets at a specified rate in C++ on Windows? | I'm writing a program that implements the RFC 2544 network test. As the part of the test, I must send UDP packets at a specified rate.
For example, I should send 64 byte packets at 1Gb/s. That means that I should send UDP packet every 0.5 microseconds. Pseudocode can look like "Sending UDP packets at a specified rate"... | Two approaches:
Implement your own sleep by busy-looping using a high-resolution timer such as windows QueryPerformanceCounter
Allow slight variations in rate, insert Sleep(1) when you're enough ahead of the calculated rate. Use timeBeginPeriod to get 1ms resolution.
For both approaches, you can't rely on the sleeps ... |
5,067,419 | 5,067,453 | Find the count of elements in array in C++ | I am trying to develop a C++ program. I am facing a problem. I have declared an array of length 100 as int arr[100].
But I have only filled 20 entries in it. Now I want to find the total number of elements in the array, which should be 20. How do I find the number of elements filled in the array?
I have tried
int size... | Every time you work with fixed-size arrays for which you want to consider some positions empty and the others filled, you must keep track of the filled element count in a separate variable. Why? Because you always have 100 elements in your array - you created them. Only that you are not using some of them - and only yo... |
5,067,492 | 5,067,545 | Why the sizeof(bool) is not defined to be one, by the Standard itself? | Size of char, signed char and unsigned char is defined to be 1 byte, by the C++ Standard itself. I'm wondering why it didn't define the sizeof(bool) also?
C++03 Standard $5.3.3/1 says,
sizeof(char), sizeof(signed char) and
sizeof(unsigned char) are 1; the
result of sizeof applied to any other
fundamental type (3... | Many platforms cannot effectively load values smaller than 32 bits. They have to load 32 bits, and use a shift-and-mask operation to extract 8 bits. You wouldn't want this for single bools, but it's OK for strings.
|
5,067,519 | 5,067,614 | Problem converting array of struct from C++ to C# | I want to convert this C++ code to C#:
typedef struct consoleCommand_s
{
char* cmd ;
void (*function)() ;
} consoleCommand_t ;
static consoleCommand_t commands[] =
{
{"clientlist", &CG__Clientlist},
{"say", &CG_Say},
{"nick", &CG_Nick},
{"logout", &CG_Logout}
} ;
// e.g.
stati... | You could do without having a class INSIDE another class and manage your default console commands in another.
public delegate void ConsoleCmd();
public class DefaultCommands
{
public static void Nick()
{
Console.WriteLine("I'm Nick!");
}
public static void LogOut()
{
Console.WriteL... |
5,067,706 | 5,067,734 | A question about friend functions | I faced a problem recently with a 3rd party library which generates classes from a xml. Here is a gist of it:
class B;
class A
{
void doSomething();
friend class B;
};
class B
{
void doSomething();
void doSomethingMore()
{
doSomething();
}
};
The compiler flags call to the function do... | There is no ambiguity. The function called in A requires an A instance. The function called in B requires a B instance.
doSomethingMore is called on a B instance and therefore the function that gets called is the one in B.
You seem to have misunderstood friendship. All it means is that, in this case, given an instance ... |
5,067,721 | 5,067,967 | Is there anyway to tag a .wav file and write a time into it? | I would like to add into each one of my .wav files a time tag. This tag would say when the file has started in time and if possible an end time. The time could be relative to the unix epoch. How would I go about doing this or can it even be done?
Thanks
-Josh
| WAV files support limited, text-based tagging, which probably works fine for you. You can specify user-defined fields in the INFO chunk ( http://en.wikipedia.org/wiki/Resource_Interchange_File_Format#Use_of_the_INFO_chunk), which is probably suitable for your needs, but there's no simpler way like you get with ID3 tags... |
5,068,104 | 5,068,567 | HowTo compare std::wstring & char*? | What I have:
[wstr1] 1 std::wstring value (e.g. "(GMT+04:30) Kabul")
[str2] 1 char* filled with the same data as std::wstring (with the same text)
I'm simply trying to compare this two value - but the following code doesn't appear to work. KMP.
Here is the converter from char* to std::wstring,
std::wstring TimeZone:... | Compare like this, if you're sure that you have only ASCII characters.
Otherwise, you can pass a custom (locale dependant ?) comparer to std::equal.
bool weirdEquals(char const* c, size_t n, const std::wstring& str)
{
if (str.size() < n) return false;
return std::equal(c, c + n, str.begin());
}
|
5,068,157 | 5,068,290 | Load library failed, but symbol is available from referenced library | I'm trying to write a Python binding for a C++ library from a vendor we have. I'm moving along, but it's quite painful (partly because we don't have the source for the library).
Right now, gcc (4.4.4) complains about some Exception class it can't find:
Load library for "FOO_Sessions" failed, the system error message is... | Set LD_LIBRARY_PATH to /home/djc/foo/lib/ before running, or explicitly load the dependant library before libFOO_Sessions.so. man ld-linux explains how the dynamic linker will search.
EDIT:
Also, set LD_DEBUG=all before running in order to see how the dynamic linker searches.
|
5,068,262 | 5,069,193 | How do I implement array::max_size()? | I am building my own array<T, n> class template for fun and education. The C++0x standard draft specifies a member function max_size() for all containers as distance(begin(), end()) "for the largest possible container". How do I implement this member function for arrays? Do I simply return std::numeric_limits<std::size... | I agree that the draft is somewhat lacking here.
It is unclear whether container here references:
any container
any container of this family
any container of a given instance of this family
Unlike @Jerry I would lean toward the latter option.
Looking at basic_string::append, the description states:
Throws: length_er... |
5,068,566 | 5,068,974 | How can I run Visual Basic code in a running Visual Basic 6.0 process (e.g. MSVBVM60.DLL)? | I'm working on debugging a legacy Visual Basic 6.0 application; the application was built into native code, but unfortunately we just have the binaries, but no source code. So I'm rather limited as far as modifications to the program go.
My final goal is to get the value of the 'Name' property of some controls given th... | A VB6 ActiveX DLL will run in the client process, but it won't have access to the Forms collection of the client process. I think the App.hInstance should return the same value though.
If you are debugging your DLL in the VB6 IDE debugger, that will cause it to run in a separate process. That debugger does some crazy t... |
5,068,588 | 5,068,838 | Migration from Windows ffmpeg 0.52 to linux ffmpeg 0.61 code error. How to fix it? | Previously I used ffmpeg on windows (0.52 build I found somewhere). Now I am porting to linux and to latest ffmpeg. So far I got 4 errors in 2 lines
On such simple line:
size = avpicture_get_size(pix_fmt, nWidth, nHeight);
I get:
initializing argument 1 of ‘int avpicture_get_size(PixelFormat, int, int)’ C/C++ Pro... | PixelFormat is defined as an enum in pixfmt.h. I think that the problem is that in C++, there is no implicit conversion from an int to an enum. So, you need to explicitly convert the int to PixelFormat. Try this:
size = avpicture_get_size(static_cast<PixelFormat>(pix_fmt), nWidth, nHeight);
or you could just make p... |
5,068,607 | 5,068,635 | `*this = rhs` in Java? | I'm coming from the C++ world and I can't find what is the Java alternative (if any) to the following:
struct SomeStruct
{
SomeStruct(){}
SomeStruct(const SomeStruct& rhs)
{
*this = rhs;
}
};
The reason why I need this is that I have a cache of existing objects, so I don't want to create anothe... | The closest is Object.clone() but read the relevant section from Effective Java first.
There are probably simpler ways to do what you want if you remove some of your requirements. For example, if you make your objects immutable then you don't need to copy the data into another object. Instead you can return a reference... |
5,068,697 | 5,068,868 | PThreads & MultiCore CPU on Linux | I am writing a simple application that uses Threads to increase the performance.
The problem is, that this application runs fine on windows, using the 2 cores that my CPU has. But When I execute on Linux, It seems that only uses 1 Core.
I can't understand why this happens.
These is my code, C++:
#include <stdio.h>
#inc... | clock() works different on windows vs linux, so don't use that to measure time. On linux it measures CPU time, on windows it measures wall clock time. Ideally these would be the same in this test case, but you should use something consistant between the platforms to measure the time. e.g. gettimeofday()
rand() seriali... |
5,069,098 | 5,069,233 | Auto wrap c++ dll into c# | I want to use c++ library in a c# project. Is there any wrapper tool to import all classes automatically?
| SWIG can help create a wrapper consisting of two parts, one C++ sided, and one C# sided.
It needs a bit of work to set up the correct generation files though.
An alternative that requires more manual coding is C++/CLI.
For pure c apis I prefer p/invoke over either of them. There is a program to automate conversion of c... |
5,069,119 | 5,077,081 | VC++ Visual Studio 2010 AssemblyName | I'm creating an automated build system for a group of projects. Most are C# and VB but we have a few VC++. I need to extract the AssemblyName properties for all of the projects before the build starts to perform some custom stuff. The C# and VB projects have an AssemblyName element inside the .csproj and .vbproj files ... | Thanks, those elements were not in my .vcxproj. Perhaps you have an older .vcproj? Anyway it did lead me to find <TargetName/> in the Microsoft.Cpp.props file that is imported into every .vcxproj file. In there is the following line:
<TargetName Condition="'$(TargetName)' == ''">$(ProjectName)</TargetName>
This was no ... |
5,069,319 | 5,069,349 | Predefinition of often used values in computations - does it change anything? | I'm auto generating C code to compute large expressions and try to figure out with simple examples whether it makes sense to predefine certain subparts in separate variables.
As a simple example, say we compute something of the form:
#include <cmath>
double test(double x, double y) {
const double c[9][9] = { ... }... | Using pow with integer arguments... ouch ! Typical implementations of pow are tuned for the general case of floating point arguments, which is why it is usually way slower to write
pow(x, 2) ( = exp(2 * log(x)) )
than
x * x
What I state here is very compiler dependant though. On one hand, some compilers may not even ... |
5,069,425 | 5,069,498 | Objective C and c++ import problem. Simple but I don't get it | I'm using cocos2d and box2d.(iPhone SDK) If I want to import box2d I add this to the top of the file #import "Box2D.h" and then I rename my class to ".mm". Now I have just a class without a ".m" file just a ".h" file.
It looks like that and if I import box2d it gives me many errors because box2d is c++ and normally i n... | Try to rename header to .hh, cause compiler still treats it as Objective C
|
5,069,517 | 5,069,532 | Trying to return an iterator with nested struct gives "does not name type" error | I'm defining a vector of a private struct inside a class, then trying to get a private function of that class to return an iterator. Simplified code:
#include <vector>
class A
{
private:
struct B {
...
};
std::vector<B> vecB;
typedef std::vector<B>::iterator BIter;
BIter FindSomething();
}... | The last line should be
A::BIter A::FindSomething() { ... }
The reason is that BIter is internal to the A class, and when the compiler gets to the definition of BIter A::FindSomething, the context (the A class) has not been established for the return type, so you must fully qualify it.
|
5,069,522 | 5,069,573 | opengl models do not overlap correctly cross platform | edit: I have added a few new lines of code to the beginning for depth buffering with no luck. See code..
edit 2: I am constructing the model builder on a wxglcanvas via wxwidgets. I have initialized WX_GL_DEPTH_SIZE of 16 and WX_GL_DOUBLEBUFFER on top of enabling depthbuffering and glClear(GL_DEPTH_BUFFER_BIT) with no ... | Sounds to me like your z-buffer isn't enabled. Without a z-buffer, the geometry is simply drawn in the order of the issued OpenGL commands. Effectivly, there is no "behind".
To get the z-buffer to function properly, you'll need to:
Request a z-buffer for your rendering window. This is platform specific.
Call glEnab... |
5,069,605 | 5,069,757 | C++ and multi-tier architecture | To attain the highest grade in a recent piece of coursework I'm asked to develop a specific application using c++ and multi-tier programming.
I understand the theory behind multi-tier architecture and exactly which parts of this application belong to which layer but i have no experience actually implementing "n-tier" a... | Usually, when you hear "n-tier" application framework (in college), they are referring to logically grouped functionality. It can be in separate processes, but is not necessarily the case. The Model-Control-View architecture or MFC's Document-View architecture are both layered. You simply want to separate code that ... |
5,070,040 | 5,070,273 | Compiling from source vs. deb package | I'm compiling several C/C++ packages from source on Ubuntu. I compare the results from my build to running with the debian install, and find that my executables are slower.
I used readelf -a to compare the two executables. Things like the relocation section for '.rela.dyn' are substantially different, but I'm not sure ... | Well, as it is open source, you should get the compile flags they use to generate the executables :)
my2c
|
5,070,057 | 5,070,082 | Catching a memory allocation error in a constructor? | I sometimes need a class in C++ which allocates dynamic memory. Since this can fail, I need to detect when the memory cannot be allocated. Usually, I do this as in the example below, ie. I do not allocate memory in the constructor but have a separate method for this, where a bad_alloc exception can be caught.
Is there ... | Not really. my_instance will be an invalid instance that can't be used.
http://www.gotw.ca/publications/mill13.htm
|
5,070,066 | 5,070,154 | C++ Linker errors when calling constructor (Beginner :-() | I am coming back to c++ after 20 years but the language seems to have evolved a lot. I cannot get this to run. I feel like a student.
This is an AVL tree exercise. The avl code was just downloaded (not mine).
// AVL.H
#include <iostream>
template <class Comparable>
class AvlTree
{
... | When you use templates, you almost always have to declare and define the templates in the header file. You can't put the definitions of function templates or class template member functions into a separate .cpp file because the compiler needs to have the definition available when you use the template.
For more informa... |
5,070,070 | 5,070,118 | C++: Using '.' operator on expressions and function calls | I was wondering if it is good practice to use the member operator . like this:
someVector = (segment.getFirst() - segment.getSecond()).normalize().normalCCW();
Just made that to show the two different things I was wondering, namely if using (expressions).member/function() and foo.getBar().getmoreBar() were in keeping ... |
or unforeseen pitfalls that would introduce bugs into the program
Well, the possible pitfalls would be
Harder to debug. You won't be able to view the results of each function call, so if one of them is returning something unexpected you will need to break it up into smaller segments to see what is going on. Also, ... |
5,070,161 | 5,071,345 | Designing a thread-safe copyable class | The straightforward way to make a class threadsafe is to add a mutex attribute and lock the mutex in the accessor methods
class cMyClass {
boost::mutex myMutex;
cSomeClass A;
public:
cSomeClass getA() {
boost::mutex::scoped_lock lock( myMutex );
return A;
}
};
The problem is that this makes the class n... | The simple fact is that you cannot make a class thread safe by spewing mutexes at the problem. The reason that you can't make this work is because it doesn't work, not because you're doing this technique wrong. This is what everyone noticed when multithreading first came and started slaughtering COW string implementati... |
5,070,352 | 5,078,798 | decltype in static_assert | Why this (static_assert) in a definition of a class doesn't work?
template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
static_assert(std::is_same<decltype(low),decltype(high)>::value,"Different types not allowed");
};
int _tmain(int argc, _TCHAR* argv[])
{
int low, high;
X<char,1,'a'>... | static_assert works fine, is your code that never assert.
The template struct X defines low and high as of type IntT. They are both the same type, whatever values they have.
When you instantiate the struct (X<char,1,'a'> x) you are telling the compiler that the type of IntT is char and are giving to low the value 1 a... |
5,070,487 | 5,076,376 | IronRuby and C++ DLL | I want to call c++ function from dll. Is it possible to use something like DllImport from C# in IronRuby?
| There is no option to do that directly from IronRuby at the moment. You will need to wrap the C++ library with a C# assembly (using P/Invoke) and then use the C# assembly from IronRuby.
|
5,070,521 | 5,070,601 | does `const auto` have any meaning? | I think the question is clear enough. Will the auto keyword auto-detect const-ness, or always return a non-const type, even if there are eg. two versions of a function (one that returns const and the other that doesn't).
Just for the record, I do use const auto end = some_container.end() before my for-loops, but I don'... | Maybe you are confusing const_iterator and const iterator. The first one iterates over const elements, the second one cannot iterate at all because you cannot use operators ++ and -- on it.
Note that you very seldom iterate from the container.end(). Usually you will use:
const auto end = container.end();
for (auto i = ... |
5,070,557 | 5,070,749 | Missing characters using read() from unistd.h | We're using the read() method from unistd.h to receive data from the serial port in a Linux environment. To read data from /dev/ttys1 specifically.
Part of the data we're receiving include the characters 0x0A (line feed) and 0x0B (vertical tab), but the library seems to ignore them.
I mean, we use an unsigned char[] to... | ttys? Are you sure to put the terminal driver in the correct state to pass out those characters?
(See tcgetattr and tcsetattr). Depending on your precise setting, you can play interactively with those settings with the stty program.
|
5,070,561 | 7,584,377 | DebugDiag Crash Rule Does Not Auto-Execute | I'm using DebugDiag for the first time, and I'm using it on Windows 7 x64. I've created a crash rule for (x86) myprogram.exe, which is guaranteed to crash because I've coded it intentionally to crash with an "unknown exception (0xc0000417)".
I have windows "startup and recovery" configured to capture mini-dumps. It w... | I assume you are using version 1.1 of DebugDiag.
I'm afraid it is not fully functional on Windows 7.
In version 1.1, the analysis-only version is installed and leak-tracking and dump generation does not work.
If you plan to generate dumps on application crash, you can use ProcDump from SysInternals with -e -ma flags.
D... |
5,070,775 | 5,070,989 | Desktop Sharing and Chat open source | I need library or ready to use open source desktop sharing and chat application in C#, C++ or Java. I should use this in my project.
I see real vnc is not open source anymore? don't suggest real vnc.
Please suggest most SIMPLE and easy to use library/application.
| Take a look at TightVNC
Also take a look at these questions on stackoverflow
How can I display a VNC Viewer in a Java rich client (LGPL, Apache, MIT license)?
Java VNC Libraries
|
5,071,069 | 5,071,143 | Behavior of simple code with pointers in C++ | Suppose we have the following code:
sphere * a, * b;
a = new sphere(1.0);
b = a;
b->setRadius(2.0);
delete b;
a->setRadius(4.0);
sphere * c = new sphere(5.0);
b = new sphere(3.0);
cout << a->getRadius() << endl;
What will be the outcome:
(a) 4.0
(b) 3.0
(c) A segmentation fault.
(d) Compiler error.
(e) The behavior ca... | Up to delete b; everything is ok. The next line (a->setRadius(4.0);) will trigger an undefined behaviour, because you are accessing a deleted object. The problem is that 90% of the times it will work (yes, this is a problem, because the other 10% of the times it will crash and you will lose the night finding why!)
Why ... |
5,071,094 | 5,071,366 | Sane Configuration Method for very Complex Piece of Software? | We are writing a C++ program, that needs to be highly configurable (at start time).
Right now we have a base XML file, which contains several configuration variables, and filenames of other XML files with more configuration variables. All in all, we have a tree of about 10 XML files, and several binaries file formats w... | Lua was designed for configuration.
|
5,071,141 | 5,071,340 | Suitable Data Structure for storing and calculating Highest Scoring K items | I need to store W items. Each item has a 'string' attribute and a 'double' attribute (the item's score) associated with it. In each iteration, additional C items are added to the set. After the iteration is complete, score of some of the items is updated by a small amount. Now, out of the W+C items only W items need to... | I would store these values in two parallel structures. First, have an array of the double values, each of which stores a pointer. Next, store all the strings in a hash table along with an auxiliary integer. The idea is that the pointers in the array point to the nodes in the hash table or trie holding the string ass... |
5,071,179 | 5,078,879 | When I resize a label from code rubbish displays briefly on the new empty space | I'm resizing and moving controls.
The code is working as I want, except that I'm getting a black rectangle displayed briefly in the new space before the correct display appears.
The moving of a control is done when another control changes its height.
I make the changes from OnPaint in a class derived from Label and... |
I'm probably doing something wrong, but I don't know what.
One logically wrong thing that you're doing is resizing from within a paint event. That makes no logical sense. Inside a paint event, the portion of the control to be repainted has already been determined (and is indeed supplied in the event arguments). Re... |
5,071,413 | 5,071,485 | How to CreateProcessAsUser and make it a foreground window? | I'm trying to start an UI using CreateProcessAsUser but the window doesn't come as the foreground Window.
I wouldn't mind if it was a normal window, but this window triggers the UAC prompt and it isn't displayed in foreground neither.
| From your description, it sounds as if you are trying to launch the other process in elevated mode. If that's what you're trying to do, you cannot set it to the foreground window. In fact, non-elevated processes aren't allowed to touch elevated processes in any way/shape/form.
The created process has to be responsible ... |
5,071,482 | 5,071,527 | Question on abstract base classes in c++ | Suppose class stringGetter contains exactly one pure virtual function: the overloaded paren-
theses operator, string operator()(int x). Also suppose that class getPageString is a
public stringGetter that implements operator().
Which of the following C++ statements will certainly result in a compiler error?
(a) stringGe... | (a) results compiler error because instances cannot be created for abstract classes.
|
5,071,600 | 5,071,678 | When accessing a C++ variable how is its content resolved? | When accessing a variable in C++, how is its content resolved?
Is it possible for the OS to remap the variable to a different address without affecting its logical address? Is it possible to have 2 variables pointing to the same logical address in 2 different processes?
| Yes, it's absolutely possible for the OS to move variables around in memory. Virtually all modern computers use virtual memory, in which each process believes that it has access to the machine's full address space. Whenever a memory read or write occurs, though, the address is translated from the virtual address in t... |
5,071,640 | 5,071,737 | Tips for an AI for a 2D racing game | I have a school project to build an AI for a 2D racing game in which it will compete with several other AIs.
We are given a black and white bitmap image of the racing track, we are allowed to choose basic stats for our car (handling, acceleration, max speed and brakes) after we receive the map. The AI connects to the g... | There's no "right answer" for this problem - it's pretty open-ended and many different options might work out.
You may want to look into reinforcement learning as a way of trying to get the AI to best determine how to control the car once it's picked the different control statistics. Reinforcement learning models can ... |
5,071,890 | 5,072,043 | temporary variables and performance in c++ | Let's say we have two functions:
int f();
int g();
I want to get the sum of f() and g().
First way:
int fRes = f();
int gRes = g();
int sum = fRes + gRes;
Second way:
int sum = f() + g();
Will be there any difference in performance in this two cases?
Same question for complex types instead of ints
EDIT
Do I understa... | You can answer questions like this for yourself by compiling to assembly language (with optimization on, of course) and inspecting the output. If I flesh your example out to a complete, compilable program...
extern int f();
extern int g();
int direct()
{
return f() + g();
}
int indirect()
{
int F = f();
int G ... |
5,071,963 | 5,072,308 | Why cant i call 'explicit C(const C&)'? | Heres the link to code and the error
I dont understand why the line return (const C&)cc; doesnt work.
Heres a paste of code and error
#include <stdio.h>
class C
{
public:
int i;
explicit C(const C&) // an explicit copy constructor
{
printf("\nin the copy constructor");
}
explicit C(int i... | Examples of calling the explicit copy-constructor:
http://ideone.com/bV4S7
http://ideone.com/G0OYi
Of course, pass-by-value and return-by-value always call the copy constructor implicitly, so declaring the copy constructor explicit will prevent this (not necessarily a bad thing).
|
5,072,058 | 5,073,114 | how to convert bash script to C++ using boost::iostreams | I'm trying to convert the following bash code into C++ using boost::iostreams:
#!/usr/bin/bash
(
gzip -cd file1.ext.gz
cat file2.ext
) | grep '^regex' # or sed 's/search/replace/'
I can open a file and decompress it:
std::ifstream s("file.ext.gz", std::ios_base::in | std::ios_base::binary);
boost::iostreams::f... | 1) I don't know if there's anything built into boost, but this class seems to be exactly what you want: http://hamigaki.sourceforge.jp/hamigaki/iostreams/concatenate.hpp
The catch here is that it expects CopyConstructible devices to concatenate and Chains seem to not be CopyConstructible. However, we can easily work ar... |
5,072,082 | 5,072,381 | Assignment via copy-and-swap vs two locks | Borrowing Howard Hinnant's example and modifying it to use copy-and-swap, is this op= thread-safe?
struct A {
A() = default;
A(A const &x); // Assume implements correct locking and copying.
A& operator=(A x) {
std::lock_guard<std::mutex> lock_data (_mut);
using std::swap;
swap(_data, x._data);
r... | I believe your assignment is thread safe (assuming of course no references outside the class). The performance of it relative to the const A& variant probably depends on A. I think for many A that your rewrite will be just as fast if not faster. The big counter-example I have is std::vector (and classes like it).
st... |
5,072,257 | 5,072,289 | std::lower_bound and comparator function with different types? | I have an array of structures, sorted on a member of a structure, something like:
struct foo
{
int bar;
double baz;
};
// An array of foo, sorted on .bar
foo foos[] = { ........ };
// foos[0] = {0, 0.245}
// foos[1] = {1, -943.2}
// foos[2] = {2, 304.222}
// etc...
I want to find the element with a specific .... | From the standard, 25.3.3.1/3, on std::lower_bound():
Returns: The furthermost iterator i in the range [first, last] such
that for any iterator j in the range
[first, i) the following
corresponding conditions hold: *j <
value or comp(*j, value) != false.
From that, you may use
bool comp(foo a, int b)
or you ... |
5,072,286 | 5,072,327 | Problem returning vector from a function | error: expected constructor, destructor, or type conversion before '<' token
Relevant section of C++ code:
InputParser::vector<bar*> getFooBar(){
return bars;
}
We have defined vector bars; as a private variable in the header file.
Can someone please explain how to resolve this error?
| Your question is not too clear. If this is supposed to be a std::vector, that's not the type you are using. Assuming getFooBar is a member of InputParser, the syntax is:
std::vector<bar*> InputParser::getFooBar()
{
return bars;
}
|
5,072,340 | 5,072,614 | C# Marshalling double* from C++ DLL? | I have a C++ DLL with an exported function:
extern "C" __declspec(dllexport) double* fft(double* dataReal, double* dataImag)
{
[...]
}
The function calculates the FFT of the two double arrays (real and imaginary) an returns a single double array with the real an imaginary components interleaved: { Re, Im, Re, Im, ..... | There are a few problems with your example:
The C++ code has no idea how big those arrays are. The marshaller will pass them a valid pointer, but without a corresponding length parameter, there's no way to tell how big they are. sizeof(dataReal) and sizeof(dataImag) is likely 4 or 8 on most platforms (i.e. sizeof(vo... |
5,072,411 | 5,072,462 | Why does this code continuously print newlines? | int row,column;
for (;;) {
cin >> rows >> columns;
if (!rows && !columns) break;
vector<char> dots(rows * columns);
copy(istream_iterator<char>(cin), istream_iterator<char>(), dots.begin());
// process vector
copy(dots.begin(), dots.end(), ostream_iterator<char>(cout, " "));
cout <... | An istream_iterator reaches its end when an input error or end-of-file occurs (buffer overrun which may happen with your vector doesn't count :) ).
Once cin is in error or EOF state, all subsequent input operations will fail (unless you cin.clear(); the state) and the code ends up just displaying newlines.
It's a bit... |
5,072,487 | 5,072,500 | C++ operator overloading method | I'm working through some home work and having problems with how to form my method signature for overloading a member of a class.
My header file
class MyInt
{
int internalInt;
public:
MyInt::MyInt(int i);
const MyInt operator+(const MyInt& mi);
const MyInt& operator++();
};
My code file
MyInt::MyInt(in... | try:
const MyInt& MyInt::operator++()
{
cout << "Inside the operator++\n";
internalInt++;
return *this;
}
You are returning the this pointer, not the reference, you need to dereference it.
|
5,072,554 | 5,072,596 | How does Stroustrup's Can_Copy template work? | Stroustrup provides a Can_copy template. How does it work?
template<class T1, class T2> struct Can_copy {
static void constraints(T1 a, T2 b) { T2 c = a; b = a; }
Can_copy() { void(*p)(T1,T2) = constraints; }
};
In particular, why does he need the line void(*p)(T1,T2) = constraints; instead of an empty constru... | It's because not used member functions in templates don't exist in generated code, so to check constrainst you would have to call constraints() explicitly somewhere.
This way code for constraints() is generated, so constraints are checked in compile time (and that is the purpose of Can_copy).
|
5,072,845 | 5,072,864 | Scope with Brackets in C++ | Is there any case in which putting code within brackets to reduce its scope is something that I might want to do, or is this one of those cases in which you guys will tell me, "If you need to do that in your code, then your code is badly written."
For example:
//***CODE****
{
int foo=stuff;
//use foo, and then I'm ... | Yes, because this has the advantage that any local variables in that block will be destroyed at the end of the block. This is especially useful if you have some kind of scope guard that you want to release as soon as possible, e.g.,
{
std::lock_guard<std::mutex> lock(the_mutex);
// use protected objects
} //... |
5,072,916 | 5,072,975 | Determining if a type is derived from a CRTP base class | I'm trying to create an is_foo function, that I can then use with enable_if, to determine if a type is derived from a certain CRTP base class. The code below is my attempt at implementing the is_foo function, but it doesn't actually work. Could someone tell me what I need to change to fix it?
Thanks.
#include <iostre... | Add a typedef to the Foo base:
template < typename Derived >
struct crtp
{
...
typedef int is_crtp;
};
Implement a has_field check:
BOOST_MPL_HAS_XXX(is_crtp)
Implement your metafunction:
template < typename T >
struct is_crtp_derived : has_is_crtp<T> {};
This is the only way I can think of that will correctly c... |
5,073,122 | 5,073,174 | Dynamic allocation or automatic recommended for subsystem creation? | I am a hobbyist C++ programmer and currently working on a game (using Ogre3D) and I have a question regarding the memory allocation for my main classes.
I have read a lot on memory allocation, allocating automatically on the stack and dynamically on the heap, and their differences (performance, limited stack size). Sti... | Always prefer automatic allocation over dynamic allocation. And when you need dynamic allocation, make sure its lifetime is managed by automatically allocated resource wrappers, like smart pointers.
|
5,073,273 | 5,073,301 | thread using 100% of core | Is there a way to use multiple cores for one thread? I am presently using Qt on Ubuntu with an i7
| No.
You can run one thread per core. You can run many threads on one core via time sharing. But you cannot run one thread on two cores. (Not at the same time, but it can switch between cores).
|
5,073,274 | 5,074,302 | QTopengl c++ simple 2d app | Im trying to make a simple 2D application, and our image processing professor has told us to use opengl. Im working with c++ and QT.
I want to open a simple window that holds a place where I can draw points of different colors. All by code, there is no user interaction. I cant use any other library, can anyone tell me ... | check out :
http://www.digitalfanatics.org/projects/qt_tutorial/chapter14.html
|
5,073,350 | 5,073,366 | Accessing arrays by index[array] in C and C++ | There is this little trick question that some interviewers like to ask for whatever reason:
int arr[] = {1, 2, 3};
2[arr] = 5; // does this line compile?
assert(arr[2] == 5); // does this assertion fail?
From what I can understand, a[b] gets converted to *(a + b) and since addition is commutative, it doesn't really ma... | Yes. 6.5.2.1 paragraph 1 (C99 standard) describes the arguments to the [] operator:
One of the expressions shall have type "pointer to object type", the other expression shall have integer type, and the result has type "type".
6.5.2.1 paragraph 2 (emphasis added):
A postfix expression followed by an expression in sq... |
5,073,458 | 5,073,490 | C++ Noobie - I cannot get past solving this for my homework assignment. I am stuck. Please help! | "I cannot seem to get this C++ program to work!! I have been trying for a couple of hours, and I am not grasping the concept. Here is the question from the book:
"Write a C++ function:
void rect (int& ar, int& per, int len, int wid)
that computes the area ar and perimeter per of a rectangle with length len and width w... | A simple call with rect (ar, per, len, wid); should work fine. You have to provide the right number of parameters as expected by the function (which is four).
And you should probably also add:
per = 2 * (len + wid);
to your rect function as well, but I assume that was coming once you'd sorted this problem out.
You sho... |
5,073,507 | 5,073,602 | Include files in c++? | I was wondering how to include files in C++... I was looking at a lot of different things and could not figure it out. I just want to include another function or method or w/e you call it.
I know you need like #include "filename.cpp"; but I don't know how to use stuff from filename.cpp or .h or w/e you want to call it.... | Usually, in headers goes the declarations and in source files goes the implementation. Though there is a exception for this in case of templates. Remember that only source files get compiled. So, what ever symbols present in the source file must be known to the compiler. Now taking an example -
foo.h
struct foo
{
i... |
5,073,590 | 5,073,643 | Simple audio manipulation library? | I want to make an application that can split an mp3 into pieces. Ex: if I give t a 3 minute song, and want 3 parts, I would expect 3 new mp3s at 1 minute each.
Thanks
| I'd try this: http://mp3splt.sourceforge.net/mp3splt_page/about.php
It claims to have a GUI, and command-line interface, and even a library. I'd probably start with the GUI or CLI and see how it goes.
|
5,073,674 | 5,076,337 | Create password dialog window | How do i put up a password dialog window before starting up the main dialog window?
| You just need to create the dialog as you would create any other dialog.
Perhaps the root of your question is that you aren't sure how to create the EDIT control that shows a password. The trick is to create it with the ES_PASSWORD style so that the text the user enters is hidden when they type.
You'll probably not wan... |
5,073,992 | 5,074,112 | Extract IP address from a string using boost regex? | I was wondering if anyone can help me, I've been looking around for regex examples but I still can't get my head over it.
The strings look like this:
"User JaneDoe, IP: 12.34.56.78"
"User JohnDoe, IP: 34.56.78.90"
How would I go about to make an expression that matches the above strings?
| The question is how exactly do you want to match these, and what else do you want to exclude?
It's trivial (but rarely useful) to match any incoming string with a simple .*.
To match these more exactly (and add the possibility of extracting things like the user name and/or IP), you could use something like: "User ([^,]... |
5,074,029 | 5,074,523 | Is there a good/widely adopted c++ template coding convention/standards? | I like coding standards. When writing C++ I love coding standards. A good coding standard adds context to the language, making the hard to parse a little bit easier.
There are a few commonly practiced standards that I think everyone is at least a little bit familiar with:
Member variables prefixed with 'm' or 'm_'
Cla... | Just adding my grain of salt. I think the two most important libraries in the world of C++ programming are the Standard Template Libraries and the Boost Libraries. I personally try to mostly conform to the kind of notation that is predominant in these libraries. That is, underscore-separated lower-case names for classe... |
5,074,122 | 5,130,444 | std::istream_iterator<> with copy_n() and friends | The snippet below reads three integers from std::cin; it writes two into numbers and discards the third:
std::vector<int> numbers(2);
copy_n(std::istream_iterator<int>(std::cin), 2, numbers.begin());
I'd expect the code to read exactly two integers from std::cin, but it turns out this is a correct, standard-conforming... | Unfortunately the implementer of copy_n has failed to account for the read ahead in the copy loop. The Visual C++ implementation works as you expect on both stringstream and std::cin. I also checked the case from the original example where the istream_iterator is constructed in line.
Here is the key piece of code from ... |
5,074,208 | 5,074,388 | std::fill does not turn into memset for POD types | I am expecting a std::fill on an continuous container, say std::vector, will automatically compiled to a call of memset. However, when I tried the following code
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
vector<double> vec(300000);
fill(vec.begin(),vec.end(),... | Addressing your specific example of double, it would have to be a platform specific optimization and most likely g++ decided not to do such a thing. The reason is of course any platforms using a representation of double for which 0.0 does not mean all zero bytes. Note that additionally, setting to any number OTHER than... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.