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
6,536,303
6,536,333
Using "double" as counter variables in loops
In a book I am currently reading, there is this excerpt: You can also use a floating-point value as a loop counter. Here's an example of a for loop with this kind of counter: double a(0.3), b(2.5); for(double x = 0.0; x <= 2.0; x += 0.25) cout << "\n\tx = " << x << "\ta*x + b = " << a*x + b; This code fr...
The first one will eventually terminate, even if x doesn't reach exactly 2.0... because it'll end up being greater than 2.0, and thus break out. The second one would have to make x hit exactly 1.0 in order to break. It's unfortunate that the first example uses a step of 0.25, which is exactly representable in binary fl...
6,536,469
6,536,649
How to restrict part of public interface of a class to only one class?
Following is an interface: class SIM{ private: //private data public: Send(); Display(); Recieve(); Encrypt(); }; How do I restrict access to Display() function (it has to be lie in public part) of SIM to other classes except one class (Neo etc). I don't want to use friend etc. Edit: I can move the display() to priva...
You can have Display take a dummy const reference to a type that can only be created from a privately nested within the class you want to be able to make the calls. Then in order to pass that type to Display you have to be a member of that class. But why would you do that when friend does exactly what you want? Code ex...
6,536,686
6,537,571
How do I convert my apache 2.0 module project to C++?
I already developed a C based module for my Apache 2.0 environment and it works well but I am not a total expert at C programming so I would like benefits of C++ try/catch, strings, and other C++ benefits. While researching Apache modules, I ran across several articles that said specifically all work needed to be in C ...
Some open source framework propose C++ layer to apache2.0 module environment such as WSO2CPP. Code provided is not so complex to understand if you don't want to introduce such a library between your code and apache. You may be interested in the ServiceSkeleton class ...
6,536,747
6,536,776
Sign(+/-) error in byte in Java byte setting operations
I am declearing in Java public byte[] orbits = new byte[38]; Now if I am doing orbits[24] = (byte)0xFF; orbits[24] should get populated by 11111111 i.e FF(in hexadecimal) but instead its getting populated with -1. This operation in C++ working perfectly char orbits[38] orbits[24] = (char)0xFF; How to replicate the s...
Well, it just happens that -1 is 0xFF. Everything is correct. byte stores values from -128 to 127 using two's complement. In Java there are no unsigned types. If you want to use bit patterns, then use byte. 0xFF and -1 are the same thing in this situation. If you want to use numbers, that is, 0xFF is actually 255 and n...
6,536,748
6,536,979
const reference to function pointer
I have a function Foo and a class CDelegate. typedef void (*typeFctPtr)(void*); void Foo(void* dummy) { cout << "Foo\n"; } class CDelegate { public: CDelegate (const typeFctPtr& f_ref_Wrapper, void* f_pvSubscriber) : m_ref_Wrapper(f_ref_Wrapper), m_pvSubscriber(f_pvSubscriber) { } inline void ...
You're holding a reference to a pointer to a function (and the pointer is a temporary which has been destroyed by the time you use it, so things go badly wrong). Try changing your typedef to be a function type: typedef void typeFct(void*); ... const typeFct & m_ref_Wrapper; Then with your existing code you'll end up w...
6,536,805
6,536,848
Initializing a static const array of const strings in C++
I am having trouble initializing a constant array of constant strings. From week.h (showing only relevant parts): class Week { private: static const char *const *days = { "mon", "tue", "wed", "thur", "fri", "sat", "sun" }; }; When I compile I get the error "excess elements ...
First of all, you need an array, not a pointer. static const char * const days[] = {"mon", "tue", "wed", "thur", "fri", "sat", "sun"}; Second of all, you can't initialize that directly inside the class definition. Inside the class definition, leave only this: static const char * ...
6,537,416
6,537,500
WriteFile returning error 1784
I am creating a program to populate a disk with a dummy file system. Currently, I am writing files of variable sizes using WriteFile. WriteFile(hFile, FileData, i * 1024, &dwWrote, NULL); err = GetLastError(); err returns #1784 which translates to The supplied user buffer is not valid for the request...
My guess is that FileData is not large enough for you to write i * 1024 bytes from it. Is i the loop control variable for your list of files? If so, you need the write buffer FileData to grow 1K at a time as you loop through your files. This is an unusual construct. Are you sure the logic is correct here? Post more...
6,537,553
6,638,336
Wrapping a template function with boost.python
I'm trying to expose the following c++ function to python using boost.python: template <typename genType> genType refract( genType const & I, genType const & N, typename genType::value_type const & eta); and what I got is this: template<typename N> N reflect(N const & i, N const & n,...
This is not the perfect answer since it requires abusing the type system and writing plenty of additional glue code. You could try defining a wrapper template to decorate your target type such that it would have the necessary typedefs to satisfy the calling function (reflect). This example demonstrates the failings of ...
6,537,632
6,537,689
Writing OpenGL applications in C++
I am a linux user. I write OpenGL applications in python but i am going to write OpenGL applications in C++ , but i have a problem. there is no 'GL' folder in '/urs/include' directory and i have not acces to OpenGL headers. what should i do? is there not installed packages?
You have to install it. For Ubuntu, I think the command is: sudo apt-get install freeglut3 freeglut3-dev As this installs everything freeglut depends on. For other linux distros (I run Arch Linux), just search Google for opengl headers {distro}.
6,537,794
6,538,298
Instruction pointer strange behavior
I'm experiencing a very weird problem. Let's say I have a class, a public member of which is a vector of pointers to some type: class SystemState { // ... public: SystemState (const SystemState& s); // copy constructor std::vector <Concept *> m_L; // ... }; I fear it is important to know that the Concept class...
Rule of Three: If a class defines one of the following it should probably explicitly define all three[1]: destructor copy constructor copy assignment operator Your class SystemState defines a destructor and a copy constructor, but not a copy assignment operator. Consider: SystemState t; { SystemState s; s.A...
6,537,948
6,538,103
Storage allocation of local variables inside a block in c++
I want to know at which point the compiler allocates storage for local variables inside a block. How does goto and switch jump past a constructor? : class Tree {/*...*/} ... void foo (int i){ if (i < 10) goto label; //illegal: cannot jump past a ctor Tree t (45); label: switch (i){ case 1: Tree ...
6.7/3: It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) ...
6,538,059
6,538,091
Not able to compile C/C++ code that's using ncurses
I've just discovered ncurses and have just started learning it, however the examples in my tutorial don't compile on my computer. I had to install ncurses manually and did so by entering "apt-get install libncurses5-dev libncursesw5-dev". I had to do this because before having done so I got an error saying that I could...
you have to link the ncurses library g++ -o hello_world hello_world.cpp -lncurses
6,538,104
6,538,119
looking for a c++ socket dll to use in c#
I want to write a c# program that create a socket using a native socket dll witch is would be written in c or c++ any idea about a good c++ socket dll ?
You can do this yourself using direct PInvoke on the Winsock API, which is all wrapped up in a system DLL. The question is, why would you want to? Unless the hypothetical DLL has some added value that's not clear in the question, can't think why using System.Net is not infinitely preferable.
6,538,133
6,538,184
How can boost::bind call private methods?
boost::bind is extremely handy in a number of situations. One of them is to dispatch/post a method call so that an io_service will make the call later, when it can. In such situations, boost::bind behaves as one might candidly expect: #include <boost/asio.hpp> #include <boost/bind.hpp> boost::asio::io_service ioServic...
You can call any member function via a pointer-to-member-function, regardless of its accessibility. If the function is private, then only members and friends can create a pointer to it, but anything can use the pointer once created.
6,538,211
6,538,836
Is it a good thing that the top items in my programs profile are _Unwind_SjLj_Unregister and _Unwind_SjLj_Register?
As a follow up to this question, is it a good thing that my the top 2 things are still exception handlers? on one hand, its doing a lot of exceptions. on the other, this is in sdl, meaning that its probably as optimized as possible, which means that my other functions are really fast. so... here's the top of the profi...
These are not exception handlers, but rather functions to notify the exception handler of destructors that need to be called if an exception is thrown. For example, consider for (int i = 0; i < 1000000; ++i) { std::string stuff; // or any type with a non-trivial destructor function(); // maybe with argum...
6,538,227
6,538,538
How do you convert C++ _tcscpy, _tcscat to Delphi?
I'm converting this code from C++ to Delphi but I don't get the following part of the code. Can anyone explain me what the following code means; what's happening to the szBuff buffer ? I'm pretty sure it's such kind of formatting (replacement), but I don't even know what is expected as a result and I can't find any sen...
_tcscpy and _tcscat are TCHAR macro versions of C standard library functions strcpy and strcat for copying and concatenating C strings. They evaluate to ANSI or Unicode versions depending on whether or the type of project you are targeting. It's really C code rather than C++ code in my view. In Delphi you would simpl...
6,538,234
6,538,458
MPI_Barrier and recursion
I'm trying to use MPI_Barrier (OpenMPI) to force all the process to be in the same depth of a recursive call. This is the code #include <iostream> #include <fstream> #include <stdio.h> #include <mpi.h> using namespace std; void recursive_function(int,int,int); int main(int argc, char *argv[]) { int rank, size; ...
There is no guarantee that stdout among the MPI processes is ordered in any way. That is, you need to have the processes communicate to prove that they are all at the same recursion depth. E.g. after the barrier each process != 0 sends a message to rank 0 which prints something.
6,538,547
6,538,586
Array by reference length in C++
Possible Duplicate: Calculating size of an array This question has been asked before, but I want to confirm it. Let's say I have the following C++ function: #include <stdio.h> #include <stdin.h> #define length(a) sizeof(a)/sizeof(a[0]) int main() { double c[] = {1.0, 2.0, 3.0}; printf("%d\n", getLength(c)); ...
The template version would work. Who said it will not work? template<typename T, int size> int length(T(&)[size]) { return size; } This is correct. It will return the length of the array. You just need to call this function directly. It seems you want to call this function from getLength(). Don't do that, because...
6,538,605
6,538,715
Defining a new Object of a Class within a Template in C++, Error: Missing Template Arguments
Have a simple program, where I can insert a string into a statically defined array of strings of size 20. This program worked just fine, until I was assigned to change it to use templates, so the code (with modificaiton) would support intergers or strings. Using the Class "Shelf" in the included header, I can no longe...
You need to specify a parameter to T. Templates need to be instantiated with the datatype passed as a parameter, like so: Shelf<std::string> book;
6,538,631
6,539,431
UnitTest++ command line arguments
I want to use a command line argument in one of my tests. I couldn't find any example of this on the web. TEST(SomeTest) { std::string file("this is some command line argument"); CHECK(something); } int main(int argc, char** argv) { return UnitTest::RunAllTests(); } Any ideas?
Answer There's no real reason to test command-line arguments directly. Instead, write your unit tests to check the behavior of your code (functions and classes) given different arguments. Once you are satisfied that your code is working properly under unit test, simply plug it into main and it should work properly ther...
6,538,632
6,538,690
How to expose a map of pointers as a map of const pointers?
I have a class with an std::map of pointers as a member. Now, I'd like to expose that member in a read only fashion: modification is not allowed for neither the map, nor the objects pointed to. Internally I need those pointers to be non-const, and I want to expose them as const. I do have a solution that compiles at le...
This is of course undefined (EDIT: it looks like it's actually only unspecified) behavior because the two maps are (from the language point of view) totally unrelated types. It may appear to work now but sometime it's going to break and cause a ton of headaches. Did you consider that instead of exposing an implementati...
6,538,707
6,538,803
C++ problem with Datagram (UDP)winsocket to sendto and recvfrom on the same socket through the loopback adapter
I am trying to send some data with a udp socket and receive them back on the same socket through windows loopback adatper. In my network properties I set the loopback adapter to have the following ip 192.168.1.1 the recvfrom function returns -1 indicating an error. I also monitor the traffic on the loopback adapter wit...
You are binding your server socket to port 0, i.e. asking the OS to assign random port number to it. That has to be the same port you are sending to, 27015 in your case. Also, you don't have to byte-swap INADDR_ANY.
6,538,896
9,725,937
Can't create modal dialog from MFC DLL
I'm trying to launch a modal dialog from a DLL loaded by an MFC application. I'm using VS2010 and both the EXE and DLL use MFC in a static library. I call DoModal() in my DLL to launch the dialog, with the parent being a CWnd* pointing to the main window from the MFC app. The dialog resource is in the DLL. This event...
Check that you've actually created a CWinApp somewhere in your current module (DLL/EXE). Every module should have one, and only one, CWinApp object. Typically, you would make the CWinApp object a global variable such that it is created and destroyed when the module is loaded and unloaded, respectively.
6,539,009
6,754,303
gcc exception specification of default destructor
class A { public: virtual ~A() { } }; class B : virtual public A { public: ~B() throw() {} }; class C : public B { }; int main(int argc, char * argv []) { return 0; } That code gives the following error: error: looser throw specifier for ‘virtual C::~C()’ error: overriding ‘virtual B::...
I presume that in the real code either ~A() or ~B() is declared virtual? (The error message is complaining about a virtual destructor, but in the code as written none of the destructors are virtual.) I believe the virtual inheritance is what is triggering your problem. C's (implicitly defined) destructor is required to...
6,539,011
6,539,046
templates and typedef
I have some class like : template<int DIMENSION, typename T> Vector { ... } Now, I want to specialize the typename and provide a new type using a typedef. I thus found an answer on StackOverflow at C++ typedef for partial templates I thus did : template < int DIMENSION> using VectorDouble= Vector<DIMENSION, doubl...
The answer you refer to says: If you have a C++0x/C++1x compiler C++1x is not yet current, so most compilers don't support its features. In particular, VC++9.0 (VS2008) has almost no support for them. VC++10 (VS2010) does support some features, but I don't know if what you need is one of those.
6,539,345
6,539,972
Using inp() on 16Bit Dos 5with Turbo C++ 3.0
First off I'd like to say that I know this is a really outdated question. That,s probably why I can't find any information through google. (or I'm just worse at searching than I'd like to admit! haha.) All the results pretty much tell me that inp() & outp() are useless on modern systems because the kernel handles al...
This looks thorough: http://www.beyondlogic.org/spp/parallel.htm Also, make sure you configure the parallel port in the BIOS for Bidirectional mode. Other possibilities are Output Only, EPP and ECP modes, but Bidirectional will work best for what you are trying to do. You'll need bit 5 in 0x37a to control the directi...
6,539,707
6,539,758
Template error with dependent names
In the following code, I get a compile error that I don't have if I remove the templates : template<int DIM> class myClass { public : enum Mode {aa,bb}; myClass(){}; }; template<int DIM> class myClass2 { myClass2(){}; void myfunc(myClass::Mode m); }; template<int DIM> void myClass2<DIM>::myfunc(myCl...
I believe that you have two problems in your code. The first is in this declaration in myClass2: void myfunc(myClass::Mode m); Because myClass is a template, you need to specify what the template parameter is. I assume that you probably meant to write void myfunc(myClass<DIM>::Mode m); However, due to a weird idios...
6,539,942
6,540,214
how to modify private members that are const?
I know this sounds like a strange question, but bear with me. I have a custom class that has some large objects which need to be returned by reference to avoid a copy. My class looks something like this: class csv_File { public: csv_File(std::string); //constructor std::string const& access(int,int)...
After fixing up your program, and with the hint from @user763305, I suppose you have something like this (note: this program compiles, but invokes undefined behavior when run, since the storage vector is left empty): #include <string> #include <vector> class csv_File { public: csv_File(std::string) {} std::string ...
6,540,304
6,540,907
C++ COM Interop: Using C# namespace with dot notation in c++
I have a C# namespace defined as A.B.C which I tried using in a C++ header with using namespace A::B::C; and I get error C2653: A is not a class or namespace. The unmanaged project is referencing the managed project with this namespace. How do I get around this? TIA.
COM Interop doesn't let you do that. COM interop lets you retrieve a C++ COM interface pointer to a .NET object, using e.g. CoCreateInstance. If you want to refer to the C# namespaces and types directly (not through a COM interface pointer), you want C++/CLI (the /clr option for Visual C++).
6,540,307
6,540,326
Converting Binary to Decimal using while loop in C++
I am currently reading a book on C++ and there is a task which asks the reader to convert a binary number (inputted by the user) to a decimal equivalent. So far I have the following code, but all it does is output 0. Any idea what has gone wrong? #include <iostream> using namespace std; int main() { int x, b = 10, dec...
Because the while( x > 0) loop only stops when x <= 0. Besides, cin >> x lets the user input a decimal number.
6,540,320
6,540,374
Casting floating point (double) to string
I'm running into something I've never seen before and would very much like to understand what is going on. I'm trying to round a double to 2 decimal places and cast that value to a string. Upon completion of the cast things go crazy on me. Here is the code: void formatPercent(std::string& percent, const std::string& va...
std::precision sets the maximum number of significant digits to display On the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum and therefo...
6,540,386
6,540,583
Assembly Performance Tuning
I am writing a compiler (more for fun than anything else), but I want to try to make it as efficient as possible. For example I was told that on Intel architecture the use of any register other than EAX for performing math incurs a cost (presumably because it swaps into EAX to do the actual piece of math). Here is at...
To even have a hope of repeatable, determinstic timing at the level that RDTSC gives, you need to take some extra steps. First, RDTSC is not a serializing instruction, so it can be executed out of order, which will usually render it meaningless in a snippet like the one above. You normally want to use a serializing ins...
6,540,606
6,540,677
Round Double and Cast to String
I suppose this question is a follow up to a previous question I had regarding casting a double to a string. I have an API where I'm given a string which represents a number. I need to round this number to 2 decimals of precision and return it as a string. My attempt to do this follows: void formatPercentCommon(std::s...
Streams are the usual formatting facility in C++. In this case, a stringstream will do the trick: std::ostringstream ss; ss << std::fixed << std::setprecision(2) << number; percent = ss.str(); You are probably already familiar with setprecision from your previous post. fixed here is used to make the precision affect t...
6,540,735
6,540,809
Break a loop when the user just input an enter in visual c++ or code blocks
I want to know how to make stop a while loop when the user just input an Enter without asking to continue or , here is my code: int main() { bool flag = true; int userInput; while(flag){ cout<<"Give an Integer: "; if(!(cin >> userInput) ){ flag = false; break;} foo(userInput); }...
Use getline. Break if the string is empty. Then convert the string to an int. for(std::string line;;) { std::cout << "Give an Integer: "; std::getline(std::cin, line); if (line.empty()) break; int userInput = std::stoi(line); foo(userInput); } std::stoi will throw an exception on failure,...
6,540,777
6,540,797
How do you cast unsigned short data[32] to unsigned char* very fast
If you had to convert unsigned short data1[32] to unsigned char* data2 in a tight loop to be executed 10 million times what function would you use to get the best performance? I am using this reinterpret_cast<unsigned char*>(data1); but was wondering if there is a better way
reinterpret_cast is the holy grail of performance seeking coders, namely code that results in zero clock cycles.
6,540,948
6,540,990
C++ templates: how to determine if a type is suitable for subclassing
Let's say I have some templated class depending on type T. T could be almost anything: int, int*, pair <int, int> or struct lol; it cannot be void, a reference or anything cv-qualified though. For some optimization I need to know if I can subclass T. So, I'd need some trait type is_subclassable, determined as a logi...
You want to determine whether it is a non-union class. There is no way known to me to do that (and boost hasn't found a way either). If you can live with union cases false positives, you can use a is_class. template<typename> struct void_ { typedef void type; }; template<typename T, typename = void> struct is_class { ...
6,541,068
6,541,111
Need help passing some LPCTSTR's to a function in C++
I'm very new to C++ and have a question that is probably obvious. I am able to use the MSDN example to install a service (http://msdn.microsoft.com/en-us/library/ms682450%28v=VS.85%29.aspx) if I have it in a stand alone program. I'm trying to add this as a function inside another project and am having trouble passing t...
LPCTSTR is long pointer to const text string Depending on whether you are targeting a UNICODE/MBCS/ANSI build you'd need const char* (ANSI/MBCS) const wchar_t* (UNICODE) (from memory)
6,541,087
6,541,106
C++ to Java conversion question about extern "C"
I have to convert some C/C++ code to Java. My C++ is extremely rusty. In a .h file, I have the following: #ifdef __cplusplus extern "C" { #endif /* tons of declarations */ #ifdef __cplusplus } /* extern C */ #endif What is the use of extern "C"? What does it mean? Is it telling the compiler that corresponding code s...
It's telling the compiler that function signatures should be C compatible. Name mangling are different in C and C++ (i.e. C++ supports method overloading while C does not) so in order to make some function calls (i.e. some DLL dynamic calls) compatible with C signature, you use extern C in C++ code. Take a look at this...
6,541,194
6,545,275
C++/Tk how to exequte general tcl code?
So we have code like: #include "cpptk.h" #include <stdio.h> using namespace Tk; void hello() { puts("Hello C++/Tk!"); } int main(int, char *argv[]) { static char* str = "button .a -text "Say Hello ppure TCL"\n" "pack .a\n"; init(argv[0]); button(".b") -text("Say Hello") -comman...
Have you got access to the Tcl_Interp* handle used inside C++/Tk? If so (and assuming here you've got it in a variable called interp) use: int resultCode = Tcl_Eval(interp, str); Next, check the resultCode to see if it is TCL_OK or TCL_ERROR (other values are possible, but uncommon in normal scripts). That tells you t...
6,541,651
6,541,708
Google Mock: leaked mock object found at program exit?
When I define my test as follows it works. TEST(MyService, WhenCalled_DoesTheRightThingTM) { // Arrange ThirdPartyClassFake stub; EXPECT_CALL(stub, GetFirstName()) .WillRepeatedly(Return("Bob")); // Act std::string result = stub.GetFirstName(); // Assert EXPECT_STREQ("Bob", resul...
0xc0000005 is Access Violation, from memory. What's likely is that this SEH exception was thrown and the destructor wasn't called properly if you didn't compile the code with the right switches.
6,541,725
6,542,226
Writing a console-based C++ IRC-client
I'm learning C++ and so I've decided to begin coding a IRC-Client. I basically want it to be consolebased, and I've looked in to libraries such as ncurses, but I don't really know whether or not this would be the best approach. I imagine the UI being divided into one part where whatever messages are written appear, and...
Using ncurses for the interface sounds like a good idea. You can do a single-threaded select-based network and terminal client -- check out Beej's guide. Alternatively, Boost.asio, single-or-multithreaded, should be a solid choice, too.
6,542,004
6,648,127
Is it possible to compile a VST on linux?
For a class project I'm attempting to write a VST plugin backed by CUDA. My current CUDA workflow is on a Linux box, so I'd prefer to compile and link there. According to Wikipedia, this should be possible (I couldn't find any Steinberg documentation relevant to Linux) but I can't find a Makefile or instructions on ho...
jVSTwrapper seems to run on linux, but they are only supporting the 2.4 SDK at the moment. Actually, that's a much safer bet, as not too many hosts have full VST3 support yet, and the 2.4 SDK is more or less universal. You will probably have more luck building with that SDK under linux, but it's still going to require ...
6,542,026
9,585,206
Constructor and anonymous union with const members
Is it possible to have an anonymous union with const members? I have the following: struct Bar { union { struct { const int x, y; }; const int xy[2]; }; Bar() : x(1), y(2) {} }; With G++ 4.5 I get the error: error: uninitialized member ‘Bar::<anonymous union>::xy’ with ‘const’ type ‘const int [2]’
This was a problem in GCC that was fixed in version 4.6. Your code now works fine. It still depends on a GCC extension because it uses an anonymous struct, but most compilers support them now. Also, the following code now builds properly with -pedantic: struct Bar { union { const int x; const int y; }; Ba...
6,542,083
6,542,698
What is the cause of this overload resolution headache?
I've got a program where I've got a lot of nested if/switch statements which were repeated in several places. I tried to extract that out and put the switches in a template method class, and then allow clients to overload which switch branches they wanted to specifically handle using overloading: class TraitsA {}; clas...
Any ideas why it's failing that conversion instead of choosing the perfectly good generic overload in MergeFoo? Yes, because of name hiding rules. If a function in the derived class has the same name as a function in the base class, the base class function is "hidden", it doesn't even look at the parameters of the in...
6,542,135
6,542,371
dynamic_cast to the same type does not check type of object
I am trying to determine whether an object pointed by a T* pointer is truly a T object, or some other, unrelated type. I tried dynamic_cast, however it is less than useless, it returns the pointer itself instead of null even when it is obvious it does not point to a valid T object: Object* garbage = reinterpret_cast<Ob...
Base on your example, it sounds like you've got shallow copy Arrays which someone could trick into containing different types than they are supposed to contain. I think the "normal" solution to this problem would be to make that difficult for users to do (i.e. don't provide conversions between Array<T> and Array<U>). ...
6,542,208
6,542,335
Best simple way to mock static/global function?
I have a simple almost value-like class like Person: class Person { public: Person(ThirdPartyClass *object); virtual ~Person(void); virtual std::string GetFullName() const; virtual int GetAge() const; virtual int GetNumberOfDaysTillBirthday() const; }; I'm using a third party library and the Third...
Create a link seam. Put your destroy declaration in a header, and then have two implementation files: // Destroy.cpp void Destroy() { //Code that really does destruction } And for testing: // DestroyFake.cpp void Destroy() { //Code that does fake destruction } Then link the first file to your main binary, and...
6,542,339
6,545,111
Calculate offset/skew/rotation of similar images in C++
I have multiple images taken simultaneously pointing at the same direction from the same starting location. However, there is still a slight offset because these cameras were not in the exact same place when the picture was taking. I'm looking for a way to calculate the optimal translation/shear/skew/rotation needed to...
Here is a short code that does what you want (I use openCV 2.2): Suppose you have 2 images: srcImage,dstImage, and you want to align them The code is very simple. Use it as basis for your algorithm. Code: // Detect special points on each image that can be corresponded Ptr<FeatureDetector> detector = new SurfFeat...
6,542,342
6,555,512
Determine max length of thrust::device_vector
Is there a way to determine the maximum size of thrust::device_vector<T> that you can safely allocate?
There isn't a straightforward way that I am aware of. My usual approach has been to do something like this: const size_t MB = 1<<20; size_t reserved, total; cudaMemGetInfo( &reserved, &total ); char fail = 0; while( cudaMalloc( (void**)&pool, reserved ) != cudaSuccess ) { reserved -= MB; if( reserved < MB ) ...
6,542,367
6,542,401
Templated C++ Object Files
Lets say I have two .cpp files, file1.cpp and file2.cpp, which use std::vector<int>. Suppose that file1.cpp has a int main(void). If I compiled both into file1.o and file2.o, and linked the two object files into an elf binary which I can execute. I am compiling on a 32-bit Ubuntu Linux machine. My question regards how ...
It knows what the templates are through name mangling. The type of the object is encoded by the compiler in its name, and that allows the linker to filter out the duplicate implementations of the same template. This is done during linking, and not compilation, because each .o file can be linked with anything thus canno...
6,542,683
6,542,706
Use of the function IsWin2000() produces a C++ warning: C4996 - Deprecated Function
So when I am using the function, IsWin2000(), to figure out whether or not the computer running my application is running windows 2000, i get the warning: warning C4996: 'IsWin2000': This function is exported to support existing modules and is obsolete. If this is an obsolete, deprecated function, what is the proper w...
GetVersionEx See the Remarks at OSVERSIONINFO for a list of results and how to interpret them. See Getting the System Version for a fully fledged example. And lets not forget what the spec says: Identifying the current operating system is usually not the best way to determine whether a particular operating syste...
6,542,688
6,542,723
unable to declare class without initialization?
For standard data objects such like int, the following can be done int number; number = 0; Basically, you can declare number before initializing it, useful if you initialize inside various if statements and you don't want number going out of scope. Can something similar be done with custom classes? I have a cl...
Your first line will give you an error since the constructor doesnt have default values and a constructor without parameters doesnt exist. Just use a pointer (or even better a smart pointer, so you dont have to take care of deleting the object). But be sure to check afterwards that x was either 0 or 1, i.e. check that ...
6,542,747
6,542,910
boost::thread undefined reference
I just installed the boost libraries and I am trying to use multi - threading. I copied this example exactly from the boost library example. I am getting the error: undefined reference boost::thread::join() Here is the code, #include <boost/thread.hpp> #include <boost/thread/xtime.hpp> #include <iostream> struct threa...
which compiler? try this if it is gcc $ g++ -o ./app.out ./source.cpp -lboost_thread if you are running on windows, perhaps that you have to make sure that the pthread you have installed, and also you have to tell the compiler where and how to link them together, your application and 3rd party lib such as boost_thread...
6,542,794
6,544,328
How to get the Linux Flash ROM size in C?
Is there any C/C++ library or Linux system command that i can use to get the ROM size? ON start-up the Kernel displays the proper size in Mb. I just can't seem to find where i can pull it from Thanks -Naze By the way, im using a jff2 ROM file system on an embedded system. ARM7 cpu.
If it appears as an mtd device, you can do the following cat /proc/mtd dev: size erasesize name mtd0: 00030000 00010000 "BootLoaders" mtd1: 00200000 00010000 "Kernel" mtd2: 00280000 00010000 "RootFS" mtd3: 00350000 00010000 "User" Size are in hexadecimal For more information on an individual mtd, you will find t...
6,543,035
6,543,047
Using Interlocks for thread synchronization and maintaining cache coherency
If I were to use some kind of algorithm that uses InterlockCompareExchange operations on a variable in C++ that determines if a set of data is being written to by a particular thread (by creating my own little lock), how do I ensure that the interlocked operation that updated the value is immediately seen by the other ...
The compiler can't reorder loads or stores across an interlocked function call, and the implementation will include whatever machine instructions are needed to make sure the CPU core won't. Cache coherency is always maintained, the only thing you have to worry about is when the value actually gets written out from the ...
6,543,229
6,543,235
delete[] Array of characters
Possible Duplicate: delete[] supplied a modified new-ed pointer. Undefined Behaviour? Let's say I've allocated a handful of characters using new char[number]. Will it be possible to delete only a few end characters (something like delete[] (charArray + 4);, which will supposedly de-allocate all of characters except ...
The only "safe" way to do it is to allocate a new array, copy the data, and delete the old one. Or you could just follow the std::vector way and differentiate between "capacity" (the size of the array) and "size" (the amount of elements in it).
6,543,244
6,543,322
why does this C++ code print a after every line?
#include <iostream> using namespace std; int main() { for (;;) { char ch ; if (cin.fail()) break; cin.read((char*)&ch, sizeof(unsigned char)); cout<<hex<<(unsigned int)(unsigned char)ch<<endl; cin.clear(); } } Why does this code always print a after every line? I just used any char as st...
The a that you see is simply the hex value of the '\n' character at the end of the line of input. If you don't want to see that character, simply wrap the output line in an if statement that checks for that character and doesn't bother to do any output when it's seen: if (ch != '\n') { cout<<hex<<(unsigned int)(uns...
6,543,313
6,543,337
typedef function pointer that takes argument ClassName* before defining ClassName?
I have the following situation: typedef void (*F_POINTER)(ClassName*); class ClassName { public: F_POINTER f; } This happens because an instance of ClassName needs to pass a pointer itself to the client. However, If I write things in this order, I get complains about ClassName not declared, whatnot. Howev...
Forward declaration: class ClassName; typedef (*F_POINTER)(ClassName*); class ClassName { public: F_POINTER f; } Or shorter: typedef (*F_POINTER)(class ClassName*); // implicit declaration;
6,543,500
6,543,572
QSyntaxHighlighter highlight part of match with QRegExp
i needed to match a string like the following: XXX But both "1." and "XXX" is highlighted , and i'm currently using the following regex: QRegExp ("^\s+(\d+\.)?\s+\b[A-Z]{2,}\b") How can i highlight only XXX in this case ? Many thanks !
Your regex should be something like: QRegExp ("^\s+(\d+\.)?\s+(\b[A-Z]{2,}\b)") so you can capture XXX in your regex. Then, you retrieve all matches using capturedTexts(). The string you're after should be the last index since the first item is the entire string that matches, the second one would be the number and dot...
6,543,652
6,543,831
Different template syntax for finding if argument is a class or not
While reading this question , I came across @Johannes's answer. template<typename> struct void_ { typedef void type; }; template<typename T, typename = void> // Line 1 struct is_class { static bool const value = false; }; template<typename T> struct is_class<T, typename void_<int T::*>::type> { // Line 2 static bo...
Line 1: Choosing the partial specialization below if the test succeeds. Line 2: int T::* is only valid if T is a class type, as it denotes a member pointer. As such, if it is valid, void_<T>::type yields void, having this partial specialization chosen for the instantiation with a value of true. If T is not of class typ...
6,543,653
6,543,760
Why do you have to link libraries AND set include directories
Hey so i'm a little confused on why, in msVS++ 2010 you have to have include directories when all the headers and cpp files are inside the static libray or static library project in my case. I made the static library project with cmake, and the source file i was told to set it to is the same i'm now told to make the i...
Because VS++ while abstracting the underlying implementation does not hide it completely. Include directories and libraries are targeted at different phase of the process, which are traditionally handled by different programs. Include directories by the preprocessor, libraries by the linker. Those programs are now ca...
6,543,791
6,544,556
Can you use C++ libraries in a Cocoa (Obj-C) project?
I'm considering learning Objective-C and Cocoa, mostly in order to use Apple's tools and GUIs. However, I'd also like to do some graphics programming; OpenFrameworks and Cinder are two libraries which catch my eye, but then we're in C++ land. I come from a Java/Swing/Processing background... don't know much about the...
In short, C++ is just fine for OS X and iOS programs, and plays with Objective-C quite nicely. In more detail: However, I'd also like to do some graphics programming; OpenFrameworks and Cinder are two libraries which catch my eye, but then we're in C++ land. I won't speak for those libraries directly. To answer your ...
6,544,020
6,544,068
same number is displayed for a single output but the output is as expected when there is more than 1 output
This is a small program: #include <iostream> #include <cstdlib> using namespace std; int main() { long x = rand(); cout << x << endl; } It always displays 41.But if i modify the program like , #include <iostream> #include <cstdlib> using namespace std; int main() { for( int i = 0 ; i <= 9 ; i++ ) { ...
The random number generator built in compilers are usually pseudo random number generator. They typically use a recursive equation to generate next random number and use a seed to generate first random number. Check this link. To avoid having same random number as the first one, you need to change the seed. Again, same...
6,544,038
6,544,066
Problem in erasing element in list
struct ScheduleTaskInfo { unsigned int nTaskID; __time64_t timeStartTime; __time64_t timeEndTime; }; typedef list<ScheduleTaskInfo> SchedulerList; SchedulerList::iterator itrSchedulerList; for(itrSchedulerList = gSchedulerList.begin();itrSchedulerList != gSchedulerList.end();itrSchedulerList++) { SYSTE...
You should write itrSchedulerList++ in else-block as: for(itrSchedulerList = gSchedulerList.begin(); itrSchedulerList !=gSchedulerList.end();) { SYSTEMTIME st; GetLocalTime(&st); CTime ctSyatemTime(st); if (itrSchedulerList->timeEndTime == ctSyatemTime.GetTime()) { it...
6,544,139
6,544,209
Logical AND + assignment in c++, safe?
I just learned this great pattern (from javascript actually) and I would like to apply it to my c++ code. To explain the pattern, let's say I am representing a string as a linked list of these: struct link_char; struct link_char { link_char * next; char code; }; Note that the last character of any link_char stri...
Yes. Built-in logical AND (&&), logical OR (||) and the comma operator (,) are the only cases in which for a binary operator C++ guarantees that evaluation will compute left expression and then (if not short circuited) right expression (comma operator of course always evaluates both operands, first left and then right)...
6,544,246
6,544,552
C++ thread termination with waiting window
So, the code goes somehow like this: MAIN(){ /*waiting window class declaration*/ threadinfo* oThread=new threadinfo(); //An object that will help me know when to finish the thread QueueUserWorkItem((LPTHREAD_START_ROUTINE)waitingWindow, (void*)mThread, WT_EXECUTELONGFUNCTION); function_that_takes_time(); ...
The best way to end threads in general, is to let them "gracefully" finish up by themselves. You could tell the thread to end by setting an event, for example: HANDLE hevent_die = CreateEvent(...); HANDLE hthread_something = CreateThread(...); // or _beginthread() ... DWORD WINAPI thread_func (LPVOID param) { whil...
6,544,310
6,544,427
C++ simple cache design for function output
I assume it's a quite frequent problem with well-known solutions, which I wasn't able to find. So I'm seeking advice here. Problem Statement Consider the following setting: class A; // some class const A f(const A&); // an _expensive_ function void do_stuff() { A a; a.modify(...); do_stuff1(f(a)); // c...
I've done similar stuff with interfaces like this: class F { public: virtual int f(int a)=0; }; class Cache : public F { public: Cache(F &f) : f(f) { } int f(int a) { /*caching logic here, calls f.f() if not found from cache */ } F &f; }; class Impl : public F { int f(int a) { /* real implementation here...
6,544,361
6,555,268
Box2D static library project installation issues
Hey so i just took the following steps: Downloaded Box2d 2.1.2 and used cmake to build the msVS++ projectiles Built Box2D.sln under debug and release, but didn't touch the libs or dlls Made a new Win32 project, and copied the code from "Hello World" which was included in the Box2D download into my new projects main so...
Found the problem: didn't see the warning saying that Box2D.h was skipped because it was placed before stafx.h; so i switched the order of the includes.
6,544,443
6,579,532
How to pause FFmpeg from C++ code?
I'm writing a VisualC++ program which have code invoke ffmpeg.exe to convert video file. I wonder is it possible to pause/resume ffmpeg converting thread from C++ code? LR.
All you need to do is suspend and resume the ffmpeg child process itself. The main problem is: there is no SuspendProcess API function. And there is no documented or safe way of doing this. The only simple way of doing this is via SuspendThread/ResumeThread. See this article on codeproject about how to do it.
6,544,912
6,545,009
C++ bit manipulation
I am trying to extract character value from UTF-8 format. Suppose I have two characters, and I extract 5 bits from first character => 10111 and 6 bits from another character => 010000 so ch1 = 10111; ch2 = 010000; how would I combine them to form 10111010000 and output its hex as 0x5d0? Do I need to shift or is there...
You need to use shifting, plus the | or |= operator. unsigned int ch3 = (ch1 << 6) | ch2; // ch3 = 0000010111010000 I'm assuming here that an unsigned int is 16 bits. Your mileage may vary.
6,545,012
6,545,040
Regarding empty initialisation of static array of class types
When I ran static code analyzer QACPP, I got a warning. According to the QACPP documentation, initializing with {0} only works for built in types. To initialize an array of objects of type A, {} must be used. As below: int i[5] = {0}; // Only works with built-in types. A a[5] = {}; // OK, works with both built-in ...
Yes, it is a standard rule. An array is an aggregate. The rules of initialization are explicitly mentioned in the standard for aggregates. Does this statement: A* ap[5] = {} intialise the 5 pointers with NULL? Yes QACPP throws me a warning when I used A* ap[5] = {NULL} What warning? Maybe the warning is that you...
6,545,490
6,545,598
How can I check a function was called by another function?
I am currently trying to make sure that a member function of one class is only called by a member function of another class. The architecture is imposed and cannot be changed, the port means that some logic has to be done in a.call() before calling b.call(). a.call() therefore calls b.call() to simplify things and make...
Off the top of my head, options would be: Make b.call private and make b add a or a.call as a friend Turn b.call into a class and put the body into a a private constructor with a or a.call as a friend grep the source code for b.call, make sure the only call is in a.call, and add a comment at the declaration saying "i...
6,545,559
6,549,500
problem in rendering triangles in Opengl-es 2.0
Possible Duplicate: Problem when going from opengl 1.1 to Opengl-es 2.0 I am trying to render an isosurface by drawing triangles which takes its data from a text file and render it using opengl-es 2.0 . I was able to do it in Opengl 1.1 but because in opengl-es 2.0 some functions are not present so I am getting diff...
First, don't create a buffer in the drawing function (which is supposed to run often), but in some initialization code (e.g. after loading the data from file), as I suppose it won't change after loaded from the file (and if yes, then just update the buffer data). Second, don't make a buffer for every triangle, but a si...
6,545,879
6,547,648
CMake dependency on defined (preprocessor) header file
I have a configuration file setup that defines the correct header files to include for certain components. Later I include that file via the preprocessor token. Unfortunately CMake's dependency scanner completely ignores the header file. Essentially it comes down to this: #define HEADER_FILE "somefile.h" #include HEADE...
You can add an explicit dependency to a source file by setting the OBJECT_DEPENDS property: set_property(SOURCE source.cpp APPEND PROPERTY OBJECT_DEPENDS "somefile.h") You'll have to do this for any source file that includes your configuration file.
6,546,284
6,546,385
Selectively populated vectors with substrings extracted from a source string
I have a char array, in which its contents look something like the following: char buffer[] = "I1 I2 V1 V2 I3 V3 I4 DO V4"; As you may see, it's a typical blank separated character string. I want to put all sub-string(s) starting with a letter "I" into a vector (IVector), and sort its elements in ascending order. At t...
You can iterate over all the substrings using an std::istream_iterator<std::string>: std::stringstream s(buffer); std::istream_iterator<std::string> begin(s); std::istream_iterator<std::string> end; for( ; begin != end; ++begin) { switch((*begin)[0]) { // switch on first character // insert into appropriat...
6,546,309
6,546,428
a small issue in using exception handling in c++
The below given simple exception program is giving Unhandled Exception "Microsoft C++ exception: int at memory location 0x0012fe94..". I am getting this error immediately after the function excep() is returned. Please can anyone tell why this error is coming here. Also it will be helpful if all the possible mistakes in...
In the line throw excep(20); excep(20) is called first, whose return value is then thrown, i.e. you throw an integer. It is roughly equivalent to: const int i = excep(20); throw i; To get you an idea how exception-snytax looks: #include <iostream> #include <stdexcept> using namespace std; int main () { try { ...
6,546,412
6,546,477
Why is 'this' not volatile?
Having spent the last few days debugging a multi-threading where one thread was deleting an object still in use by another I realised that the issue would have been far easier and quicker to diagnose if I could have made 'this' volatile. It would have changed the crash dump on the system (Symbian OS) to something far m...
this is not a variable, but a constant. You can change the object referenced by this, but you can't change the value of this. Because constants never change, there is no need to mark them as volatile.
6,546,470
6,547,589
Uniform initialization of references
I am currently trying to understand the new uniform initialization of C++0x. Unfortunately, I stumpled over using uniform initialization of references. Example: int main() { int a; int &ref{a}; } This example works fine: % LANG=C g++ uniform_init_of_ref.cpp -std=c++0x -o uni -Wall -Wextra uniform_init_of_ref.cpp...
According to N2672 the paragraph 8.5.4.4 should say: Otherwise, if T is a reference type, an rvalue temporary of the type referenced by T is list-initialized, and the reference is bound to that temporary. [ Note: As usual, the binding will fail and the program is ill-formed if the reference type is an lvalue reference...
6,547,041
6,547,070
Why am I getting a g++ error about discarding qualifiers in my code when compiling?
Just a little warning: I've only been doing C++ for 2 weeks now, expect to see stupid beginner errors. I was writing some (useless) code to get familiar with classes in C++ (it's a wrapper around a string), and I added a copy constructor, but I keep on getting this error: pelsen@remus:~/Dropbox/Code/C++/class-explorati...
You need to make getData a const-method: const string CValue::getData() const { return *value; } Also, as your class looks now, it is not necessary to make value a pointer. Just make it a member-object.
6,547,056
6,547,099
Template parameter deduction with function pointers and references
Possible Duplicate: Why are qualifiers of template arguments stripped when deducing the type? Consider the following C++ code: void f(int&); template <typename T> void tpl(void (*)(T), T); void bar(int& x) { tpl(&f, x); } Compilation using GCC 4.6.0 fails with the following error message: fntpl.cpp: In fu...
Because these are fundamentally different void f(int&); and void (*)(T) the compiler has only deduced that T is int, so it looks for: void f(int); which is nothing like your intention, change the function pointer to this: template <typename T> void tpl(void (*)(T&), T); And the compiler will be happy...
6,547,131
6,562,600
Qt window resize problem
I am having a problem redrawing a QWidget window after its size has been adjusted. I have tried update(), repaint(), adjustSize(), but all seem to suffer from the same thing: only part of the window is redrawn, resulting in the window frame on the bottom and right sides to not show. The window is also not resized entir...
We use a mix of designer and code to create layouts, the Qt layout system can be very unintuitive at times. But I would probably not layout a full series of tabs in one designer ui file, i would make each tab each own widget and then assemble them either through code or in the designer by promoting to custom classes. T...
6,547,323
6,547,393
Virtual function acting weird in inheritance?
Lemme explain my problem by giving an example: #include <iostream> class PC { public: PC():Data(0) { } virtual void display() { std::cout<<"The data is :"<<Data<<std::endl; } protected: int Data; }; class SmartPC:private PC { public: SmartPC():PC() { } void convert(...
According to scott meyers : static_cast<PC*>(this); will create temp base copy of SmartPC. but temp->display(); executed the display() function of derived class why is it so? it should execute function of base's display() , since the object is now completely a copy of base of SmartPC. No copy is created, you are only...
6,547,461
6,547,553
std::basic_string specialization
I need to override only length function from std::basic_string because it's not correct for a custom char type on a specific platform. This is current declaration for, let's say, CustomString typedef STL::basic_string<CustomChar, STL::char_traits<CustomChar>, STL::allocator<CustomChar> > CustomString; I need to have a...
You need to specialise the std::char_traits structure and override its static size_t length(const char_type* s); function to do that. Then you don’t even need to specify all the template parameters when instantiating a basic_string. The following definition should be enough: typedef std::basic_string<CustomChar> Custom...
6,547,464
6,547,786
Is an empty function called at all in optimised code?
If the TEST macro is not defined, I would like to know whether there is a performance difference in these two pieces of code: void Func1(int a) { // ... } #ifdef TEST Func1(123); #endif and: void Func2(int a) { #ifdef TEST // ... #endif } Func2(123); With TEST not defined, Func2 would become an empty functio...
It pretty much comes down to whether that particular call to Func2 is inlined or not. If it is, then an optimizing compiler ought to be able to make an inlined call to an empty function the same as not calling it at all. If it isn't inlined, then it's called and returns immediately. As long as the function definition i...
6,547,602
6,547,615
Expression must have class type
I have't coded in c++ for some time and I got stuck when I tried to compile this simple snippet: class A { public: void f() {} }; int main() { { A a; a.f(); // works fine } { A *a = new A(); a.f(); // this doesn't } }
It's a pointer, so instead try: a->f(); Basically the operator . (used to access an object's fields and methods) is used on objects and references, so: A a; a.f(); A& ref = a; ref.f(); If you have a pointer type, you have to dereference it first to obtain a reference: A* ptr = new A(); (*ptr).f(); ptr->f(); The a->b...
6,547,664
6,547,692
A question about for_each in vector of c++
I have a question about the for_each in vector, the code is following: #include <iostream> #include <algorithm> #include <vector> using namespace std; struct myclass { void operator() (int i) {cout << " " << i;} } myobject; int main () { vector<int> myvector(3,4); cout << "\nmyvector contains:"; for_each (m...
This is a functor. std::for_each is a function template that basically expands to this: for (iter = myvector.begin(); iter != myvector.end(); ++iter) { myobject(*iter); } So myobject can either be a function pointer, or it can be an object with an overload for operator().
6,547,922
6,548,074
What are differences between std::string and std::vector<char>?
So what are main differences and which of them will be used in which cases?
vector<char> gives you a guarantee that &v[0]+n == &v[n] whereas a string doesn't (practically, it is the case, but there is no guarantee)... AFAIK C++0x gives that guarantee already there is no implicit conversion from const char* to vector<char> string is not an STL container. For example, it has no pop_back() or ba...
6,547,976
6,547,992
Retrieve Windows Events programmatically from a remote computer - Windows XP
I need to retrieve Windows Event Logs programmatically from a remote XP system. Any links/resources related to this would be really helpful. Thanks in advance!
You should be able to get event the event log/build a watcher using Windows Management Instrumentation (WMI). Here's an article on building a "watcher". http://www.siccolo.com/Articles/CodeProject/LogWatcher_RSS_feed/build_log_watcher_rss_feed_using_WMI.html There are a few caveats to using WMI remotely, but as long a...
6,548,017
6,548,099
Editing A Pipe Delimited File With C++?
I am using Visual Studio 6 and want to read a pipe delimited file, edit some fields and save the file. What would be the best approach for this? Could ADO help me for example? Or maybe Boost? Although I have looked into the Boost string stuff and it doesn't support VC6. Can STL help? Sorry to ask but I don't want to wa...
If the file is purely |-delimited then you can use overloads of getline that allow you to specify a different delimiter. Just read the input "line by line" - each line will be the data up to the next | character - modify the field using string or stringstream and then output it, not forgetting to include a '|' delimit...
6,548,075
6,548,110
Can we declare a function with the same signature but different return type in the base class?
the question may look silly ,but i want to ask.. Is there any way we can declare a method in a class with same signature but different return type (like int fun(int) and float fun(int) ) and during the object creation can we dynamically decide which function to be executed! i have got the compilation error...i...
You can always take the return value as a template. template<typename T> T fun(int); template<> float fun<float>(int); template<> int fun<int>(int); Can you decide dynamically at run-time which to call? No.
6,548,158
6,548,196
Available Memory Size in Visual Studio C++
I am developing a "pyramid" game that uses a Minimax tree that searches for the "best" move .. but my game is freezing. My deduction is that it's a memory problem but I am using only 124kb of memory. How much memory can I allocate with the new operator? Or, what is the memory limit assigned to my application by default...
The OS does decide how much memory you'll be able to allocate at each given time, making your question impossible to answer. I would be you, I would show the faulty code instead of thinking it's the compiler or the environnement that does something wrong. 124kb is nothing on most platforms. If it's not throwing a bad_a...
6,548,319
13,702,865
C++ std::basic_string/char_traits specialization
This is related to: std::basic_string specialization and Circumventing template specialization I tried the solution from std::basic_string specialization, but the problem is that CustomChar is a typedef for wchar_t and I have redefinition(conflict with specialization from std). How may I avoid usage of chart_traits wh...
This is the answer provided by Charles Bailey as a comment: You can supply an alternative traits class (i.e. something other than a std::char_traits specialization) while still using wchar_t as the charT template parameter to std::basic_string
6,548,486
6,548,551
Most important const & rvalue refs
In C++03 you can use the const& trick (or "most important const") to extend the lifetime of a temporary to the lifetime of the reference. My question is, in C++0x, does this behaviour extend to rvalue references? I.e auto&& x = someFunction();
According to [class.temporary], if that compiles then yes, the lifetime of the temporary is extended.
6,548,548
6,548,565
why is abort method called?
In the following program abort method is called even when I have got the applicable catch statement. What is the reason? #include <iostream> #include <string> using namespace std; int main() { try { cout << "inside try\n"; throw "Text"; } catch (string x) { cout << "in catch" << x ...
Quite simple really! You threw char const*, but do not have a matching catch for it. Did you mean throw std::string("...");?
6,548,753
6,548,854
Is it possible to embed nginx in a C/C++ application
The application runs in Linux, Windows, Macintosh. Also, if yes, how much effort is required?
Does nginx run on windows? I think you'd have a much better result using an existing library that includes a good http server. My first choice would be libevent.
6,549,087
6,549,179
Qt and dynamic library sample code
i wanted to create a software which conforms to the following structure: A GUI window , and many Qt dynamic libraries , which exports function interface. So two things to clear out , how to make a plugin for Qt apps , and how to load them , load the exported function by them. Many thanks !
How to Create Qt Plugins
6,549,532
6,549,704
Calculating mathematical constant e using while loop
I am currently doing a task in a book which asks me to calculate the mathematical constant e using the while loop. I managed that fairly easily, however I am having troubles calculating e^x, whereas the user inputs x and the degree of accuracy. The code I used for computing e is: #include <iostream> #include <iomanip> ...
This line: exponent *= exponent; is wrong. It should be: exponent *= temp;
6,549,791
6,550,013
Boost Spirit: Error C2664, Cannot convert 'const boost::phoenix::actor<Eval>' to 'char'
I'm new to Boost Spirit and trying to write JSON parser using Boost Spirit 2.4.2 (Boost 1.46.1). For the code below, I get the error when trying to execute semantic action/attribute: Error 1 error C2664: 'void (char)' : cannot convert parameter 1 from 'const boost::phoenix::actor<Eval>' to 'char' I saw some questi...
More update: Kostya has a good point and 'half' touches base: boost::bind actually is fine, just use different placeholders : [ boost::bind(&print_char, ::_1) ] [ phoenix::bind(&print_char, qi::_1) ] [ print_char ] All three should work, but not mixed :)
6,549,795
6,549,936
Why is an assignment to a base class valid, but an assignment to a derived class a compilation error?
This was an interview question. Consider the following: struct A {}; struct B : A {}; A a; B b; a = b; b = a; Why does b = a; throw an error, while a = b; is perfectly fine?
Because the implicitly declared copy assignment operator of B hides the implicitly declared copy assignment operator of A. So for the line b = a, only the the operator= of B is a candidate. But its parameter has type B const&, which cannot be initialized by an A argument (you would need a downcast). So you get an erro...
6,550,083
6,555,050
How to determine if a class contains a subclass / type?
Can we have a SFINAE trick to know, if the class has certain subclass/type. Something like, template<typename TYPE> // searches for "my_type" struct has_inner_type { enum { value = <???> }; }; Following are the examples: struct A { class my_type {}; // has_inner_type::value = true }; struct B { }; // has_inner_t...
Following is the answer which was present in the wikipedia link I posted in the question !! (thanks to @n.m.) template <typename T> struct has_inner_type { typedef char yes[1]; typedef char no[2]; template <typename C> static yes& test(typename C::my_type*); template <typename> static no& test(...); static...
6,550,509
6,550,724
Amortized analysis of std::vector insertion
How do we do the analysis of insertion at the back (push_back) in a std::vector? It's amortized time is O(1) per insertion. In particular in a video in channel9 by Stephan T Lavavej and in this ( 17:42 onwards ) he says that for optimal performance Microsoft's implementation of this method increases capacity of the vec...
Assuming you mean push_back and not insertion, I believe that the important part is the multiply by some constant (as opposed to grabbing N more elements each time) and as long as you do this you'll get amortized constant time. Changing the factor changes the average case and worst case performance. Concretely: If you...