question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
5,306,913
5,306,938
c++ about operator overloading
why The assignment operator must be a non-static member function operator(), operator[], and operator-> must also be implemented as non-static member functions. for example class IntList { private: int m_anList[10]; public: int& operator[] (const int nIndex); }; int& IntList::operator[] (const int n...
All these operators (operator=, operator(), operator[], and operator->) gets invoked on an instance of the class of which you define these operators as non-static member functions! static member or non-member functions are like free functions. They don't get invoked on an instance of the class. For example, if you make...
5,307,036
5,307,051
What is difference between template <typename T> and template <class T>. For me both are generating the same result
What is difference between template <typename T> and template <class T>. For me both are generating the same result. for example template <class T> T Average(T *atArray, int nNumValues) { T tSum = 0; for (int nCount=0; nCount < nNumValues; nCount++) tSum += atArray[nCount]; tSum /= nNumValues; ...
There is no difference. typename and class are interchangeable in the declaration of a type template parameter. You do, however, have to use class (and not typename) when declaring a template template parameter: template <template <typename> class T> class C { }; // valid! template <template <typename> typename T> ...
5,307,169
5,307,215
What is the meaning of a C++ Wrapper Class?
I have a little trouble in understanding a wrapper class. It would be great if some one could help providing apt examples. What is a C++ Wrapper Class and what are the circumstances of writing it ? What is it's use any way ? Thanks.
A "wrapper class" is a de facto term meaning a class that "wraps around" a resource; i.e, that manages the resource. When people write a wrapper, then, they are doing something like this: class int_ptr_wrapper { public: int_ptr_wrapper(int value = 0) : mInt(new int(value)) {} // note! needs copy-constr...
5,307,627
5,315,975
Test Driven Development with C++
Looking to start doing TDD in C++. I've seen CPPUnit, but I was wondering if there are other options that people prefer? Thanks for your suggestions!
I can recommend Google Mock, which has become part of Google Test bundled. We switched from UnitTest++ to Google Test/Google Mock a couple of years ago and have never looked back. Google Mock can be used even if you don't want to use the mocking facilities. Its matchers are very useful.
5,307,688
5,308,301
Is there a way of structuring precompiled headers in VS that doesn't make my code awkward to build in GCC?
In the past I've used precompiled headers in VC to speed up compile times but usually only in smaller projects that are basically just a small directory of source code. Since VC++ requires that all files include the same header exactly regardless of path (say "foo.h" and not "../foo.h") things get hairy when you have d...
Is it possible to update project include path, so there is no need to create separate header. We used header file Common/Common.h to create precompiled header in all projects. If the problem is compilation time, different approaches may address it: we removed precompiled headers from the project, as distributed compila...
5,307,753
5,307,781
Can't Find any online documentation for MySQL c++ connector API
I started working on mysql c++ connector API. But I can't find any online documentation for the API , I can only find example. Is there any link (or hidden way using doxygen) to generate documentation ?
I think http://dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html Would be most suitable for this.
5,307,807
5,307,820
Do quotes in library include path in C++ mean base directory of the project?
Do quotes in library include path in C++ mean base directory? #include "header.h" I would think it would be in the project folder, but I am wrong.
#include <foo.h> means that it will look for the file anywhere in the include path. #include "foo.h" means to look relative to the directory of the file that the #include statement is written in, and fallback on the include path if it cannot be found locally.
5,307,848
5,321,154
Get the file causing linker error in g++
I am building a binary which uses multiple components which are compiled as .so files. I am getting a flurry of linker errors which point to which .so file caused them, but can I get information about which files are calling undefined functions or if possible source code locations where undefined functions are being ca...
You are asking "which object file inside a shared library is causing the error". The problem is that by the time that shared library has been linked, all object files have been "fused together", and no longer exist inside the shared library as separate entities, so your question is somewhat meaningless. That said, if y...
5,307,999
5,310,322
SHMultiFileProperties with c++
Seen an example of using SHMultiFileProperties on the site with c# but I'm really having trouble using it with unmanaged c++. I am a beginner so i would appreciate any help or maybe a small example.
Although it is commented out, you might take a look at shareaza/CtrlLibraryFileView.cpp.
5,308,112
5,308,138
What number is e+000?
I have a data file full of numbers I'm loading into a vector of floats. However, the numbers in the data file are of the form -4.60517025e+000 but are being read in like -4.60517 What number should -4.60517025e+000 be?
The number -4.60517025e+000 is interpreted as -4.60517025 × 100 = -4.60517025. More generally, a number of the form AeB is interpreted as A × 10B. In your case, the file is being read properly, but the numbers are being rounded to some number of decimal points when being displayed. You can use stream manipulators to d...
5,308,196
5,308,322
How can I disable net share folder with C/C++ in Windows?
I want to write a program with C/C++ for disabling net share folders and to prevent users from create a new share folder. Does anyone know the methods?
There is a method of doing it with C++ here. Here is another stackoverflow question that addresses a similar issue. In short, you need to call GetNamedSecurityInfoW() method with appropriate parameters to get the security descriptor of the folder and then you have to modify the ACL of the folder through methods explain...
5,308,198
5,309,041
How do I force a section of unfinished code to run even under max optimizations?
I have a function in my program that preforms a whole bunch of floating point math. It returns an array of values which is not currently being used in my program yet. I want to test this piece of code for speed under maximum optimizations, however since the code isn't used, the compiler conveniently skips the function ...
I'm sure there are many compiler tricks, but the easiest way is to just make it look like you are using the value. In this case, just pass the returned array to some other function. The other function doesn't need to do anything, but that should be enough to convince the compiler you need the results. If you find that ...
5,308,228
5,308,254
Printing the HTML of a website with c++/php?
I've been wondering, is there any way to print out the HTMl code of a website using c++ or php code? IF there is, I'd be glad if you could provide me with some materials to read and/or perhaps some codes would be perfect :) and also, can we send a javascript command to that website using c++/php?
print file_get_contents("http://stackoverflow.com/questions/5308228/printing-the-html-of-a-website-with-c-php"); print the source: print htmlspecialchars(file_get_contents("http://stackoverflow.com/questions/5308228/printing-the-html-of-a-website-with-c-php")); please explain regarding the js command, what do you wa...
5,308,464
5,314,034
Create Multiple Excel sheet in VC++
How to create Excel file with multiple worksheet in VC++ and save it.
The answer is XL->Worksheets->Add(); Worksheets are added in reverse order. #import "C:\Program Files (x86)\Common Files\microsoft shared\OFFICE12\mso.dll" #import "C:\Program Files (x86)\Common Files\microsoft shared\VBA\VBA6\VBE6EXT.OLB" #import "C:\Program Files (x86)\Microsoft Office\Office12\excel.exe" \ rename("D...
5,308,506
5,308,556
Readable alternative to std::set::find
Usually I don't care about the value of the item in the set, I care only whether or not it exists. And repeatedly writing if (s.find(val) == s.end()) is long, ugly and less readable. Is there a nice way which looks like if (contains(s,val)), which is somewhat standard (stl, boost). Bonus point for a solution that works...
If your concern is primarily terseness, then I'd suggest: if (s.count(val)) { // count == 1 == true, element exists } else { // count == 0 == false, element does not exist } But personally I still prefer checking find against end since the intent is more explicit. It's worth a bit of extra typing to me.
5,308,541
5,308,646
error C2297: '<<' : illegal, right operand has type 'double'
string mesag=""; mesag="aDoubleArray value at 0------->"<<aDoubleArray[0]<<" aDoubleArray value at 1 is "<<aDoubleArray[1]; addLog(AMR_LT_WARN, mesag);// this part not working addLog(AMR_LT_WARN, "this works well"); i dont know anythng about c++ just want to print aDoubleArray values to log file but it throws err...
You will have to do something like the following: char message[100]; sprintf(message, "aDoubleArray value at 0-------> %g aDoubleArray value at 1 is %g", aDoubleArray[0], aDoubleArray[1]); std::string mesag(message); addLog(AMR_LT_WARN, mesag);// this part not working addLog(AMR_LT_WARN, "this works well");
5,308,584
5,308,793
How to return text from Native (C++) code
I am using Pinvoke for Interoperability between Native(C++) code and Managed(C#) code. What i want to achieve is get some text from native code into my managed code. For this i try lot lot of things,e.g passing string/stringbuilder by ref, using [IN] and [OUT], Marshaling to LPSTR, returning string from function etc. b...
I'd do it with a BSTR since it means you don't have to call into native twice per string, once to get the length and then once to get the contents. With a BSTR the marshaller will take care of deallocating the BSTR with the right memory manager so you can safely pass it out of your C++ code. C++ #include <comutil.h> BS...
5,308,598
5,308,637
what does in c++ for example means typedef void(Number:: *Action)(int &);
Hi i have this command pattern example from the web , but there is something i dont understand is the typedef thing , what is the * Action represns here i dont even have this method defined ... here is the code example : #include <iostream> #include <vector> using namespace std; class Number { public: void dubbl...
The typedef defines a pointer to a function which is a method of class Number and accepts an int. Note that when you provide an actual function, it's dubble, and it is implemented. But you can add more, and when you do - you would only change the Number class, not the Command and others.
5,308,660
5,308,679
What does my_string(char* s) mean?
Please tell me what does the parameter (char* s) means?? Can it accept an array of characters or it will just accept pointers. Please also tell how can i make this to accept an array of strings and then dynamically assign memory depending on the length of the string.
Technically, it's a pointer to a single char variable. However, it can also be the pointer to the first element of an array of char values. You can increment and decrement the pointer to move through the string (s++ or s--) as long as you don't go beyond the ends. You can also use indexing without changing the pointer,...
5,308,776
5,308,817
Securing a RPC service
I'm writing a small services which will store files on disk and later, on request, return them to the client. I'm looking over my options when it comes to securing this service so no unauthorized program can read/write the data. The simplest solution would use impersonation so that the service thread handling the call ...
You typically only impersonate while handling a client request. The rest of the time, the service is configured to use a system account (usually THE system account) that has (or is configured to have) full privileges to do its necessary tasks. The security issue to watch out for is of course, ensuring that a user can't...
5,308,861
5,310,784
QTableView: how to do something on start/end editing?
Are there any signals (I cannot find anything in the docs) emitted when user starts and ends the QTableView widget cell edititing? I want to execute some function from table model then user begins edit eny cell and execute another function when user ends editing. How can I do this?
Actions when user starts/ends editing can be done by implementing your own Delegate. Also there is dataChanged signal in QAbstractItemModel.
5,309,020
5,309,100
How to get the full stream output with pstreams?
http://pstreams.sourceforge.net/ pstreams is an apparently very simple library, re-implementing popen() for C++. The library is very simple to install, consisting of only one single header file. You can download the header file here and add it to your application: http://pstreams.cvs.sourceforge.net/viewvc/pstreams/ps...
The streaming operator >> is designed to read a word at a time to a std::string, while skipping surrounding whitespace, just as you do when reading a number. If you want to read an entire line of text at a time, use getline instead. std::getline(in, str);
5,309,296
5,309,353
Passing the value of vector string to the win32 Function SetWindowText in C++
How could i pass the value of vector string to the win32 Function SetWindowText in C++. so far this is my code for that: vector <string> filelist; string path; path = Text; filelist = GetPath(path); SetWindowText(EditShow,filelist);
You could concatenate them all into one string and pass that as a c-string: #include <sstream> // for std::stringstream #include <algorithm> // for std::copy #include <iterator> // for std::ostream_iterator std::stringstream buffer; std::copy(filelist.begin(), filelist.end(), std::ostream_iterator<std::s...
5,309,414
5,309,431
in c++ when subclassing why sometimes need to add virtual keyword to overridden function?
Why do I sometimes see in C++ examples when talking about subclassing / inheritance, the base class has virtual keyword and sometimes the overridden function has also the virtual keyword, why it's necessary to add to the subclass the virtual key word sometimes? For example: class Base { Base(){}; virtual void f() ...
It is not necessary, but it helps readability if you only see the derived class definition. §10.3 [class.virtual]/3 If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf ...
5,309,494
5,309,828
copy buffer contents to another buffer
I have the contents of an http request in my buffer. I then define another buffer of the same size as the last one. And i need to copy the contents of the buffer to my new buffer. So the help i need is that how do i get to copy one buffer to another buffer. I tried memcpy but it is not working. void TrivialMediaPlayer:...
I am not sure what the exact code you write to copy from one StringSptr from another. But if you wanna memcpy( (void*)buf1 , (void*)pMediaData , pMediaData.Size() ); You must make sure that you should defined the "void*" function in the BufferSptr class (seems like a class written by you) to convert your BufferSptr ob...
5,309,505
5,309,609
GUI on top of a JVMTI agent
I am planing to develop a profiler by using the JVMTI API provided by Oracle. For a visualization I would like to implement a GUI (Qt framework) on top of the agent code. My first jvmti agent is aready compiling and running and I started to integrate the agent into my Qt project. Now I am facing the problem how to coup...
Well.. you have a number of choices the most obvious would be socket based comms. You'll have to assume that the majority of profiling use cases will involve a remote headless JVM on a server. In my profiler you can operate headless with a small start/stop/control utility on the same machine as the agent, data is colle...
5,309,543
5,309,736
Are Boost's unordered containers Thread-safe for reading?
For example, for MSVC, read-only is thread-safe on containers. Is boost similarly thread-safe for read-only? Update: i.e. Can we expect `const' methods to guarantee no memory corruption for multi-threaded use.
The upcoming standard defines the thread safety of all standard containers, and I would be very surprised if the boost implementations didn't meet this guarantee. In particular, you should be able to read from any instance of the container from any thread, as long as no thread is modifying the container.
5,309,835
24,325,370
Access thread-local from another thread
How can I read/write a thread local variable from another thread? That is, in Thread A I would like to access the variable in Thread B's thread local storage area. I know the ID of the other thread. The variable is declared as __thread in GCC. Target platform is Linux, but independence might be nice (GCC specific is o...
I was unfortunately never able to find a way to do this. Without some kind of thread init hook there just doesn't appear to be a way to get at that pointer (short of ASM hacks that would be platform dependent).
5,309,994
5,310,021
How do you use string.erase and string.find?
Why cant i call string.find in string.erase like so: str.erase(str.find(a[1]),str.size())? edit:code added #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; // html tags string tags[5]={"<!--...-->","<!DOCTYPE>","<a>","<abbr>","<acronym>"}; // //check if string exists i...
There's nothing wrong with that call (assuming a[1] exists and is found in str at least once) #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; std::string a = "wwwwww"; str.erase(str.find(a[1]), str.size()); std::cout << str << '\n'; } test run: http...
5,310,536
5,310,598
GUI development In Linux
I am working on application which need to develope in both windows and linux. I am going to develop the GUI in MFC on windows. I wanted what GUI available specific to Linux. Any body suggest me API for the linux to develop the GUI.
I suggest gtkmm. It's modern, portable and object oriented. And it doesn't use a weird pre-compiler :)
5,310,553
5,310,954
Scalar Value Function returns VARCHAR(MAX) in C++ ADO (not .NET)
I created a scalar-valued function in MSSQL that returns VARCHAR(MAX). I am using a CommandPtr (preCom) filled with the parameters for the function, and I am calling the function with the following call: _variant_t vNull; vNull.vt = VT_ERROR; vNull.scode = DISP_E_PARAMNOTFOUND; HRESULT hr = ptrCom->raw_Execute(&vNull, ...
See Updating an Application to SQL Server Native Client from MDAC: When MDAC applications connect to SQL Server, the data types introduced in SQL Server 2005 will appear as SQL Server 2000-compatible data types as shown in the following table. SQL Server 2005 type SQL Server 2000 type varchar(max) text So I...
5,310,601
5,310,643
Complex vectors in C++
I work with this vector: vector<string, vector<int>>. I supposed that the first iteration returns an array: for (vector<string, vector<int>>::iterator it = sth.begin(); it != sth.end(); ++it) { // how do I get the string? // I tried (*it)[0], but that did not work } Also, how would I push_back to this vector? ...
vector takes: first template parameter is a type second optional parameter is an allocator vector<int> is not a valid allocator for string. Assuming you do not want map here, you probably want: vector< pair<string, vector<int> > > outerVec; vector<int> vecInt1, vecInt2; vecInt1.push_back( 1 ); vecInt1.push_back( 5 );...
5,310,805
5,312,260
Split up a collection, for each subset respecting probabilities for properties of its items
For a small game (for which I am a bit forced to use C++, so STL-based solutions can be interesting here), I encountered following neat problem. I was wondering if there is any literature on the subject that I could read, or clever implementations. Collection S of unique items {E1, E2, E3}, each item E having a set of ...
This has resemblance to a constraint satisfaction problem (CSP) with hard and soft constraints. There are a couple of standard algorithms for that, but you have to check, if they apply to your particular problem instance. Check wikipedia for starters.
5,310,908
5,311,475
boost::filesystem::file_size error when using a path with whitespace
I'm asking boost::filesystem::file_size for a file with path "/tmp/test\ file.txt", and it reports no such file or directory when it is there. Error: fs::file_size("/tmp/test\ file.txt") reported boost::filesystem::file_size: No such file or directory -rw-rw-r-- 1 rturrado users 12486 Mar 15 12:01 /tmp/test file.txt A...
Closing this question, as I fixed the issue thanks to Mat and ymett comments. boost::filesystem::file_size("/tmp/test file.txt") works just fine. You don't need any escaping.
5,310,983
5,336,006
Which editor for coding in Borland C++
I have a 64 bit OS (Windows 7). I want to code in C++ but the default editor of Borland does not support full screen mode on my system. Which editor do i use to solve this problem? I want to code in Turbo C++ only.
use netbeans-IDE 6.0.. it will solve your problem.
5,311,063
5,311,175
how to track Message Response time and retransmission
I am working on Client Server application. There are lots of command exchanged between client server.There are certain command for which response time is 30sec,20 sec. I am developing this application both windows and linux platform. Suppose client sents a coomand called "COMAND1" and expects respose "RESPONSE1" within...
You have a few options: Use alarms (i.e. signals) - if your granularity is seconds, this may be adequate If you can use a third-party library - such as boost, it will provide concepts such as dead line timers. RYO, with threads and select (or some such - e.g. pthread timed condition wait) btw. IMHO, the right way is ...
5,311,306
5,311,456
How to find an arbitrarily oriented minimum bounding box in c++
So let's say I have a list of N pairs of positive long coordinates (points). How do I find the smallest rectangle containing all of them? The rectangle can also have floating coordinates and be rotated in any angle and further shrunk... Not just X, Y, Width and Height! I already know how to find the smallest polygo...
See http://www.geometrictools.com/Source/ComputationalGeometry.html The section "Minimum-area box" has various examples. e.g. Compute a minimum-area oriented box containing the specified points. The algorithm uses the rotating callipers method. https://www.geometrictools.com/Samples/Geometrics.html#MinimumAreaBox2D h...
5,311,407
5,312,025
What's the difference between running a debug app hosted in Visual Studio and running it directly?
I have an application running on the .Net framework 4 and my application runs managed AND unmanaged code. UDP sockets are used with a custom comms stack to speak with our custom hardware. When the application is run from Visual Studio, all is fine, but when it is run on its own, it often freezes. I have seen the behavi...
The one thing that's different when running the Release build without a debugger is that the JIT optimizer is enabled. The code runs faster. Which has a strong correlation with your problem, threading problems are timing sensitive. Count yourself lucky (I'm sure you don't) that this goes wrong while your code is sti...
5,311,445
5,311,602
reading a directory in C++ in portable way
I have a requirement as follows. I have a directory for eg i have /tmp/myFolder Under "myFolder" i have files whose names as below myFile-N001.txt myFile-N002.txt myFile-N003.txt in my application while writing to a file i should write to largest number file in /tmp/myFolder, for eg in above case i should write to myF...
This is really two problems in one. I'd use Boost.Filesystem to portably iterate over the files and store them in a vector with (untested) std::string maxname; unsigned maxnum = 0; for (fs::path::iterator i(dir.begin()), end(dir.end()); i != end; ++i) { std::string name = i->string(); unsigned num; if (std...
5,311,548
5,311,580
What's the issue with malloc() and virtual functions?
Possible Duplicate: C++: why is new needed? Why cant I use malloc to allocate space for my objects when they are children of a class containing virtual functions? This is really frustrating. Is there a good reason? The following program illustrates the problem. It segfaults on line 27, where I call aa->f() #include ...
A common way to implement virtual functions is to have a pointer to a "virtual table" or vtable at a negative offset from the object. This table is needed to figure out what virtual function to call. This is why just malloc'ing space doesn't work.
5,311,624
5,424,421
C++: stop RPC service
from my C++ source, I am starting an RPC service calling svc_run(). Everything looks just fine and I can see my service running if I type rpcinfo -p in my terminal. Now I am working on a "cleanup" function which should stop this service and remove it from the rpcinfo -p list. How can I do that? At the moment I am only...
After some time, I found out how to do this. Actually I faced some unexpected difficulties. The standard way to do this would be to use this: svc_unregister(PROGID, VERSION) but somehow, it did not work for me. After lots of trial and some online help (http://www.spinics.net/lists/linux-nfs/msg05619.html) I was able t...
5,311,797
5,312,195
C++::How to put different length arrays of const strings into common class
Sorry, new to C++, converting from C, and have struggled to find a good way to do this... //Fragment follows const char *List1[]={"Choice1", "Not a good choice", "choice3"}; //rom-able const char *List2[]={"Hello", "Experts", "Can", "You", "Help?"}; class ListIF{ private: int index; char *list; public: void GetVal...
Not sure what you want your functions to be but one way to wrap the arrays would be: EDIT : changed to incorporate Larsmans suggestion (on the chance that your compiler can't handle his answer). class ListIF { private: std::vector<const char*> m_list;//stores ptrs to the ROM public: ListIF(char const **list, s...
5,312,042
5,312,223
C++ protected access
is there anyway i can access a protected variable in a class without inheritance. class ClassA{ protected: int varA; }; class ClassB{ protected: ClassA objectA; }; ClassB theMainObject; I would like to access varA through theMainObject.
I assume modifying definition of ClassA is forbidden. Here is a tricky way for you, but I don’t encouraging you to use it :) class ClassA { protected: int varA; }; class ProtectedRemover // magic thing { public: // <- Note this! :) int varA; }; class ClassB { protected: ClassA objectA; public: // Just ad...
5,312,213
5,312,298
Uses of unnamed namespace in C++
When would one use unnamed namespace in C++ ? Is it better in any sense than a free standing function? Also, should it be used only in source file and not in header file?
According to Stroustrup, you should use it in places where in old C you would have made static globals. The idea is that the items in question can be "global" to the source file they are in, but not pollute the namespace of any other source files in your compilation. In other words, you shouldn't be creating static glo...
5,312,259
5,312,468
check boost::variant<T> for null
I have a boost::variant in my program and I want to check if the variant itself is initialized and also if there is a value contained in one of it's types. I've tried empty() on the variant, but that doesn't seem to work. Neither does checking against NULL. Does anybody know how to check for this? EDIT: Ok, It seems i...
A boost::variant is always initialized. If you did not initalized it explicitly, the first item was constructed using its default constructor: struct Foo {}; struct Bar {}; struct Visitor: boost::static_visitor<> { void operator()(Foo const& foo) const { std::cout << "Foo\n"; } void operator()(Bar const& bar) cons...
5,312,267
5,319,596
Wrapping a C++ library in Objective-C is not hiding the C++ symbols
I am trying to wrap a C++ library (for Sybase Ultralite) with Objective-C so that the library can be imported into MonoTouch. I have created an Objective-C library and included the compiled C++ library in this project, libulrt.a. To get my project to compile I set the path to the User Header Search Path to point to the...
@Mark Bessey is on the right track here, but he's incorrect that there is little difference between setting the language and adding the C++ library. Adding the C++ library is cheap and required (one way or another). Changing the language is expensive because the ObjC++ compiler is slower, and the resulting code is in m...
5,312,294
5,312,337
Adding random integer number in c++
How do I add in c++ a random integer number between 100 and -100 to an int variable?
int rnd = 0; rnd += ( ( rand() * 200 ) / RAND_MAX ) - 100; Edit: Obviously this is going to have issues where RAND_MAX is equal to INT_MAX. In which case the answer below: Adding random integer number in c++ is probably more appropriate. Edit: On Windows platforms RAND_MAX is defined 0x7fff and so this calculation wil...
5,312,331
5,312,652
Which data format for efficient socket communication in C++/Qt
I want to implement a profiler which tracks the state of the JVM in real time. I am not sure which data format would be appropriate for this task as I have to receive updates of the state of the JVM. I thought XML would be great, but with every change sending the whole XML data seems to be very bogus.
Maybe JSON Format? http://www.json.org/
5,312,773
5,312,969
C++ application: Is it possible to pass accepted TCP connection from one process to another?
So I wonder - is it possible to pass accepted TCP connection (on Windows or Unix like OS) from one process to another? Here the point is to pass connection - not data in a way a proxy app would.
On Windows, use WSADuplicateSocket, pass the filled in WSAPROTOCOL_INFO to the other process, use WSPSocket to recreate a socket. On unix-like OS'es this is possible using the sendmsg() system call. libancillary abstracts this for you.
5,313,000
5,315,150
A new buffer created every time the program is called
I need to create a new buffer every time. Something like this int bufcalc; bufcalc++; BufferSptr buf[bufcalc] (new Buffer (pMediaData->Size()) ); memcpy(buf[bufcalc]->GetData() ,pMediaData->GetData() , pMediaData->Size()); where bufcalc is type int and increments everytime. if(bufcalc>=2) { DecodeBufferData (...
Try using std::vector instead of array. The std::vector expands as necessary and can use index variables like array: std::vector<Buffer *> buf; buf.push_back(new Buffer(pMediaData->Size())); memcpy(buf[bufcalc]->GetData() ,pMediaData->GetData() , pMediaData->Size()); The std::vector is much safer than an array. S...
5,313,031
5,313,106
How to force cdecl calling convention for functions declared in specific header file
Hi My VC2008 project uses the stdcall calling conventions. I have an external library that I am using which has been built with cdecl naming convention, however they didn't mention the calling convention in the function declaration of the functions. I would like to know if VC has some kind of #pragma or other keyword t...
You can specify calling convention by: Do nothing and you get the default of cdecl. Specify __cdecl explicitly (or perhaps through a macro). Elect to use cdecl throughout a translation unit by compiling with /Gd. There's no pragma or anything similiar to control calling convention.
5,313,150
5,313,521
LZF may compress with different algorithms
I am using libLZF for compression in my application. In the documentation, there is a comment that concerns me: lzf_compress might use different algorithms on different systems and even different runs, thus might result in different compressed strings depending on the phase of the moon or similar factors. I plan to c...
The reason for the "moon phase dependency" is that they omit initialization of some data structures to squeeze out a little bit of performance (only where it does not affect decompression correctness, of course). Not an uncommon trick, as compression libraries go. So if you put your compression code in a separate, one-...
5,313,322
5,313,716
C++ cast to derived class
How can i cast to a derived class? The below approaches all give the following error: Cannot convert from BaseType to DerivedType. No constructor could take the source type, or constructor overload resolution was ambiguous. BaseType m_baseType; DerivedType m_derivedType = m_baseType; // gives same error DerivedTy...
Think like this: class Animal { /* Some virtual members */ }; class Dog: public Animal {}; class Cat: public Animal {}; Dog dog; Cat cat; Animal& AnimalRef1 = dog; // Notice no cast required. (Dogs and cats are animals). Animal& AnimalRef2 = cat; Animal* AnimalPtr1 = &dog; Animal* AnimlaPtr2 = &cat; Cat& ...
5,313,349
5,313,505
Use Constraint delaunay triangulation to Triangulate a Polygon
I have a constraint delaunay triangulation (CDT) algorithm, and I have a polygon ( it could be concave or convex) as input. How can I use that constraint delaunay triangulation algorithm to break the polygon into triangles without introducing new points? Edit: The union of all the triangles must equal to the polygon. S...
The easiest way since you have a polygon and not a point cloud would be to triangulate naively then visit each edge and test to see if it is outside the original polygon using simple line-polygon intersection tests. Depending on your algorithm you may be able to do this test as part of the triangle subdivision and skip...
5,313,433
5,315,482
Segfault Issues With Array of Structs Inside a Struct
Edit: The first commenter reports that the code has no apparent errors, so I've revised the post with more code. Apologies for the length. Again the error appears to be when I reference the string vars in the substructure... note that if I remove the first write that causes the segfault in segfaults later on due to a...
You are adding "boxX_start.pdb" to stringstream on every iteration without clearing the stream. Memory usage could add up very quickly with a large NUMBEROFBOXES value. Try this void InitSimpleVars(sim_t & MySim) { std::stringstream in; MySim.StartTime = clock(); //INITIALIZE Box Sim Vars... ...
5,313,477
5,340,760
gSOAP namespace prefix problem
I have noticed a few people have asked this question but I haven't been able to find a satisfactory answer. I am using gSOAP to create c++ stubs from a wsdl document. The problem is gSOAP is prefixing the namespace to the soap method names when sending a soap message. For example it is sending <ns2:Inform></ns2:Inform>...
Which version of gSOAP do you use? If it's 2.8.1 or higher you can try using this: soap_omode(&soap, SOAP_XML_DEFAULTNS); I found it on http://cateof.wordpress.com/2010/09/21/default-namespace-gsoap-with/
5,313,528
5,313,636
Why do I need to use `pthread_exit()` from the main thread, while it was not created by a `pthread_create`?
I have a question about some code I'm testing to start understanding posix threads. I have this basic code: #include <iostream> #include <string> #include <sstream> #include <pthread.h> using namespace std; void *printInfo(void *thid){ long tid; tid =(long)thid; printf("Hello from thread %ld.\n",tid); ...
If you don't use pthread_exit in the main function then all created threads are terminated as main finishes, i.e. in your case before they have printed anything. By calling pthread_exit in the main function makes main wait until all threads have completed. From the pthread_exit man page: The process will exit with an ...
5,313,793
5,320,569
QtWebkit resolving event dispatcher
i'm playing around with QtWebkit lately and i was wondering if it is possible to resolve the element displayed in the QWebView which is responsible for an event, e.g. a MouseEvent. I've installed an EventFilter function at the WebView Object with a function like this: bool WebKitManager::eventFilter(QObject *obj, QEven...
I believe what you could do is: cast object parameter to QWebView get QWebFrame under mouse via vebView->page()->frameAt() method use hitTestContent method of the returned frame to detect the element for the given mouse position Below is an example: bool WebKitManager::eventFilter(QObject *object, QEvent *event) { ...
5,313,897
5,313,951
Where is the errnos defined? Example linux c/c++ program for i2c
When something goes wrong in a classic linux c/c++ software we have the magic variable errno that gives us a clue on what just went wrong. But where is those errors defined? Let's take a example (it's actually a piece from a Qt app, therefore the qDebug()). if (ioctl(file, I2C_SLAVE, address) < 0) { int err = errno...
They are generally defined in /usr/include/errno.h* and are accessible by including errno.h: #include <errno.h> I write out both the errno value and its textual meaning when reporting an error, getting the textual meaning via strerror(): if (something_went_wrong) { log("Something went wrong: %s (%d)", strerror(err...
5,313,943
5,358,452
vim omnicppcomplete pattern not found
I installed vim7.3 on my computer (under windows 7) and i want to use an autocomplete plugin. I searched a lot and found that Omnicppcomplete is the best for that. So i followed this tutorial: Install OmniCppComplete plugin My _vimrc config file looks like this: set nocp filetype plugin on syntax on set filetype=cpp ...
the problem was that the set tags+=C:/Program\ Files/Vim/vimfiles/tags/stl there is something wrong here: :pwd -> c:\Windows\system32 copy the tags file to system32 restart vim then the following c++ code worked.
5,314,313
5,314,370
How to pass a multimap into function
I have a pretty simple question. Im just learning Maps and multimaps and want to know how to pass them into a function. Ive got most of my mind wrapped around multimaps but would like a quick example on how to pass them into a void function. int main() { multimap<string,int> movies; movies.insert(pair<string,int>("Ha...
Why pass by pointer? I think it is better to pass a reference (if the map shall be modified within the function) or reference to const otherwise void calculateAverage(const multimap<string,int> & q) { // this function wont calculate the average obviously. I just wanted to test it int averageH; int averageP; int average...
5,314,319
5,314,606
How to export std::vector
I'm writing application wiht boost.python library. I want to pass function into python which returnes std::vector. I have a little troubles: inline std::vector<std::string> getConfigListValue(const std::string &key) { return configManager().getListValue(key); } BOOST_PYTHON_MODULE(MyModule) { bp::def("getListV...
You should write a converter like this: template<class T> struct VecToList { static PyObject* convert(const std::vector<T>& vec) { boost::python::list* l = new boost::python::list(); for(size_t i = 0; i < vec.size(); i++) { l->append(vec[i]); } return l->ptr(); }...
5,314,432
5,314,578
Load a numpy array into C from a file that was saved with numpy.save(...)
I'd like to access data in a C program that resides in a file that was written from python using numpy.save(...). So far, I was looking for a way to call the C version of numpy.load my C program, but it seems there is no directly accessible C version, because numpy.load uses the pickle module. Another solution would be...
The .npy format is not really meant to be read from outside NumPy. There are many formats available with provide both, excellent C and Python libraries, like HDF5 and NetCDF, so I can't see any reason whatsoever to access native NumPy files from C. If you want to do this anyway, here are the docs of the .npy format. ...
5,314,504
5,314,542
FILE Type Not Recognized in MFC
I'm using FILE type in my MFC project but after compiled, it shows the following errors: Error 23 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 24 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Error 22 error C2146: sy...
Ultimately, it lives in stdio, so you want: #include <stdio.h>
5,314,562
5,314,829
Pushing images into a gstreamer pipeline
After playing around with some toy applications, exploring the documentation and googling around (including the mailing list archives) I am still puzzled for what I would think is a rather common use case. I have an existing code that generates images (in memory) and I would like to push these images into a gstreamer p...
GStreamer uses plugins to do everything. Plugins that create data or take it from an external source are called "src" plugins. The generic src plugin for injecting application-generated data into a pipeline is called appsrc. The API provided by appsrc is documented as part of the App Library. Here's one example that ...
5,314,735
5,314,838
How to add external libraries to qt4 application c++
what is the best way to add additional compiled libraries to my qt project ? For example boost or poco libs ? Thanks :)
If you're using the GCC compiler add something like this to the .pro file: For Boost: INCLUDEPATH += d:/Biblioteki/C++/boost/boost_1_44_0a LIBPATH += d:/Biblioteki/C++/boost/boost_1_44_0a/stage/lib LIBS += -lboost_system-mgw44-mt-d-1_44 LIBS += -lboost_filesystem-mgw44-mt-d-1_44 LIBS += -lboost...
5,314,858
5,314,908
Passing a non-reference as a reference, without temp variable
I am trying to do the following: call a function which takes references as parameters without passing "variables", just values. Shouldn't my compiler(gcc) be able to make temporary "variables" to send in? It would seem that mvc does it, one way or another (other person in project uses it). I have: foo(Vector&,Vector&) ...
Vector(1,2,3) creates a temporary, and a temporary cannot be bound to non-const reference! So make the parameters const as: void foo(const Vector&, const Vector&) Now it'll work!
5,314,859
5,315,010
shared_ptr - ccomptr swap
I got a simple question here Let's suppose we have a codebase that employs usage of shared_ptr/enable_shared_from_this. And we have been asked to convert -a portion of- the codebase into a COM server where we are supposed to use CComPtr instead, while it is not a mandatory requirement... now here is the question; Is th...
There is no need for enable_shared_from_this when using CComPtr because CComPtr does not maintain a reference count. Instead, the object it points to maintains the reference count. All CComPtr does is call member functions on the object that increment or decrement the reference count. There is no problem with doing the...
5,314,906
5,315,019
I have a map<string, vector<record>>, how to remove records from vector<record>?
I have tried all possibilities I could, and failed to find solution. Please help I want to remove records in vector in map while iterating over it. map < string, vector < record> >::iterator map_it; for(map_it = map_records.begin(); map_it != map_records.end(); ++map_it){ vector < record>::iterator vec_it; for(...
vec_t = map_it->second.erase(vec_it); //note the assignment! You also need to check it's validity immediately, so better re-write the inner loop as: for(vec_it = (*map_it).second.begin(); vec_it != (*map_it).second.end(); ) { if(condition) vec_it = map_it->second.erase(vec_it); else ++vec_it; ...
5,314,953
5,315,085
Are std::strings good at random insertion / random erasing?
I want to make a simple text editor using std::strings. If my text is 500,000 characters and I want to insert or remove at the 253,000th character, will this be slow, or will it be just as fast as if my text contained 10 characters? Otherwise I'm not sure what I'll do to fix it (unless I use a linked list but then read...
I've never used it myself, but I believe this is what rope is for.
5,314,975
5,315,046
Running a Secondary Thread for Output in C++
I’m looking for a portable method for creating threads specifically for output of data in C++. I’d prefer to stay away from Boost if possible, but I’m not against using it if it’s the best option. Here is the situation: I have a program that does a complex computation on some data that it reads and produces three outpu...
C++ doesn't support threads in its standard (at least not now), and to have threads portably you must use some library. There are many C++ libraries giving you portable threads out there, and your particular problem doesn't seem special in any way. Boost is very well received and adopted and has the best chance to infl...
5,315,073
5,315,098
Segmentation Fault: Why?
I have this piece of code which compiles and works as expected: #include <iostream> using namespace std; int fun(int* p){ *p = 20; return 1; } int main(){ int* number; *number =10; cout << "before: "<<*number<<endl; fun(number); cout << "after: "<<*number<<endl; return 1; } Whil...
number is not pointing to a valid memory location in main(). Just the program has declared a pointer, number, that can hold an address of integer type. But, it not assigned/initialized to point to any integer's location. int* number = new int; *number = 10; And since the program is managing resources, it should retur...
5,315,134
5,332,780
"Invalid template argument" error in Visual Studio but not GCC
suppose you have the code template <template<class> class BaseType> class EST16 : public BaseType<int> { public: EST16(double d) { } }; template <class T> class SCEST { T y; }; typedef EST16<SCEST> EST16_SC; class Child : public EST16_SC { public: Child() : EST16_SC(1.0) { ...
The error message is because NotWorkingChild derives (indirectly) from SCEST<int>, which makes SCEST inside the scope of NotWorkingChild refer to the class SCEST<int>, instead of the template. MSVC is correct to reject this, and GCC4.5 should reject this too (GCC4.5 has more correct injected class name lookup). Here i...
5,315,176
5,315,581
LLVM get constant integer back from Value*
I create a llvm::Value* from a integer constant like this: llvm::Value* constValue = llvm::ConstantInt::get( llvmContext , llvm::APInt( node->someInt() )); now i want to retrieve the compile-time constant value back; int constIntValue = constValue->??? The examples shown in LLVM Programmer manual seem to imply that c...
Given llvm::Value* foo and you know that foo is actually a ConstantInt, I believe that the idiomatic LLVM code approach is to use dyn_cast as follows: if (llvm::ConstantInt* CI = dyn_cast<llvm::ConstantInt>(foo)) { // foo indeed is a ConstantInt, we can use CI here } else { // foo was not actually a ConstantInt } ...
5,315,203
5,315,260
Class API design: should I return a field in getXxx() method by value or as a const-ref?
Just a C++ newbie question. I have a class like class Person { private: std::string m_name; }; Is it better to design getter as std::string name() const; so m_name will be copied each time name() is called or as const std::string& name() const; so caller can make his own copy, if he wants.
In general, I would go with the const& version, since it avoids unnecessary copying. However, if you're making a class that's intended to be accessed by multiple threads simultaneously, returning a copy is cleaner and more reliable.
5,315,427
5,315,454
Returning values from thread specific code using boost threads
I'm using C++ boost library threads like this MyThread alarm(); boost::thread thrd(alarm); if (thrd.timed_join(boost::posix_time::seconds(timeout))) { cout << alarm.modified_var << endl; } else { cout << alarm.modified_var << endl; } modified_var is changed inside MyThread class but when I print it later after...
That is because the alarm-object is copied when passed to the thread constructor. The solution is to wrap it in a boost::ref: boost::thread thrd(boost::ref(alarm));
5,315,574
5,316,274
Using std::runtime_error instead of CException
When I throw a CException in the main thread, it is neatly caught by the framework and a nice MessageBox shows the error text. When I throw an std::runtime_error the application just crashes. The problem is I don't see the text of the exception, and I have to spend time to figure out it's actually something I've 'throw...
Somewhere within MFC's implementation of the main message loop it has a try/catch setup that gives the behavior you see when CException types are thrown. You could wrap your own code in various try/catch statements to catch the exceptions, as already stated by others. It would also be possible to wrap MFC's message loo...
5,315,716
5,315,833
typedef'ing an enum does not make the enum-values visible
I have a class in which I have an enumeration, defined like this: class X { public: enum Direction {DIR_LEFT, DIR_RIGHT}; }; Now I want this enumeration to be reused in another class, like this: class Y { public: typedef X::Direction Direction; }; As expected, using Y::Direction works co...
Unfortunately C++ doesn't introduce a new scope with an enum although C++0x is improving things. Practically this means that you can't typedef an enum and get the enumerated values as well. What you can do is use a nested struct with the name you want for the enum and typedef THAT. class X { public: struct Directio...
5,315,885
5,316,204
Convert std::exception to EXCEPTION_POINTERS
I may be completely misunderstanding how to use the Google Breakpad API, and am open to comments / suggestions / rude remarks if that is the case. I am trying to call the following C++ function: bool WriteMinidumpForException(EXCEPTION_POINTERS* exinfo); I have a reference to a std::exception: try { return QApplicat...
In the MSVC compiler, C++ exceptions piggy-back onto the native Windows exception plumbing (SEH, Structured Exception Handling). There's a pretty big impedance mismatch though, the concept of an exception filter is doesn't have a good match in C++. By the time the catch handler catches an exception, the SEH exception...
5,315,908
5,316,079
Why can't everything be overloaded in C++?
It is reasonable that sizeof and typeid cannot be overloaded, but I can't see the harm in overloading ?:, .* and .. Are there technical reasons for this?
To quote Bjarne Stroustrup: There is no fundamental reason to disallow overloading of ?:. I just didn't see the need to introduce the special case of overloading a ternary operator. Note that a function overloading expr1?expr2:expr3 would not be able to guarantee that only one of expr2 and expr3 was exec...
5,316,152
5,316,259
Store data in executable
I'm just curious about this for a long time. Is it possible for an application to store some changeable data (like configurations and options) inside its own executable? for example: is it possible to design a single executable which if a user ran, set some configurations, copied it into another PC, then the applicati...
Yes and no - Yes, there's plenty of space in an executable image you can put data. You can add a pre-initialised data segment for this, say, and write the data into there; or a resource, or you can abuse some of the segment padding space to store values in. You control the linker settings so you can guarantee there wi...
5,316,242
5,316,414
Visual C++ memory block padding
I am currently working on getting a large project stable before doing testing, and appear to have random crashes in release mode. Is there a way to increase memory block padding to recognize out of bounds access violations more easily? As well, can you recommend any other debugging techniques that check as much as poss...
Microsoft provides the Page Heap provided in Application Verifier. This mode of executing your program will help you immediately find buffer overruns.
5,316,387
5,316,563
Imitate a static constructor in C++
This a question related to the initialization of objects in C++. I have a group of classes (not instances), inheriting from a common base class, and I need them to register info about themselves in a container (specifically a map) when the program starts. The problem is that I need it to be dynamic. The container is de...
You are describing different problems all at once. On the particular issue of having some sort of static initialization, a simple approach is creating a fake class that will perform the registration. Then each one of the different classes could have a static const X member, the member will have to be defined in a trans...
5,316,446
5,316,650
Redirect standard streams back to Console and Keyboard in C++
After redirecting standard input and output to some files(for example) using freopen how can I redirect them back to where they were at the very beginning?
You can duplicate/clone the initial FD's using id = fcntl(blah,F_DUPFD,0), and then use dup2(0,id) to copy it back (after closing stdin!), then reopen the file using fdopen(). Repeat for the others. However, that probably doesn't get you what you want exactly - it gets you a random filehandle that is associated with ...
5,316,529
5,316,547
OpenGL texture inverted
I'm trying to map the input from my webcam to a plane in OpenGL. I'm using OpenCV to get the images from the webcam. The problem I have is that the texture is vertically inverted, if my texture is "v", the current result is "^". I want to fit the image taken from the webcam to my plane (2x2). Its lower left corner...
Flip the texture coordinates on the quad you're rendering. OpenGL does store texture "upside-down" from how most people assume they'd be, so the simplest way to handle it is just work with OGL. glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,-1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); gl...
5,316,562
5,316,622
Is it possible to hide a password defined within C++ code
... so that browsing the disassembly won't immediately expose the password (declared as a static variable). As an example, imagine a program that has a zip file attached that it must open for assets but is not easily accessible to prying eyes. I know that it is impossible to completely hide or protect that zip but I'm ...
No but there are things you can do to make it harder. Store the password as a series of numbers, do some calcualtions on them to generate the actual password, store parts of the password in resources such as icons etc.
5,316,742
5,316,806
Error: Invalid use of void expression
#include <gtk/gtk.h> #include <string> using namespace std; class WIN { protected: GtkWidget *window; public: GtkWidget* get_window(){ return window; } void set_window(GtkWidget* w){ window = w; } void set_title(string s) { gtk_window_set_title (GTK_WINDOW(window), s.c_str()...
Seems like gtk_widget_show() returns void. That's the void expression you are using in an invalid way. http://library.gnome.org/devel/gtk/2.99/GtkWidget.html
5,316,943
5,367,864
C++ and member function pointers
I'm trying to send an address of a member function to my "Thread" class so I can activate it from there. I read that I can use functors but I want it to be generic in a way that I can send it to my "Thread" constructor and functors need templates, so it won't be enough for me... Does anybody know a way to do this? tha...
Finally I decided to use a stub function as suggested in this thread: Create thread is not accepting the member function thanks everbody :)
5,317,177
5,318,286
Export variable into python from C++ using boost.python
I have, for example, a varibale in c++: const float Pi = 3.1415926535898f; What is the best way to export it into python-module using boost.python? I want to access it as variable in global scope.
Seems that it can be easily done using: boost::python::scope().attr("Pi") = Pi;
5,317,488
5,317,699
"Assertion Failed" on destructor
does anyone know whats wrong with this ?? it keeps giving me an "Assertion Failed" _BLOCK_TYPE_IS_VAILD(pHead->nBlockUse) when it tries to use the detructor on a non empty stack EDIT:MORE CODES: class stack { private: struct StackNode { int x; int y; StackNode *next; }; StackNode *top; ...
You copy your stack when passed into print_stack and didn't follow the rule of three What is The Rule of Three? which results in a double deletion and your problem. Unless you're doing this as an exercise, use std::stack instead - it's been tested and debugged for years.
5,317,571
5,317,591
C++ NetBEAN cout Error?
#include <cstdlib> using namespace std; /* * */ int main(int argc, char** argv) { cout << "COME AT ME BRO!\n" return 0; } It says cout is unable to resolve identifier The C++ code assistance is setup properly, I'm just not sure whatelse it could possibly be.
You did not include <iostream> and thus the identifier std::cout is never declared or defined in your program.
5,317,621
5,317,725
How can I find and reserve an available port for a different thread?
I'm trying to construct two components that communicate via UDP sockets. Component 1 is in the main thread and Component 2 is in a secondary thread. Multiple copies of this application can be running on the same machine at the same time, so I can't used fixed ports. The program also needs to be run on both Windows and ...
I don't think I can pass the QUdpSocket across the thread boundary You can, so do that. Just don't use it in both your threads simultaneously .
5,317,692
5,317,754
Strange casting problem Derived to Base in C++
I have three classes: Base, Derived (inherits from Base), and Stats (which uses a Base). The program makes a Derived object, which may be deleted and reconstructed several times during the program's execution. It also sets up a Stats object which will only be created once, but needs to call functions on the Base of the...
You are creating a reference to a temporary Base * that points to what d was pointing at (NULL in this case). That temporary is destroyed after line that invokes the constructor finishes executing. Congratulations, you've just invoked undefined behavior! After that, anything can happen. Essentially, this line reads lik...
5,317,735
5,317,811
How to write destructor when i have pointers in class?
using namespace std; class WINDOW { protected: GtkWidget *window; public: WINDOW(); GtkWidget* get_window(); void set_window(GtkWidget* w); void set_title(string s); void show_widget_all(); static void main_loop(); };
In this case just do window = NULL; Do delete window; window = NULL; in the class where you created the object. This rule helps avoiding bugs.
5,317,777
5,317,843
Is std::complex stored in an interleaved fashion?
That is, on disk, if I have an array of std::complex, is it stored RIRIRIRI or RRRRIIII or something else? My real question is - if I have a structure that I have defined that contains two numbers, can I do a reinterpret cast an array of my structure to use functions that would expect a std::complex array? What about m...
A C++ class is little more than a struct with some adornments. As such, the members defined in a class are arranged sequentially in memory, contiguously for each element of that type. In other words, an array of std::complex, where each element contains RI, will be stored RIRIRIRI. You can probably get away with a re...
5,317,971
5,318,049
Partial template specialization question
class FooInterface { virtual void toggle() = 0; }; template <class TYPE, class CONFIG> class Foo : public FooInterface { virtual void toggle(); TYPE value_; }; template <> void Foo<bool, class CONFIG>::toggle() { if (CONFIG::canToggle()) value_ = !value_; } struct MyConfig { static bool canToggle() { ...
dispatch template<class CONFIG, class C> void toggle_impl(type<bool>, C &c) { if (CONFIG::canToggle()) c.value_ = !c.value_; } template <class TYPE, class CONFIG> class Foo : public FooInterface { virtual void toggle() { toggle_impl<CONFIG>(type<TYPE>(), *this); } TYPE value_; };
5,318,000
5,318,138
finding a pythagorean triplet (project euler)
I'm well aware this brute force method is bad and that I should be using something like Euclid's formula, and that the final loop isn't needed as c = 1000 - (a + b) etc... but right now I just want this to work. bool isPythagorean(int a, int b, int c) { if((a*a + b*b) == c*c && a < b && b < c) { cout << a <...
This part of the code iterates very strangely: for(a = 1; a < b; ++a) { for(b = 2; b < c; ++b) { for(c = 3; a + b + c != 1000 && !isPythagorean(a, b, c); ++c) { } } } Initially, a = 1, b = 2, c = 3. But upon the first for(c), c=997, so the second iteration of for(b) will run up to b=996. Keep d...
5,318,424
5,318,450
Implicit conversion between datatypes
Why does, for example, the result of operation between an unsigned short and int always yields an int? unsigned short s = 65535; int i = 65535 Expression typeid(s * i * i).name(), gives a value which is out of the range of an int but still the implicit conversion returns an int, why?
There are a set of conversions called the usual arithmetic conversions that are used prior to the evaluation of most arithmetic operators. Basically, you can consider there to be a few rules for arithmetic on integers: First, integer arithmetic is never performed with operands "smaller than" int, so in the case of sho...
5,318,441
8,187,612
Is it possible to modify PYTHONPATH at runtime?
I have a C++ application dynamically linked to the Python interpreter. I want to be able to import python modules from a particular directory. I want to modify the PYTHONPATH for my process so that sys.path will include the paths that I added to the PYTHONPATH. That seems to be the way it works according to this doc...
I found cross-platform solution. Before invoke any other python code just execute following python lines: import sys sys.path.append("C:\\source\\\\modules")
5,318,505
5,318,690
Using _DEBUG Preprocessor Defintion in Visual Studio 2008 - C++
I have a VC++ application written using Visual Studio 2008. For debug purposes, timeout values compile differently depending on the type of build (Debug or Release). The code sample below is typical of how I am trying to do this. #ifdef _DEBUG if ( (dwObjectWaitState = ::WaitForSingleObject( m_hValidMsgRxdEvent, INFI...
Something like this instead perhaps? #ifdef _DEBUG #define NONMS_WAIT_TIMEOUT INFINITE #else #define NONMS_WAIT_TIMEOUT BAS_THREE_SEC_TIMEOUT #endif if ( (dwObjectWaitState = ::WaitForSingleObject( m_hValidMsgRxdEvent, NONMS_WAIT_TIMEOUT)) != WAIT_OBJECT_0 ) { /* ... */ } Edit: Debug builds in VS should have _DEB...