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
4,871,906
4,871,959
writing testcases for classes in my c++ program running on linux
I am a beginner for writing test-cases so i don't know about test-cases, can you briefly explain about test-cases and also, how can i write test-cases for my c++ program(classes,member functions,member variables,....) help me in writing those and compiling and running it. Advance in thanks
First of all: First find your self a framework of your liking: wikipedia list of frameworks here Install and read its documentation Identify the invariants, valid and invalid input of your methods and write tests that makes sure that they are enforced. My recommendation is to write tests that test in a black box way. ...
4,871,954
4,872,351
Virtual Functions and Performance C++
Before you cringe at the duplicate title, the other question wasn't suited to what I ask here (IMO). So. I am really wanting to use virtual functions in my application to make things a hundred times easier (isn't that what OOP is all about ;)). But I read somewhere they came at a performance cost, seeing nothing but th...
Extending Charles' answer. The problem here is that your loop is doing more than just testing the virtual call itself (the memory allocation probably dwarfs the virtual call overhead anyway), so his suggestion is to change the code so that only the virtual call is tested. Here the benchmark function is template, becaus...
4,872,105
4,872,130
Problem with reading conversion characters in c++
I have already some code: std::string str2("Hello\r\n"); if (str2.find ("\r\n") != std::string::npos) Console::WriteLine("Enter!\n"); On console screen: Enter! All good, but if we create str2 from xml.GetData() which return string std::string str2(xml.GetData()); if (str2.find ("\r\n") != std::string::npos) Con...
It depends on how your xml data is treating end-of-line. It might just be \n. Try searching for just that instead of \r\n. EDIT: Doesn't GetData() return the data associated with the current node? Unless your outside of an actual element/attribute, this might never give a new-line.
4,872,239
4,872,408
shared_ptr and the this-pointer
OK, I started using shared-pointers and pass shared-pointers as much as possible. No conversion to raw pointers anymore. This works good, except in this specific case: Suppose we have a class that also is an observer on another class, like this: class MyClass : public IObserver { public: MyClass (std::sha...
What you need is probably the enable_shared_from_this and shared_from_this facilities. The docs are here Note that you cannot use shared_from_this until the constructor has fully completed and the object is already owned by another shared_ptr. struct test : boost::enabled_shared_from_this<test> { test() { //...
4,872,299
4,872,332
Operator Overloading C++
I found this code on internet : Class Book{ Public: void operator()(int Counter) const throw(); } My question is, what operator overloading the above code used?
Firstly, that code is wrong; since C++ is case sensitive, Class and Public are not keywords. It is also very unusual (albeit legal) to capitalize the first letter of a parameter name (Counter). Assuming correct capitalization, what you have is an overload of the function-call operator. It allows you to "call" an instan...
4,872,361
4,872,554
Why are there two different getline() functions (if indeed there are)?
Every time I do a quick snippet of C++ code line std::string s; cin >> s; I curse myself because I forgot it stops at the whitespace rather than getting an entire line. Then, on remembering getline, I invariably become confused as to the two varieties: std::string s; getline (std::cin, s); and: char cs[256]; std::ci...
Bear in mind that the Standard library is composed from 3 (main) parts: IOStream, String and STL, plus some tossed in goodies and the C-headers. I don't see anything weird in having those parts loosely coupled (though I wish it was not the case). Other incongruities include: std::string::length vs std::string::size, th...
4,872,373
4,872,531
Why is including "using namespace" into a header file a bad idea in C++?
While reading from Bruce Eckel's "Thinking in C++" about namespaces, I encountered the following statement: However you'll virtually never see a using directive in a header file (at least not outside of scope). The reason is that using directive eliminate the protection of that particular namespace, and t...
Consider this program: line# 1 #include <string> 2 3 using namespace std; 4 ...
4,872,474
4,872,575
Overloaded functions are ambiguous when using SFINAE principle
I came across some code written in VS7.1 and now I'm trying to get it to work for MacOSX. The code snippet below I understand is about the SFINAE principle. From what I understand, the code is used to at compile-time know what type something is by relying on some template instantiation magic. In short, the right overlo...
Unless i'm misunderstanding the intent, the above usage sample doesn't require use of SFINAE. If you only want to statically assert the type of Type you can just use something like this: template<class T1, class T2> struct SameType { static const bool Value = false; }; template<class T> struct SameType<T, T> { ...
4,872,566
4,872,612
cppcheck thinks I have "Redundant code: Found a statement that begins with numeric constant"
Cppcheck (version 1.46.1) gives the following warning for an enum like this one: enum DATABASE_TYPE { DATABASE_TYPE_UNKNOWN = -1, // <- line of warning DATABASE_TYPE_ORACLE, DATABASE_TYPE_MSACCESS }; Redundant code: Found a statement that begins with numeric constant I don't think, that it's redundant....
My guess is, either: A) invalid somehow is declared or defined elsewhere. B) the enum is defined in a header included twice (without header guards). Because you get the same error for this code: enum SomeEnumType { invalid = -1, first, second, }; enum SomeEnumType { invalid = -1, // <- line of warning ...
4,872,615
4,872,650
Passing type information to function in lieu of virtual template function C++
I have a base class which implements the following: struct Consumer { template <typename T> void callback(T msg) { /*null implementation */ } }; I then have a class implement this: struct Client : public Consumer { void callback(Msg1 msg); void callback(Msg2 msg); void callback(Msg3 msg); }; Th...
If you really don't want to use virtual functions (this seems to be a perfect use case for them actually, but I don't know about your message classes), you can use the CRTP: template <typename U> struct Consumer { template <typename T> void callback(T msg) { static_cast<U*>(this)->callback(msg); } }; stru...
4,872,626
4,873,029
How to leave the world of OBJ-C as early as possible and enter an existing C++ codebase in an iOS OpenGL ES app?
I'm looking to write an iPhone app which utilises an existing OpenGL (which will be ported to ES) code base. I can't spend too much time invested in learning OBJ-C, so if I can limit its usage to the bare essentials (Input/OS stuff etc...) that would be great. I know how to wrap the C++ code in opaque pointers to get t...
You can write C++ code or Obj-C++ (a mixture of the two languages) code at any time during your project's development. In order to get Xcode to compile the C++ correctly, you need to set the build settings in the info for your target(s) (or project). If you right click on a target and go to "info", or double click on t...
4,872,769
4,872,834
System notification area balloon by C++?
Is there simple code to show balloon notification for C++? I'm using Visual Studio 2010.
Check here and here. In general Google rules if you know the right words (system tray is not called "tray" -- it's "system notification area")
4,872,803
4,872,878
deleting memory allocated in static function in C++
I have C++ class as follows class anotherClass; class myClass { private: myClass() {} ~myClass() {} typedef std::map<string, anotherClass* > stringToClass; static stringToClass s_stringToClass; public: static anotherClass* getStringToclass(string name); }; in above class for get...
If you store it in a static variable, I guess you need them till the end of the execution of your process... If not, then you need to add a method to clean this static variable by deleting each element and call it when you don't need it anymore. You should not do it in the destructor as the static variable is not linke...
4,872,809
4,872,816
In C++ what does template<> mean?
It's not a syntax I'm familiar with, but I saw it in another question, an example being: template<> struct Allowed<std::string> { }; What does template<> actually mean, with no template type/parameter?
It's a specialization. template<> means that the specialization itself is not templated- i.e., it is an explicit specialization, not a partial specialization.
4,872,846
4,873,489
Porting cocos2d to Qt
Does any one know how porting is done. Actually I want to port cocos2d to Qt platform & I have no idea about this. If anyone know please help me.
What you want to look at is not Cocos2D itself (which is pure python and will require a platform for which Python is available, including OpenGL / SDL functionality), but rather Cocos2D-X. That provides a cross-platform C++ API closely mapped to Cocos2D's python interfaces. See: http://www.cocos2d-x.org/projects/cocos2...
4,873,044
4,873,208
How to minimize compilation time in C++
I've coded an script that generates a header file with constants like version, svn tag, build number. Then, I have a class that creates a string with this information. My problem is the following: As the file is created in every compilation, the compiler detects that the header has changed, and forces the recompilation...
In the header write something like: extern const char *VERSION; extern const char *TAG; extern const char *BUILD_DATE; and create a .c (or .cpp) file that will contain const char *VERSION = "0.13"; const char *TAG = "v_0_13"; const char *BUILD_DATE = "2011-02-02 11:19 UTC+0100"; If your script updates the .c file, on...
4,873,092
4,873,202
Zombie process and fork
i have a code like this... c = fork(); if(c==0) { close(fd[READ]); if (dup2(fd[WRITE],STDOUT_FILENO) != -1) execlp("ssh", "ssh", host, "ls" , NULL); _exit(1); } close(fd[WRITE]); fd[READ] and fd[WRITE] are pipe file descriptors. when i run it continuously, there are a lot of zombie processes...
If you have no intention to wait for your child processes, set the SIGCHLD handler to SIG_IGN to have the kernel automatically reap your children, eg. signal(SIGCHLD, SIG_IGN);
4,873,104
4,873,191
deleting memory for static variable in C++
Possible Duplicate: deleting memory allocated in static function in C++ Hi All, I have C++ class as follows interface myInterface; class anotherClass : public myInterface {}; class myClass { private: myClass() {} ~myClass() {} typedef std::map<string, myInterface* > stringToClass; static s...
Note: You should reformat on the old thread, instead of creating new question. Anyway, I paste my answer here. I think in your case, the destructor won't help, because there is no any object of MyClass. I propose three ways 1. Don't store pointer, store the object itself. 2. Put the delete function into atexit; In yo...
4,873,347
4,876,456
Receive compressed data using Boost::asio
I have a client that sends me data using this function: void CServerRetrieve::Send(char *buf, DWORD size, int flags) { unsigned char *zlib; unsigned long szzlib; m_zlib.Deflate((unsigned char*)buf, size + 1, &zlib, &szzlib); // include the terminating 0 char char zbuf[5]; zbuf[0] = 'Z'; memcpy(&...
The fact that you are receiving compressed data really does not matter to Boost.Asio. Assuming you you know the size of the data you are about to receive, a std::vector<char> is fine for receiving the compressed data. You'll need to resize it prior to invoking async_receive Just make sure this buffer does not go out of...
4,873,446
4,873,514
Using binary data in C++ string
I am working with binary data coming from a service provider. I am subscribing to this data through HTTP request, using C++. Every now and then, I get an HTML payload coming from this provider. The HTML payload is actually binary data, which looks like that: ! ¦ô¿Âˤ ÍÌL? Àÿ Àÿ¥ š™©@ Àÿ Àÿ or ! H·ô¿Âˤ ÍÌL? Àÿ333?...
You can write your payload in a file and read it using a std::ifstream. That would allow you to change the payload without having to recompile. If you really want to store it as binary data, you can use an array of char, and initialize it like that : const unsigned char raw_data[] = { 0x21, 0x20, 0xc2, 0xa6, 0xc3, ...
4,873,475
4,873,602
Can you use sequential #if blocks in an autoexp.dat preview?
I have a quadratic equation struct, and I'd like to make it look nicer in the visual studio 2008 debugger. Here's the struct: struct QuadraticEquation { float squareCoefficent; float linearCoefficent; float yIntersection; } I'd like it to appear as a properly formatted equation in the debugger: 3.0x^2 - 1.3x + 6....
I think you have to use nested #if's to achieve something like this. Check how std::complex<*> is done in the default autoexp.dat. This will take a lot of typing to cover all possible combinations. Do you really need that? Maybe displaying it simply as a struct is good enough for practical purposes.
4,873,493
4,873,581
How can I convert number of seconds since 1970 to DateTime in c++?
How can I convert number of seconds since 1970 to DateTime in c++? I am getting the time in the below format: 1296575549:573352 The left part of the colon is in seconds and the right part in micro seconds. Please help. Thanks, Syd
Try and use gmtime() (see http://www.cplusplus.com/reference/clibrary/ctime/gmtime/) or localtime() to convert a time_t to a struct tm
4,873,565
4,873,960
How big is wchar_t with GCC?
GCC supports -fshort-wchar that switches wchar_t from 4, to two bytes. What is the best way to detect the size of wchar_t at compile time, so I can map it correctly to the appropriate utf-16 or utf-32 type? At least, until c++0x is released and gives us stable utf16_t and utf_32_t typedefs. #if ?what_goes_here? typed...
You can use the macros __WCHAR_MAX__ __WCHAR_TYPE__ They are defined by gcc. You can check their value with echo "" | gcc -E - -dM As the value of __WCHAR_TYPE__ can vary from int to short unsigned int or long int, the best for your test is IMHO to check if __WCHAR_MAX__ is above 2^16. #if __WCHAR_MAX__ > 0x10000 ty...
4,873,589
4,873,624
Problem declaring Global Variable in C++
I have a global variable in the class: IloModel model; that is going to be shared amongst several functions of the class. In one of the functions, I am going to initialize this model like: model(env); I get the error: Error 1 error C2064: term does not evaluate to a function taking 1 arguments This ...
when you do IloModel model; It is being initialised with the default constructor; so IloModel() What you need to do is model = IloModel(env); There error is probably because it is looking for a function model with one paramatere and not finding one.
4,873,971
4,875,072
Visual Studio 2008 class view missing classes
I've just ported a large project from an older version of Visual C++ to VS2008 and notice that the class view is mising a bunch of my classes. Looking at the solution view, the header files declaring those classes are present, so I'd expect to see them in class view. Any reason why certain classes would be excluded, ...
Tried Hans' suggestion of looking what was different about a header file with a missing class, and noticed the following myheader.h #ifndef MYHEADER_INCLUDED #define MYHEADER_INCLUDED class MyClass { ' ' }; #endif Now everything after the #ifdef was greyed out in the editor, which suggested the IDE throught the ma...
4,874,075
4,874,297
Parsing a pair of ints with boost spirit
I have the following code: std::string test("1.1"); std::pair<int, int> d; bool r = qi::phrase_parse( test.begin(), test.end(), qi::int_ >> '.' >> qi::int_, space, d ); So I'm trying to parse the string test and place the result in the std::pair d. However it is not wor...
It should work. What people forget very often is to add a #include <boost/fusion/include/std_pair.hpp> to their list of includes. This is necessary to make std::pair a full blown Fusion citizen.
4,874,688
4,875,518
What can I do to improve my Fibonacci number generator?
I'm solving this problem: G(n) is defined as G(n) = G(n-1) + f(4n-1) , for n > 0 and G(0) = 0 f(i) is ith Fibonacci number. Given n you need to evaluate G(n) modulo 1000000007. Input First line contains number of test cases t (t<40000). Each of the next t lines contain an integer n ( 0 <= n < 2^51). Output Fo...
Sometimes such problems can be tackled with mathematical tricks, instead of brute force solutions. The large value of n and modulo, in my opinion, are indications that a clever solution exists. Of course figuring out the solution is the hard part. (I'm not sure if this is ideal in your case, I'm only pointing you an al...
4,874,896
5,129,736
How to display unsupported(formats) images in Android application?
By default, Android has the decoders to display the following images formats: jpg, png, bmp, and gif. If I want to develop an application which can display other image formats (like tiff, psd, pcx, mat, mng) which library (using c or c++ or java) should I use to achieve this?
Your question is not really about Android, but more about which language is suited for the task. Native code can perform better than Java, but since it sounds like you will be using someone else's code then the real question becomes "what is available?" You can write an Android imaging application in Java or C/C++, t...
4,875,289
4,875,462
Making swap faster, easier to use and exception-safe
I could not sleep last night and started thinking about std::swap. Here is the familiar C++98 version: template <typename T> void swap(T& a, T& b) { T c(a); a = b; b = c; } If a user-defined class Foo uses external ressources, this is inefficient. The common idiom is to provide a method void Foo::swap(Foo&...
So why not simply write a swap template that does exactly that: swap the object representations*? There's many ways in which an object, once being constructed, can break when you copy the bytes it resides in. In fact, one could come up with a seemingly endless number of cases where this would not do the right thing ...
4,875,482
4,875,550
How to turn 'const boost::filesystem2::path' into 'const char *'?
How to turn 'const boost::filesystem2::path' into 'const char *'?
Try using path::string().c_str()
4,875,511
4,875,683
C++ newbie: good resources (books) for learning about streams?
I would like to learn about streams in C++. I have done some googling and searching on Amazon and have not had any success in finding a book/web resource on this topic. Any suggestions would be much appreciated! I have found some information on sites like cplusplus and forums, but I'm still still unclear about a num...
I don't know of a book that deals with streams as its major subject. I'm sure you can find a lot of resources on the Internet, but judging their quality may be difficult. The following two books have rather good coverage of streams and might be work looking into. Of course they cover a lot more than just streams. T...
4,875,532
4,875,805
Moving a small C++ project from XCode to Visual studio. Ceiling/floor unrecognized?
I have a small c++ project I've been working on in XCode, that I'd like to do some work with on my Windows machine, on Visual Studio. I made a new project and copied all of the source files into the new project. There are no external dependencies. Now, Visual Studio does not like any of my floor or ceil calls. I get...
It might be a collision between std::ceil and ceil (if you use an evil using namespace std). -> Remove the using namespace and add std:: in front of every occurence. It is possible that the compiler doesn't know which version of ceil to use ceil(float foo) or ceil(double foo). -> Check if the arguments of your call a...
4,875,935
4,876,072
Proper Way To Initialize Unsigned Char*
What is the proper way to initialize unsigned char*? I am currently doing this: unsigned char* tempBuffer; tempBuffer = ""; Or should I be using memset(tempBuffer, 0, sizeof(tempBuffer)); ?
The second method will leave you with a null pointer. Note that you aren't declaring any space for a buffer here, you're declaring a pointer to a buffer that must be created elsewhere. If you initialize it to "", that will make the pointer point to a static buffer with exactly one byte—the null terminator. If you wa...
4,875,989
4,876,341
template pass by const reference
I've looked over a few similar questions, but I'm still confused. I'm trying to figure out how to explicitly (not by compiler optimization etc) and C++03-compatible avoid copying of an object when passing it to a specialized template function. Here is my test code: #include <iostream> using namespace std; struct C { ...
So if you don't always want to accept a const reference (which is reasonable for base types [int, long, float etc.]), you can use a little boost magic. #include <iostream> #include <boost/call_traits.hpp> using namespace std; struct C { C() { cout << "C()" << endl; } C(const C&) { cout << "C(C)" << endl; } //C...
4,876,221
4,876,361
Assigning a value bit by bit
If I have a struct like so: struct example { uint16_t bar:1; uint16_t foo:1; }; Then I have another 16-bit variable: uint16_t value; If I want the first bit in "value" to be assigned to "example.bar", and the second bit in value to be assigned to "example.foo", how would I do that? EDIT: I tried the following: t...
try it with: struct example x; x.bar = value & 1; x.foo = value & 1 << 1; fooN = value & 1 << N;
4,876,253
4,885,680
Storing values in buffer, within class function method
I am programming a VST DSP plugin in c++. I am creating a series of band pass filters in a 'filterbank'. I have implemented a filter class in my header (including function) and built constructor/destructor correctly in .cpp. I can pass values to the method and return them also. However, the issues lays in the area of s...
After creating my new question on nested classes found here the solution has been found. The filter classes are declared within the myPlugin class. From here constructors and destructors are built as: myPlugin::aFilterL::aFilterL() myPlugin::aFilterL::~aFilterL() in the myPlugin constructor the new instances are creat...
4,876,255
4,876,295
C++ wget multi platform code
All, my app has to download http://host/file.xml, let's say. The app is a C++ application that runs on Windows and Mac. Is there a good multi platform toolkit I can use for this or any other solutions? Just like wget on Unix. Thanks
LibCurl http://curl.haxx.se/libcurl/ might do the trick.
4,876,817
4,876,831
Question about linked lists/pointers in c++
The nature of pointers being NULL in C++ seems to feel arbitrary. I'm sure there's a method to it that I'm missing, but the following makes sense to me, but doesn't seem to work. I have the following method for adding a node to a linked list: LLNode *ll; // set to NULL in constructor. void addToLL(Elem *e) { LLNo...
You probably didn't set the next pointer to NULL in the LLNode constructor. Objects of the basic types in C++ (pointer types, numeric types, etc.) have indeterminate initial values: they don't get initialized by default. You need to explicitly initialize such objects before you use them.
4,876,845
4,876,932
How to Implement a multidimensional array if the dimension is unknown at compile-time?
I want to implement a function that gets as a parameter a dimension "n" of an array of integers. This function also gets values "k_1, k_2, ..., k_n" defining the size of the array. Then this function will fill this n-dimensional array. How do I implement this efficiently with C++? For example for n = 3 I would use vec...
Use a one-dimensional array, and fake the other dimensions using multiplication of offsets for indexing, and you can pass the dimension sizes in by vector, i.e. std::vector<int> create_md_array(const std::vector<int> & dimensions) { int size = std::accumulate(dimensions.begin(), dimensions.end(), 1, std::multiplies...
4,876,913
4,876,937
template pass by value or const reference or...?
I can write a templated function this way template<class T> void f(T x) {…} or this way template<class T> void f(T const& x) {…} I guess that the second option can be more optimal as it explicitly avoids a copy, but I suspect that it can also fail for some specific types T (eg functors?). So, when should use the firs...
Is there a rule of thumb for this? The same general rules for when to use pass by reference vs. pass by value apply. If you expect T always to be a numeric type or a type that is very cheap to copy, then you can take the argument by value. If you are going to make a copy of the argument into a local variable in the ...
4,876,959
4,877,429
Ignore Spaces Using getline in C++
Hey, I'm trying to write a program that will accept new tasks from people, add it to a stack, be able to display the task, be able to save that stack to a text file, and then read the text file. The issue comes when I am trying to accept input from the user, whenever you enter a string with a space in it, the menu to c...
You have to add cin.ignore() right after options is chosen: //get the input from the user cin >> option; cin.ignore(); And cin.ignore() is not necessary after your getline: getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN //cin.ignore(); The problem is in options - if you didn't call cin.ignore() a...
4,877,228
4,936,396
GnuWin32 Make fails to run a makefile
I have a small C++ project, and I'm trying to use the GnuWin32 Make utility to build it. This is what my calc.mak file looks like: calc.exe : calc.obj stack_c.obj input_c.obj cl calc.obj stack_c.obj input_c.obj calc.obj : calc.cpp calc.h input.h stackseq.h cl -c calc.cpp stack_c.obj : stack_c.cpp stackseq.h ...
I have found the solution. The problem was that I copied the make file from a book that teaches me C++, and the author forgot to mention that "cl" is the command calling the compiler. I'm actually using g++, so after I replaced "cl" with "g++" the error was gone.
4,877,705
4,878,529
Why can't templates be within extern "C" blocks?
This is a follow-up question to an answer to Is it possible to typedef a pointer-to-extern-“C”-function type within a template? This code fails to compile with g++, Visual C/C++, and Comeau C/C++ with basically the same error message: #include <cstdlib> extern "C" { static int do_stuff(int) { return 3; ...
What does it mean that a template "may" have linkage? What is template linkage? All names either have external linkage, internal linkage, or have no linkage (C++03 §3.5p2), but this is not the same linkage as language linkage. (Confusing, I know. C++0x changes things around considerably with linkage, too.) External...
4,877,744
4,877,774
Accessing char pointer in structure
typedef struct fred { char mytype[41]; char* myremark; } fred_t; With an instance of that structure fred_t* mystruct; I can print mytype fprintf (stdout, "%s\n", mystruct->mytype); but I am failing to get the syntax to print myremark in a similar way. (It's old code that I'm modifying.)
If the instance has been correctly initialized (i.e. the myremark points to a valid string), you can print it in the exact same manner. By the way, to print a string to stdout you can simply use puts: puts(mystruct->mytype); puts(mystruct->myremark);
4,877,929
4,877,962
How do I read an .inf file?
I'd like to be able to read through the sections and values in a .inf file. I know you can use the Profile API to read an .ini file, but am I right in understanding that an inf file is subtly different (eg, an entry may not be in an id=value format) such that the Profile API isn't suitable? What APIs are available for ...
See SetupGetIntField and the related Setup API.
4,877,990
4,878,534
Boost.Test tests on a static library
I'm using Boost.Test for unit testing. Because of several reasons, I would like to write the unit test cases on different static libraries. The problem is that when I do this, the automatic registrar doesn't work. For instance, if I have something like: // foo_tests.cpp #define BOOST_TEST_MODULE "Foo" #include <boost/t...
How to force inclusion of "unused" object definitions in a library That's your same problem and you'll have to derive a solution similar to what I did in my answer.
4,877,998
4,878,107
C++ destructor format
void arrayList<T>::erase(int theIndex) { // valid index, shift elements with higher index copy(element + theIndex + 1, element + listSize, element + theIndex); element[--listSize].~T(); // invoke destructor } The code element[--listSize].~T() looks strange. It is used to...
Explicitly calling the destructor is useful in cases where you want to properly destruct the object, but not deallocate it's memory by using delete (or delete[]) directly, such as inside some custom memory manager. It should not be used very often though.
4,878,597
4,878,689
Error in Program VC++ Win32 application?
I have developed a program for mouse event in VC++ Win32 the program is running successfully and building up with success but not showing any output can anybody tell me what is error in it or anything i missed in program hoping for quick and positive response ...
Put these lines ShowWindow(hwmd, SW_SHOW); UpdateWindow(hwmd); after HWND hwmd = CreateWindowEx(0,...
4,878,698
4,899,859
MingW c++ compile Error Win 7 x64
I'm trying to compile a simple C++ HelloWorld example on my Win 7 x64 machine with the mingw compiler. I downloaded the automated installer here: http://sourceforge.net/project/showfiles.php?group_id=2435 After setting the required paths in the system environment variables i was trying to get the compiler to work with ...
I've found the problem. The file i tried to compile was saved on my NAS-Server which requires a login to access the files. I was able to access the file via console, the compiler obviously did not. After moving the source files on my local hdd, the compiler started working.
4,878,768
4,878,842
Accessing static variable from a friend function
class Base { private: static int num; public: friend void setnum(Base obj); }; void setnum(Base obj) { obj.num=4; /* Error */ } A friend function is supposed to have access to all the private data of a class. what am i missing here? I cant seem to access the the static variable from the friend function...
You only declared the static variable num. You must to define it: class Base { private: static int num; public: friend void setvals(Base obj); }; // This must be in a .cpp int Base::num; void setvals(Base obj) { obj.num=4; } This code works. Edit: Actually you can implement the setvals() function as f...
4,878,907
4,878,955
C++ SDL header file errors
I'm following a tutorial and it said at one point it should compile, but it errored. To find out why I just used their code instead of mine and have just pasted all theirs in, however, this is picking up errors. It's in a header file, I've placed the errors below the code #ifndef _CApp_H_ #define _CApp_H_ #includ...
Is the SDL.h file in your include path? Nothing in the example jumps out at me as wrong.
4,879,045
4,879,082
Fun with uninitialized variables and compiler (GCC)
The section §3.9.1/6 from the C++ Standard says, Values of type bool are either true or false. Now consider this code, void f(bool b) { switch(b) //since b is bool, it's value can be either true or false! { case true: cout << "possible value - true"; break; case false: cout << "possible value...
I'm just curious to know why this sudden change in the behavior of uninitialized bool? Disassemble the code and see what the compiler’s doing. My guess: since the value is now only used locally, the compiler optimizes it away completely. Since the behaviour is undefined anyway, the compiler can safely just assume any...
4,879,324
4,879,568
check if a library is present
Suppose I want to include a library: #include <library.h> but I'm not sure it's installed in the system. The usual way is to use tool like autotools. Is there a simpler way in C++? For example in python you can handle it with exceptions.
autotools is the best way to detect at compile time. It's very platform-specific, but assuming you're on Linux or similar, dlopen is how you check at runtime.
4,879,331
4,879,440
Linux-x64 glibc: Why does Feb 1 come before Jan 31?
When you call mktime(), Feb 1 seems to come before Jan 31. Why is this? Am I doing something wrong or is this a bug in glibc? Here's the code: struct tm tm; time_t tt; memset(&tm, 0, sizeof(tm)); tm.tm_year = 2011; tm.tm_mon = 1; tm.tm_mday = 31; tm.tm_hour = 11; tm.tm_min = 41; tm.tm_sec = 28; tm.tm_isdst = 0; tt = ...
tm_mon is zero-based, so you attempted to set February 31st, which got normalized. Here's a link to the definition of mktime().
4,879,467
4,881,484
How to set autoreconnect option with mysql connector c++
Greetings, how can i set autoReconnect option with mysql connector c++ ? ( not with mysql c api http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html )
I am not a user of this library, so my knowledge of it is only that last 10 mins worth, so please do verify. As a general rule, the best resource of such information about usage of various specific details of a library is to take a look at its unit tests. The best thing about OSS. So if you look at MySQL Connector/C++ ...
4,879,525
4,879,543
portable code between windows and linux
I have an aplication written for linux,and i want to make it to execute under windows too. So how can i make a specific line in code to execute only if the programs runs under windows ? I know its somehting with #ifdef... Thanks
You're looking for: #if defined(_WIN32) // Your Windows specific code here #endif Edit based on comment: There is a good discussion of _WIN32 vs WIN32 here: Whats the difference between the win32 defines
4,879,665
4,879,729
Use Boost Serialization Library in VC++ 2010 Project
i've downloaded the latest version of Boost Package (1.45) and I would use only the serialization library in my VC++ 2010 project. I tried to understand how can i compile that library and use it but i don't understand... Can someone help me to compile and use the serialization library?
Unless you specifically require Boost 1.45 (or 64-bit binaries), you can get the pre-compiled boost library installers from Boostpro (the professional consulting wing of boost.org): http://www.boostpro.com/download/ If you do need to build 1.45, you will need to follow the instructions for a simple binary build: From: ...
4,880,308
4,881,869
Is it possible to save a function (pointer?) into an object?
I have searched for this, but i think i am just making myself more confused. What I am trying to do save a function pointer in an object and have it be called later in another thread. What i have been envisioning is a constructor that would take a function pointer and the parameters that will be passed to this functio...
First, you would want to typedef your function type, making it easier to reuse it and lessen the potential of mistakes. typedef void (Bar::*function_type)(int); Now you can use the typedef like this: Foo(function_type func, int func_param) : function_(func) , param_(func_param) { } Also, it's a good idea to u...
4,880,328
4,880,786
Absolute fastest (and hopefully elegant) way to return a certain char buffer given a struct type
OK first and foremost, performance is most important here so I doubt a map would work. I have a list of structs (about 16 of them) like struct A { ... }; struct B { ... }; ... each are different and each are of different sizes. I'm wondering what elegant way we might be able to do something along the lines of: char...
template<typename X> struct Buffer { static char *ptr() { // Note if no alignment is needed for your use then // just a simple "static char buf[sizeof(X)]; return buf;" // would be sufficient instead of the following. union Aligner { X x; char buf[sizeof(X...
4,880,770
4,881,340
What libraries are available for analyzing audio files for spoken keywords and/or speech to text?
I'm a super-hero in my off-time and I'm trying to build an application that analyzes audio for spoken keywords. (Think emergency/911 calls) If a keyword is "robbery", and that word is spoken within the audio provided I would like to flag that file and possibly translate it to text. What development libraries or softwa...
Wiki page here is a good starting point. Of the ones mentioned there I think CMU Sphinx is the most active one.
4,880,922
5,098,785
Can I use boost::enable_if on a member function?
I'm writing a template class, and I want to allow an additional method to exist only for a certain template type. Currently the method exists for all template types, but causes a compilation error for all other types. Complicating this is that it's an overloaded operator(). Not sure if what I want to do is actually p...
Yes, this is possible, but not with the class template parameter directly. boost::enable_if can only be used with a template parameter on the method itself. So, with a little typedef usage: template<typename T, typename BASE> class MyClass : public BASE { public: typedef Utility2<BASE> util; typename T& operato...
4,881,042
4,881,214
What kind of operations might one need to do before main()
I came across this question asking how to execute code before main() in C, mentioning there were strategies for C++. I've mostly lived in application space, so executing before main() has never occurred to me. What kind of things require this technique?
"What kind of things require this technique?" Point of fact: none. However, there are a lot of useful things you might WANT to do before main for a variety of reasons. For just one practical example, say you have an abstract factory that builds doohickies. You could make sure to build the factory instance, assign it ...
4,881,210
4,881,241
How to convert a string to a ifstream
i am trying to open a file with ifstream and i want to use a string as the path (my program makes a string path). it will compile but it stays blank. string path = NameOfTheFile; // it would be something close to "c:\file\textfile.txt" string line; ifstream myfile (path); // will compile but wont do anything. // ifstr...
string path = compute_file_path(); ifstream myfile (path.c_str()); if (!myfile) { // open failed, handle that } else for (string line; getline(myfile, line);) { use(line); }
4,881,281
4,881,349
Specialization of member class nested in a non-specialized class
template <typename T> struct A { template <typename U> struct B; template <> struct B<int> {static const int tag = 1;}; // Works fine in VS2010 }; How can I specialize B the same way, but outside of A. I tried this with no success : template <typename T> template <> struct A<T>::B<int> {static co...
To quote the C++ spec, §14.17.3.18: In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialzed, except that the declaration shall not explicitly specialize a class...
4,881,377
4,883,487
How to parse C++ source in Python?
We want to parse our huge C++ source tree to gain enough info to feed to another tool to make diagrams of class and object relations, discern the overall organization of things etc. My best try so far is a Python script that scans all .cpp and .h files, runs regex searches to try to detect class declarations, method...
I'll simply recommend Clang. It's a C++ library-based compiler designed with ease of reuse in mind. It notably means that you can use it solely for parsing and generating an Abstract Syntax Tree. It takes care of all the tedious operator overloading resolution, template instantiation and so on. Clang exports a C-based ...
4,881,412
4,881,463
Accessing a 2D array between two friend classes
My question is how to access and modify a 2D array defined in one class that is friends with another class. Below are some details on my question: In class A I declare and allocate the appropriate space for my 2D array (pointer-to-pointer) u. Class A { public: friend class B; long double **u; int fun; ...
I think you get error because A::u is not initialized ( in method A::make you initialize a local variable u, not member. You need to change void A::make() { long double **u = new long double *[nx]; // should be just u, or this->u.
4,881,810
4,882,176
Employing constructors when initializing com components
I will describe the problem as simple as i can. alright, here goes the problem; Lets suppose we have a com component class with 3 of constructors where a constructor takes at least two of parameters. As we already know we instantiate the components via QueryInterface rather calling the classes' constructors therefore i...
Instead of directly returning object instances, your QueryInterface call can return factories. For example, instead of: // implements IMyClass1 interface return new MyClass1(); You would do: // pointer to member that implements IMyClassFactory interface return &m_myClassFactory; // this could also be a static class in...
4,881,837
4,881,861
why pass by reference better?
Possible Duplicate: Is it better in C++ to pass by value or pass by constant reference? see these 2 program. bool isShorter(const string s1, const string s2); int main() { string s1 = "abc"; string s2 = "abcd"; cout << isShorter(s1,s2); } bool isShorter(const string s1, const string s2) { return s...
I suggest you read this SO Question - Is it better in C++ to pass by value or pass by constant reference?
4,881,896
4,881,927
Using a C++ class member function (cannot be static) as a C callback function
I have a C library function that expects a function pointer for callback, and I want to pass in a C++ member function. The C++ function modifies a member variable, so I can't use a static free function (as suggested in several similar posts). My attempt (shown below) fails with a compiler error. This post comes closest...
It is not possible, at least with that handler_t signature. While you can create a free function on your .cpp to wrap the member call, you need a pointer to the Foo instance: void my_wrap(int foo, void* bar) { Foo* some_foo_instance = ...; some_foo_instance->handler(foo, bar); } int main(int argc, char **argv)...
4,882,231
9,286,467
Set Build output directory in Eclipse - c++
I have a program which consists of multiple projects in eclipse (working under ubuntu and the projects being in c++), these projects consist of a main executable file, and other shared objects files and static libs. I want all these projects when built to output their files to one common binary folder, instead of thei...
Unfortunately, I have found that the C/C++ Build tab does not allow you to set the build location unless you are creating your own makefile. You've likely found that the Builder Settings tab under Project Properties>C/C++ Build is all grayed out in a default C/C++ project. This is because CDT nominates the internal bui...
4,882,400
4,882,491
How do I find permutations or combinations for byte?
A character (1 byte) can represent 255 characters but how do i actually find it?
(answering the comment) There are 256 different combinations of 8 0s and 1s. This is true because 256 = 28. Each digit that you add doubles the number of combinations.
4,882,536
4,882,592
How to write test for C++ templates?
Suppose I am writing a template library consisting of a function template template<T> void f(T); with the requirement that it works with a predefined set of classes A, B, C, and D, e.g., the following must compile: template<> void f(A); template<> void f(B); template<> void f(C); template<> void f(D); Which test fram...
Write a test case that spawns the compiler... that's how e.g. autoconf tests for existence of features.
4,882,539
4,882,551
Concatenation operator in C++?
I have an application in which I need to combine strings within a variable like so: int int_arr[4]; int_arr[1] = 123; int_arr[2] = 456; int_arr[3] = 789; int_arr[4] = 10; std::string _string = "Text " + int_arr[1] + " Text " + int_arr[2] + " Text " + int_arr[3] + " Text " + int_arr[4]; It gives me the compile error Er...
You can do this in Java since it uses the toString() method automatically on each part. If you want to do it the same way in C++, you'll have to explicitly convert those integer to strings in order for this to work. Something like: #include <iostream> #include <sstream> std::string intToStr (int i) { std::ostrings...
4,882,852
5,162,315
formula to convert Lat and Long to x & Y in an Image
HI I have a Map Image that I got from OpenstreetMap(Osmarender Image ) .My question is how to convert geographic coordinates to the co-ordinates of my picture (that is in pixels on X and Y on a picture). That is I receive geographic coordinates and it is necessary for me to draw this point on my picture. Is there any...
The Answer I was expecting can be found at Convert Lat/Longs to X/Y Co-ordinates Thanks
4,882,987
4,883,030
Planning for a file indexing program
I'm somewhat new to C++, but not programming in general. I want to write my first practice program in C++ as a file indexing program. It's seems easy enough scanning directories for names, storing that information, and filtering them depending on what I want to view. What I'm concerned about is at some point, I want t...
Isn't some kind of database the obvious answer? If you don't want to hook up to a server, you can try something like SQLite. Alternatively, if you only need to do basic lookups, you could also create your own proprietary file format. You can utilize any combination of binary and textual data in your file. It's hard to ...
4,883,027
4,883,054
C++ Naming Convention
What is the widely accepted naming convention for c++ ? (functions, classes, parameters, local variables, namespaces, etc)
I don't think there is a "widely accepted" naming convention in C++. Stroustrup's books and papers generally has the following coding style: class Shape { public: // interface to users of Shapes virtual void draw() const; virtual void rotate(int degrees); // ... protected: // common data (for implementers ...
4,883,050
4,883,081
Why is my string not being printed?
I have some code that, in its smallest complete form that exhibits the problem (being a good citizen when it comes to asking questions), basically boils down to the following: #include <string> #include <iostream> int main (void) { int x = 11; std::string s = "Value was: " + x; std::cout << "[" << s << "]" ...
"Value was: " is of type const char[12]. When you add an integer to it, you are effectively referencing an element of that array. To see the effect, change x to 3. You will have to construct an std::string explicitly. Then again, you cannot concatenate an std::string and an integer. To get around this you can write int...
4,883,238
6,271,789
Tutorial/Manual how to create Visualizer in autoexp.dat
I have some C++ datatypes for which I would like to improve the debugging experience in my team. I therefore want to create a custom visualizer in the autoexp.dat file. The [AutoExpand] section doesn't seem sufficient, so I started to look at [Visualizer]. I found this website with some explanations, but is there any c...
Appears this is already commented above but someone coming to this question would not necessarily read the comments and so might miss the great tutorial available on the boost site: https://svn.boost.org/trac/boost/wiki/DebuggerVisualizers Also http://mariusbancila.ro/blog/2007/04/06/tweaking-autoexpdat-for-custom-type...
4,883,253
4,884,261
How can I save to text g++ or gcc compiler status in C++?
I want to save to a text file the C++ compiler status. I'm using Windows. Thanks.
redirect the output to a file using the redirection operator '>'. You may want to use the STDERR stream for redirection as most of the compilers output the compilation errors on this stream, so you should try the '2>' redirection. refer the below link for more details on redirection on Windows: http://technet.microsof...
4,883,444
4,883,544
How to make the position of Widget fix?
I am creating a widget on click the button. The widget is appearing at center of the screen. I want to show that widget at a proper predefined position of the screen. And when ever I open that widget it should show at that point only. How to do this not able to understand.
Use QWidget::move() function before you show it.
4,883,515
4,883,534
In C#, what is analogous to the CHAR_BIT from C++? Fast Abs
Does C# have something analogous to C++'s CHAR_BIT? Update: Basically, I'm trying to compute abs without branching, here is the C++ version: // Compute the integer absolute value (abs) without branching int v; // we want to find the absolute value of v unsigned int r; // the result goes here int const mask...
If you consider byte in C# to be the equivalent of C++'s char then the closest equivalent of CHAR_BIT is 8. In C# a byte is guaranteed to be exactly 8 bits.
4,883,655
4,883,764
Access Specifier in C++
I read the following statements from BRUCE ECKEL'S THINKING IN C++ 1.Access specifier are part of structure and do not affect the object created from "structure Doubt:As we know the access blocks are not stored contiguously, aint it that access specifier change the way object layout in memory 2.All of the acce...
1) Access specifier are part of structure and do not affect the object created from "structure" Wrong actually, the order (in the layout) of data members within the same access specific (public, protected or private) is dictated by their order in the code, however no order is specified for data members with different...
4,884,014
4,884,159
What is wrong with this usage of std::find_if?
I get the following error when compiling the std::find_if function: error C2451: conditional expression of type 'overloaded-function' is illegal The code looks like this: typedef std::vector<boost::shared_ptr<node> >::iterator nodes_iterator; nodes_iterator node_iter = std::find_if(_request->begin(), _request->end(),...
You should use _1, not this when binding, and take a value_type as an argument of your function. If this is a class or struct member function, then bind(func, this, _1) maybe? But if it is a class member function it should probably be static because it needn't state.
4,884,044
4,975,809
Symbian C++ Development Under Mac OS X
I've been developing for Symbian S60 3rd Edition since last year using Carbide.c++ under Windows. THe problem is that I moved to Mac OS X this year(bought a Macbook Pro) and when I was going to download Carbide.c++, I saw that it's Windows-only, because of the Requirements: Microsoft Windows XP Professional Service Pa...
As of now, Mac is not officially supported if you want to develop apps for Symbian (either using QT or without QT). The problem is that all the tools needed to create the final binary run only on Windows (abld). This page on Forum Nokia makes it pretty clear: Qt for Symbian development requirements In order to dev...
4,884,064
4,895,539
can string longer than 255 bytes be used as ODBC prepared statement parameter value?
I am using the libodbc++ ODBC wrapper for C++, designed similar to JDBC. I have a prepared statement "INSERT INTO t1 (col1) VALUES (?)", where t1.col1 is defined as VARCHAR(500). When I call statement->setString(1, s), the value of s is truncated to 255. I suspect the libodbc++ library, but as I am not very familiar wi...
I don't know libodbc++, but PreparedStatements available via ODBC API can store more characters. I use it with Delphi/Kylix ODBC wrapper. Maybe there is some configuration in libodbc++ to set value length limit? I have such setting in my Delphi library. If you use PreparedStatement then you can allocate big chunk of me...
4,884,213
4,884,696
Choosing a simple, secure and lightweight network protocol
I'm building an application (both client and sever sides) that may need to send and receive data over the network. The messages will be short, and probably mostly binary. I need the connection to be secure even on public networks. I'm not looking to reinvent the wheel, so I'd love if the protocol would handle all sessi...
I think you'll first have to decide at what level you want to work. IPSEC as a protocol works at about the same level as IP; basically, you'll have to do everything yourself. HTTPS is a significantly higher-level protocol. HTTP/HTTPS is universally supported, (with a little bit of work) will work through proxies etc. H...
4,884,273
4,884,291
Why `(a-- > 0)` and `((a--) > 0)` are same?
The program is as main() { int a=1; if( a-- > 0) printf("AAAA"); else printf("BBBB"); } Its output is AAAA and if I use main() { int a=1; if( (a--) > 0) printf("AAAA"); else printf("BBBB"); } then why again the output is AAAA. () has more preference then -- .
The postfix operator -- has higher precedence than any boolean comparison operator. What do you expect exactly? a-- always evaluates to the value of a which is decremented after evaluation.
4,884,391
4,884,416
Is there any case when dynamic_cast should be used in the QueryInterface implementation?
The typical way of implementing IUnknown::QueryInterface() is the following: use a chain of if-else-if for each supported interface id and do the following: if( iid == __uuidof( IInterfaceN ) ) { *ppv = static_cast<IInterfaceN>( this ); //call Addref(), return S_OK } Now static_cast is necessary here for proper...
It would be necessary in those implementations of QueryInterface where the "supported interface ids" aren't known. E.g. if you decide to implement QueryInterface in a base class, and not override it for every derived class. A case where this would happen is the situation where you have a lot of similar types, where "si...
4,884,450
4,885,933
How initialize array and pass a pointer it to base constructor from derived?
Rewrote the question completely. Please, read it carefully Single note to not confuse you: Base constructor expects pointer to constants array. It doesn't store a pointer itself, it stores the data! I have the following code: class Base { public: Base(int*); // added this to explain why I need inheritance v...
I came into another solution: class Int3Array { int array[3]; public: Int3Array(int v1, int v2, int v3) { array[0] = v1; array[1] = v2; array[2] = v3; } int* getPtr() { return array; } }; Derived::Derived(): Base((Int3Array(1,1,1)).getPtr()) { } What do you think? I...
4,884,471
4,884,514
Problem adding reference of C++ dll in C# project
I implemented a C++ dll that compiled successfully. The project contains a header and cpp file. The cpp file includes several third party headers (Cplex mainly). Once the dll was created: I then attempted to reference the dll in visual studio and it didn't work. In the console application, I used the tlbimp.exe and I...
There are two issues here, one is that not all native dlls are also type libraries, only COM ones. the second error is more like you do not have a Visual C++ runtime available, are you building the C++ dll on the same box of trying to use it? for non COMN dlls, instead of import the type library you could use DLLImport...
4,884,494
4,885,478
Why can't we declare namespace aliases inside a class?
It looks like it's impossible to declare a namespace alias inside a class; however we can do so at function-level (tested with g++ 4.3.4) : namespace A { } class C { namespace N = A; // error: expected unqualified-id before `namespace' }; class D { void f(); }; void D::f() { namespace N = A; // OK } Any idea ...
I'm not an expert on the C++ Standard but I'll stick my neck out and have a go at answering your question. I assume the use of namespace N = A within a class declaration falls foul of the definition of how a class member should be defined. The C++ Standard defines a class member as member-specification: member-decla...
4,884,548
4,884,579
Get the last element of a std::string
I was wondering if there's an abbreviation or a more elegant way of getting the last character of a string like in: char lastChar = myString.at( myString.length() - 1 ); Something like myString.back() doesn't seem to exist. Is there an equivalent?
In C++11 and beyond, you can use the back member function: char ch = myStr.back(); In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin: char ch = *myStr.rbegin(); In both cases, be careful to make sure the string ...
4,884,713
4,885,588
Boost::ptr_list Move Element to front
currently I am trying to understand how to move an element in Boost::ptr_list to the front. I have been trying stuff like this: boost::ptr_list<myObj> mylist; boost::ptr_list<myObj> myiter; // Do something useful mylist.transfer(mylist.begin(), myiter, mylist); This version the compiler acccepts, but my program crashe...
I am assuming here you want to move the last element in the list to the front. If so here is one possible way to do it: struct myObj { myObj( int i ) : m_i(i) { } void print() const { std::cout << "i == " << m_i << std::endl; } private: int m_i; }; typedef boost::ptr_list<myObj...
4,884,854
4,884,935
Unicode string normalization in C/C++
Am wondering how to normalize strings (containing utf-8/utf-16) in C/C++. In .NET there is a function String.Normalize . I used UTF8-CPP in the past but it does not provide such a function. ICU and Qt provide string normalization but I prefer lightweight solutions. Is there any "lightweight" solution for this?
As I wrote in another question, utf8proc is a very nice, lightweight, library for basic Unicode functionality, including Unicode string normalization.
4,885,022
5,313,051
Is it possible to use HTTP byte ranges using curlpp
Is it possible to get http byte ranges when using curlpp library in c++?
request.setOpt(new curlpp::options::Range(range)); where range is the byte range. for eg. 100-200
4,885,069
4,885,507
Void type in std::tuple
Obviously, you can't have an instance of type void in a well-formed program, so something like the following declaration won't compile: std::tuple<void, double, int> tup; However, as long as we're dealing strictly with types as opposed to objects, there seems to be no issue. For example, my compiler (GCC) lets me say...
It does actually make sense that you can do typedef std::tuple<void, double, int > tuple_type; as long as you only use it as a type-list to use tuple_element on. Thus I can do tuple_element<0,tuple_type>::type * param; which will declare param as void*
4,885,091
4,885,248
C# Error Finding Method in DLLImport
I have a C++ assembly that I am importing using DLLImport. I am attempting to call its method: namespace Testing { class Test{ int Run(char* filePath, bool bEntry, double duration){//code} }; } by [DllImport(dllName, CharSet = CharSet.Auto)] public static extern int Run(string filePath, bool bEntry, double du...
The "Run" looks to be a non-static class method. Although, it's possible to call such methods from C# this is not the primary use-case. It would be way easier to consume it from .NET if you expose it via COM, or at-least as a plain C interface: extern "C" __declspec(dllexport) void* Testing_Test_Create(); extern "C" ...
4,885,194
5,351,872
PDF to Image - Magick++
I want to convert a pdf to a series of images using magick++. I currently have this code: Image * img = new Image(); img->read(Tests+"finance-02-2007-multiples.pdf[0]"); Tests is a variable which contains the folder path. The "[0]" means that I want the first page to read in an image. However, this code snippet does ...
That error is telling you that cannot find GhostScript on your computer. In order to read a PDF using Magick, you must have GhostScript installed. Magick++ has a (limited) internal support only for writing a pdf. It actually embeds an image in pdf. The reason is that GhostScript is licenced as GPL and cannot be inclu...
4,885,334
4,885,632
C++ - finding the type of a caught default exception
Say I have: try { externalLibrary::doSomething(); } catch (std::exception &e) { //yay I know what to do } catch (...) { //darn, I've no idea what happened! } There might be cases you get an exception and you don't know where it's coming from or why - in some external library with no debug info. Is there a way to fi...
Because C++ is statically typed, you must catch a known type. However, you can call an external function (or set of functions) which handle exception types unknown at the point you call them. If these handlers all have known types, you can register them to be dynamically tried. struct myStupidCustomString { myStupi...
4,885,413
4,885,470
How to Open Cmd(Command Prompt) through C program
Actually, I want to execute DOS command by a C program and want to display the output of DOS command in my C Output Window. example: use "dir C:\" which displays output to C- program
To execute a command in the same cmd.exe window where your C program is running: #include <stdlib.h> . . . system("dir C:\\"); To launch a separate windows, you need to call cmd.exe: system("cmd.exe /c dir c:\\"); (Note: I have not tested this one);