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,162,784
5,162,801
'uint32_t' identifier not found error
I'm porting code from Linux C to Visual C++ for windows. Visual C++ doesn't know #include <stdint.h> so I commented it out. Later, I found a lot of those 'uint32_t': identifier not found errors. How can it be solved?
This type is defined in the C header <stdint.h> which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010. In the meantime, you could probably fake up your own version of the header by adding typedefs that map Microso...
5,162,858
5,162,881
What's an efficient way to avoid integer overflow converting an unsigned int to int in C++?
Is the following an efficient and problem free way to convert an unsigned int to an int in C++: #include <limits.h> void safeConvert(unsigned int passed) { int variable = static_cast<int>(passed % (INT_MAX+1)); ... } Or is there a better way? UPDATE As pointed out by James McNellis it is not undefined to as...
This should also work: int variable = passed & INT_MAX;
5,163,317
5,163,427
Compare/Copy COORD struct; overloading
This seems trivial yet endless searching doesn't yield an answer. I need to compare and assign. How can I overload the COORD if I can't add a member function or friend a function? is it just bad style to use this windows based structure? Also, I know I can write my own class(or just do the operation once for each membe...
COORD only has public members, so there's no need for friend functions -- free operators should suffice: bool operator <(COORD const& lhs, COORD const& rhs) { return lhs.Y < rhs.Y || lhs.Y == rhs.Y && lhs.X < rhs.X; } bool operator ==(COORD const& lhs, COORD const& rhs) { return lhs.X == rhs.X && lhs.Y == rhs....
5,163,492
5,163,528
Scope of using namespace
After running the following code segment, the output is Outer. Inner. Inner. I know this is about the usage of "namespace", but do not understand why the call of "Inner::message()" print out "Inner". Thanks for explanation. #include <iostream> using namespace std; namespace Outer { void message( ); nam...
This makes perfect sense. Your are using namespace Outer. Inside of namespace Outer you have two members... void message(); void Inner::message(); You explicitly scoped into Inner and called message there. Why would you expect otherwise? Had you not explicitly scoped into Inner, then it would have called void Outer::...
5,163,981
5,164,122
grouping / comparing the similar news stories together which are gathered from different sources
grouping / comparing the similar news stories together which are gathered from different sources using RSS feeds. Are there any API / Code available for this. Please help. Regards, Gourav
You're not likely to find anything that specific, but there are NLP libraries which have NLP capabilities which you can design your app around. See NLP programming tools using PHP? which accepted Solr as the recommended solution. You'll likely have more luck if you relax the language constraints: much more NLP of that ...
5,164,047
5,164,129
A C++ source code analyzer
Could you suggest some open source tools that analyze C++ code and checks the following rules: naming conventions, file inclusions, function design, data types, flow control, memory allocation, file handling, portable code, runs under Solaris or SUSE
http://www.google.com/search?q=misra+checker Of course, if the rules you're trying to enforce don't exactly match someone else's idea of a coding standard, no existing tool is going to work.
5,164,059
5,164,076
Why is .NET separate from the Windows Operating System?
Since .NET is so important to Windows, and Microsoft delivers both .NET and Windows, why doesn't Microsoft simply make .NET part of Windows?
.NET does come bundled with Windows; e.g., .NET 3.5 came with Windows 7. Of course, Microsoft needs to make it available as a separate download for older computers. Newer versions of .NET are released through Microsoft Update, so I'd say it's pretty well streamlined with the OS.
5,164,336
5,164,426
Efficiently editing Pixels in an Image
I have an 8bit Image (stored in an Array) containing black(0) and white(255) pixels. Say I want to change all Black pixels in the image to grey(say 120) pixels. What is the fastest way I can change Black to Grey. I thought of two approaches- Start checking every single pixel in the image. As soon as a black pixel is f...
Probably quicker to do it a word at a time (using word aligned accesses). You can just bitwise OR with 0x78787878 (assuming 32 bits). This will not affect white pixels but will set black pixels to the required value.
5,164,370
5,164,450
Tool to count the miss rate of assembly
I want to speed up the execution of my code cpp and thought of looking at cache misses maybe I could change locality. So is there any such a tool? that would tell me the miss rate of every insns in assembly Regards
Intel has such tools (VTune). valgrind is a free alternative. I seem to remember that IBM in the purify tools suite has also something for that.
5,164,538
5,166,834
How can I speed up line by line reading of an ASCII file? (C++)
Here's a bit of code that is a considerable bottleneck after doing some measuring: //----------------------------------------------------------------------------- // Construct dictionary hash set from dictionary file //----------------------------------------------------------------------------- void constructDictiona...
Quick profiling on my system (linux-2.6.37, gcc-4.5.2, compiled with -O3) shows that I/O is not the bottleneck. Whether using fscanf into a char array followed by dict.insert() or operator>> as in your exact code, it takes about the same time (155 - 160 ms to read a 240k word file). Replacing gcc's std::unordered_set w...
5,164,679
5,164,783
how to determine if a POINT is inside the area of a button
how to determine if a POINT is inside the area of a button? the POINT is in screen coordinates , and I have the handle of the window in which the button is and the handle of the button. I tried ::ScreenToClient(okBtnH , &tempPosition) where okBtnH is the handle of the button and the tempPosition is a POINT structure...
Are you sure that okBtnH is a handle for the button control, and not just its ID? If ScreenToClient is failing with "Invalid Handle" then your handle is likely invalid.
5,164,706
5,164,979
Error during QT Build with OpenSSL
1.Download source from OpenSSL (openssl-1.0.0d). 2.Build it static using this: > perl Configure VC-WIN32 no-asm --prefix=d:\Miatar\cpplibs\openssl > ms\do_ms > nmake -f ms\nt.mak > nmake -f ms\nt.mak install 3.Download qt-everywhere-opensource-src-4.7.1, patching it (QTDIR\mkspecs\win32-msvc2010\qmake.conf - /MD to /...
You have to add -L "path/to/dir/with/Gdi32library/" and -l Gdi32 params when you run configure. Example: configure -L "C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib/" -l Gdi32
5,165,020
5,165,221
IEEE float hex 424ce027 to float?
If I have a IEEE float hex 424ce027, how do I convert it to decimal? unsigned char ptr[] = {0x42,0x4c,0xe0,0x27}; how do ? float tmp = 51.218899;
Perhaps... float f = *reinterpret_cast<float*>(ptr); Although on my x86 machine here I had to also reverse the byte order of the character to get the value you wanted. std::reverse(ptr, ptr + 4); float f = *reinterpret_cast<float*>(ptr); You might want to use sizeof(float) instead of 4 or some other way to get the s...
5,165,024
5,167,029
AfxGetInstanceHandle() triggers an assertion failure
I am using MFC in my C++ program (using Visual Studio 2008). I have to call AfxGetInstanceHandle() at the begining of my program. This function triggers a break point: AFXWIN_INLINE HINSTANCE AFXAPI AfxGetInstanceHandle() { ASSERT(afxCurrentInstanceHandle != NULL); return afxCurrentInstanceHandle; } The ASSERT stateme...
If you are using MFC you shouldn't be providing a main, wmain, _tmain, or WinMain -- MFC provides its own entry point. Put initialisation code in InitInstance of your CWinApp derived class. If you don't have a CWinApp derived class you haven't created the project correctly -- use the Visual Studio Wizards for creating ...
5,165,119
5,165,269
Extension development using c/c++
I want to do more practice for c/c++ language, someone recommended me to develop extension for other software, which is supposed to be newbie friendly My first idea was extension(addon) for browsers, then I found that Opera/Firefox/Chrome all use javascript but not c/c++ for extension development. Anyone recommend soft...
While perhaps not the browser plugin you're lookng for, you could take a look at the Code::Blocks IDE as an example. It's a C++ written app using wxWidgets for it's GUI and has a C++ pluggable interface. There's not a great deal of plugins for it, so anything simple that can boost developer productivity would be useful...
5,165,123
5,165,467
Tracking modifications in a huge tree of objects
I develop a graphical editor in C++/Qt, that uses a tree of objects as its data model. The object's classes also form a class hierarchy. You can think of a tree of widgets in some kind of GUI framework, like Java Swing or Qt. Now I want to implement an undo/redo-functionality. Therefore I need to track every modificati...
The Command Pattern is one way to do it. However every modification to the data needs to be done via a Command object and logged by the undo system. It's the sort of thing that is best included from the beginning. It could be quite a pain to retrofit. If you can't intercept the modifications by the third-party code and...
5,165,627
5,167,528
'net start spooler' fails with exit code 2 when trying to restart the printer spooler on Windows
My application installs a virtual printer driver. On some users' systems I need to restart the printer spooler because functions like OpenPrinter return RPC_S_SERVER_UNAVAILABLE (text is "The RPC server is unavailable."), which means the spooler has stopped working. I try to do that by calling "net start spooler" with...
It seem that you interpret the ERRORLEVEL code 2 in the wrong way. It is not the code ERROR_NO_MORE_FILES. I started cmd.exe under the user account and received the following output C:>echo %errorlevel% 0 C:\Users\Rita>net stop spooler System error 5 has occurred. Access is denied. C:>echo %errorlevel% 2 Any exit c...
5,165,877
5,284,669
Whole program optimization failing in VC2008
I have a reasonably large C++ program (~11mb exe) compiled under VS2008 and was interested to see if whole program optimization would significantly affect its performance. However, turning on whole program optimization and link time code generation causes the link to fail as follows; 1>c:\cpp\Win32\Atlas\tin\TINDoc.Cp...
VC2008 is a fragile beast. The optimiser just doesn't work for some cases, and looks like you might possibly have one such case. Examples of "not working" include De-optimised code (slow!) Compiler or (more frequently) linker crashes Obscure compile/link error messages Incorrect code execution (this one is rare, but n...
5,165,935
5,235,474
QLibraryInfo doesn't seem to load qt.conf
I jsut installed Qt 4.7.2 and I'm trying to use the QLibraryInfo class. My problem is that QLibraryInfo::location(QLibraryInfo::PrefixPath) always returns C:\work3\qt-4.7-vs2010-x86 which doesn't exist on my generation machine (should be C:\Qt\qt-4.7.2). According to the documentation I tried to create a qt.conf file ...
A QCoreApplication must be created because that is how the QLibraryInfo is able to determine the application directory (QCoreApplication::applicationDirPath()) from which to load the qt.conf file. Alternatively, the qt.conf can be built into the application as a resource with the path ":/qt/etc/qt.conf".
5,166,264
5,166,356
Why does virtual inheritance need to be specified in the middle of a diamond hierarchy?
I have diamond hierarchy of classes: A / \ B C \ / D To avoid two copies of A in D, we need to use virtual inheritance at B and C. class A { }; class B: virtual public A {}; class C: virtual public A { }; class D: public B, public C { }; Question: Why does virtual inheri...
I'm not sure of the exact reason they chose to design virtual inheritance this way, but I believe the reason has to do with object layout. Suppose that C++ was designed in a way where to resolve the diamond problem, you would virtually inherit B and C in D rather than virtually inheriting A in B and C. Now, what would...
5,166,315
5,166,435
C++ - Timezone conversion
I've the following piece of code to find the difference between the UTC and local time zone. struct tm *local_time, *gmt_time; time_t t = time(NULL); local_time = localtime(&t); gmt_time = gmtime(&t); int y = mktime(local_time); int x = mktime(gmt_time); tzone_diff = y - x; This doesn't...
localtime and gmtime both returns a pointer to a struct tm. This struct tm is defined somewhere in the C library, and can easily be the same for both functions. Something like the below. struct tm temp; struct tm * gmtime() { ... return &temp; } struct tm * localtime() { ... return &temp; }
5,166,322
5,166,343
c/c++ (VS2008) enclose macro param in quotes
For a lot of function calls in a C app that needs some degree of debugging I wanted to add a macro to ease the typing that I had to do. right now I am calling a function like this: aDebugFunction(&ptrToFunction, __LINE__, "ptrToFunction", param1, param2, etc) So I thought lets write a macro that does the first 3 param...
You need to use the # convert token to string command of the preprocessor. You should define your second macro this way: #define SOMEDEFINE(x) &x, __LINE__, # x Or if x can also be a macro call, and you want the string to contains the expansion of the macro, you need to use an auxiliary macro: #define TOKEN_TO_STRING...
5,166,774
5,166,912
How to use functions exported from DLL in C++?
I create two projects in VC++ Express 2010, one is DLLTest, the other is CODETest. In DLLTest, declare and define a function func() as follows: __declspec(dllexport) void func() {...}; Build DLLTest project successfully, DLLTest.dll and DLLTest.lib files created. In CODETest, i want to use the exported function as fo...
This seems all pretty unlikely, especially the part where "func" transformed into "letterList". Nevertheless, you have to tell the linker to also link the import library of the DLL so that it can resolve identifiers that are imported from that DLL. The easiest way to do that in MSVC is: #include "DLLTest.h" #pragma c...
5,166,835
5,167,205
Creating "transposed" files with random characters
I want to create a program that creates ".txt" files with random characters, but with the possibility of creating transposed "files". Next, I add an example of two ".txt" files as I intend to do. FILE1 A|B|C|D|E|F|G| H|I|J|K|L|M|N| O|P|Q|R|S|T|U| V|W|Z|1|2|3|4| FILE2 (FILE1 transpossed) A|H|O|V| B|I|P|W| C|J|Q|Z|...
to create a transposed version of file1.txt, you'll have to keep its content in memory and visit that content in a transposed way. when you write if(myfileS.is_open()) srand(time(0)); you just conditionalize the srand of the fact that the file is open or not. Not what follows. I'd put braces around everything. the ...
5,167,066
5,167,216
sqlite global variable bug
I have a global variable named mob. When I print it the first time it is what I expect: 'Wolf'. But when I print it again in the end of main, it looks like 'до'. I debugged this code a lot and mob is global so I don't understand how it could be changed. I can add comments to part of the code if necessary. I'm using sql...
Mob::_name is a raw pointer and you set it to a string that is owned and managed by SQLite. When you try to output the string again SQLite has already reused that memory, so your program runs into undefined behavior and you see garbage printed. You should deep-copy the string - preferably by using std::string to store ...
5,167,275
5,178,041
Modal window from within message handler in WTL/Winapi
I have a small application that has a message only WTL window which does the background processing. But under some circumstances I would like to show a window that should behave as modal, that is, the message handler of message only window should not return until the user has clicked the button. I was thinking that I c...
I would like to show a window that should behave as modal ... In my Unusual but Useful Dialog-based Classes Designed for Specialization you will find the way to call DoModal() on any control or homemade window.
5,167,338
5,170,045
Organizing my own external libraries in revision control
I want to set up a SVN repository to "revision-control" my projects. Currently my workspace looks like this, and I intend to keep it like that: \workspace \myPrj1 \myPrj2 \myLibBase \myLibA \myLibB myPrj1 is using myLibBase and myLibA. myPrj2 is using myLibBase and myLibB. I will have more Projects com...
Seems this is what you're looking for: Externals Excerpt: "Sometimes it is useful to construct a working copy that is made out of a number of different checkouts. For example, you may want different subdirectories to come from different locations in a repository or perhaps from different repositories altogether. You co...
5,167,575
5,168,164
Passing file-path string to semantic action in Boost.Spirit
I am new to Boost.Spirit, and I have a question related to a mini-interpreter I am trying to implement using the library. As a sub-task of parsing my language, I need to extract a file-path from an input of the form: "path = \"/path/to/file\"" and pass it as a string (without quotes) to a semantic action. I wrote some...
Almost everything is fine with your parser. The problem is a bug in Spirit (upto Boost V1.46) preventing the correct handling of the attribute in cases like this. This has been recently fixed in SVN and will be available in Boost V1.47 (I tried running your unchanged program with this version and everything works just ...
5,167,625
5,167,799
Splitting a C++ std::string using tokens, e.g. ";"
Possible Duplicate: How to split a string in C++? Best way to split a string in C++? The string can be assumed to be composed of words separated by ; From our guide lines point of view C string functions are not allowed and also Boost is also not allowed to use because of security conecerns open source is not allowe...
I find std::getline() is often the simplest. The optional delimiter parameter means it's not just for reading "lines": #include <sstream> #include <iostream> #include <vector> using namespace std; int main() { vector<string> strings; istringstream f("denmark;sweden;india;us"); string s; while (get...
5,167,656
6,572,148
Error message "error: stray '\302' in program"
I'm using Code::Blocks on Ubuntu 10.10 (Maverick Meerkat). I have connected a Mac keyboard and set the keyboard settings to "Swiss German Mac". Now whenever I write an equals sign, followed by a space (something like width = 100) I get the error message: stray '\302' in program. I know this error means that there is a ...
Since you're sure it's caused by hitting Shift + Space, you can check what X itself is doing by. First, run xev from the command line, hit Shift + Space and check the output. For example, I see: $ xev KeyPress event, serial 29, synthetic NO, window 0x2000001, root 0x3a, subw 0x0, time 4114211795, (-576,-249), root...
5,168,076
5,168,260
Linker error:1112 module machine type 'X86' conflicts with target machine type 'IA64'
Iam getting the following linker error while building an atl com dll which is targeted to IA64 using a makefile on an XP platform.. 1>atls.lib(atlcommodule.obj) : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'IA64' 1>NMAKE : fatal error U1077: '"E:\Program Files\Microsoft Visual Stu...
Hard to say where in this particular case the error is coming from, but usually it means that you are trying to link to libs compiled for a different target architecture than your code is. You say you want to generate IA64 code, but something is compiled for x86 (probably the libs)
5,168,242
5,170,746
Library include paths with same header name
What is the best method to include a file that has same name in another folder from additional include directories? Example: lib1/include/foo.h lib2/include/foo.h where both lib1/include and lib2/include are added in additional include directories. Edit: The libs are from different SDK's and every developer installs th...
First off, this answer assumes that the include guards for the two headers are compatible (i.e. not the same symbols). One thing you can do is create links in known locations to the header files of interest, giving the links themselves distinct names. For example, say your two libraries are installed at $LIB1PATH and $...
5,168,372
5,169,080
how to interrupt a thread which is waiting on recv function?
I have a socket listener which hangs on recv function: size_t recvLen = recv(sock, buf, 512, 0); I would like to terminate this thread with interrupting it. MSDN says: When issuing a blocking Winsock call such as recv, Winsock may need to wait for a network event before the call can complete. Winsock performs a...
You can interrupt it by queuing an APC to it via QueueUserAPC. However, it's most likely unsafe to terminate the thread in the APC. Queuing an APC doesn't end the recv, it just interrupts it; once the APC returns, it will go back to waiting on recv again. If you want to stop the recv completely, you should be using sel...
5,168,499
5,168,579
Unmanaged DLL project and managed WinForms application in one solution
I am using Visual Studio 2008 Professional, and I need to create solution with two projects. One project is managed WinForms C# project, second is unmanaged DLL C++ project. I created them in VS2008 and in unmanaged DLL project I exported simple function which returns some int. In managed WinForms project I imported D...
You should add dll copy to post build event. See Project properties>Build events>Post build event command line.
5,168,511
5,168,556
message to show hide a window
is there a message that I can send to a window that will have the same effect as ShowWindow(SW_SHOW) or ShowWindow(SW_HIDE)
Is there a message that I can send to a window that will have the same effect as ShowWindow(SW_SHOW) or ShowWindow(SW_HIDE)? No.
5,168,626
5,174,181
Does Google Mock count calls to mocked functions in destructor?
Does Google Mock count calls to mocked functions that occur in the destructor of the object under test?
Yes! I tested this and indeed calls to mocked functions within the destructor do count, i.e. you should EXPECT_CALL() them...
5,168,670
5,168,710
Splitting a string into integers using istringstream in C++
I'm trying to use istringstream to split a simple string into a series of integers: #include <string> #include <iostream> #include <sstream> #include <vector> using namespace std; int main(){ string s = "1 2 3"; istringstream iss(s); while (iss) { int n; iss >> n; cout <<...
It's coming out twice because your looping is wrong, as explained (indirectly) at http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5 (while (iss) is not dissimilar from while (iss.eof()) in this scenario). Specifically, on the third loop iteration, iss >> n succeeds and gets your 3, and leaves the stream ...
5,168,676
5,171,434
Need Convert Binary file to Txt file
I have a dat(binary) file but i wish to convert this file into Ascii (txt) file using c++ but i am very new in c++ programming.so I juct opend my 2 files:myBinaryfile and myTxtFile but I don't know how to read data from that dat file and then how to write those data into new txt file.so i want to write a c+ codes that ...
Very easy: Create target or destination file (a.k.a. open). Open source file in binary mode, which prevents OS from translating the content. Read an octet (byte) from source file; unsigned char is a good variable type for this. Write the octet to the destination using your favorite conversion, hex, decimal, etc. Repea...
5,168,680
5,169,189
Questions re: assembly generated from my C++ by gcc
Compiling this code: int main () { return 0; } using: gcc -S filename.cpp ...generates this assembly: .file "heloworld.cpp" .text .globl main .type main, @function main: .LFB0: .cfi_startproc .cfi_personality 0x0,__gxx_personality_v0 pushl %ebp .cfi_def_cfa_offset 8 mov...
As other have said, .file, .text, ... are assembler directives and .LFB0, .LFE0 are local labels. The only instruction in the generated code are: pushl %ebp movl %esp, %ebp movl $0, %eax popl %ebp ret The first two instruction are the function prologue. The frame pointer is stored on the stack and updated. ...
5,168,697
5,168,822
template to return specific type
I have a template function that I wish to return either the type of T or a variant. I tried to do as follows, however the compiler complains it cannot convert 'variant' to int (where I use this function with T=int). How should I implement this so I can either just return the variant or the type contain in the variant....
You can create a template specialisation for find_attribute<boost::variant>(const std::string& attribute) that return a variant and a normal version attribute<T>(const std::string& attribute). The normal version would do: return boost::get<T>(find_attribute<variant>(attribute)); But remeber that template are evaluate...
5,168,981
5,169,088
What good are public variables then?
I'm a total newbie with tons of ?'s in my mind and a lot to experience with C++ yet! There's been something which I find really confusing and it's the use of public variables, I've seen tons of code like this: class Foo { private: int m_somePrivateVar; public: void setThatPrivateVar (int const & new_val) { ...
By hiding the variable and adding methods now, the class designer allows for inserting arbitrary code into those methods in the future without breaking tons of code that use the attributes directly. Also note that providing a lot of accessor/mutator methods is generally a sign that your class design needs another look ...
5,169,313
5,169,551
Need to find the difference between two XML files in C++
Is there any library for this, or does anyone have anything done in Xerces, or any link on how to do this, or any API or any way to do this in Xerces?
I don't think Xerces includes an XML diff algorithm. If you want to implement it yourself, check out this thesis and the accompanying Java code.
5,169,439
5,170,750
Detect when Windows rebooted after crash or powerfailure
Do anyone know if its possible to detect if the last boot up was preceded by a power-failure in Windows ? My reason for wanting to detect this is to know when to re-scan files I frequently modify on disk with my service. If there is a normal startup, I can be quite sure that the shutdown went smooth and the data that ...
As a simple implementation, would CreateFile with FILE_FLAG_DELETE_ON_CLOSE (immdediately followed by FlushFileBuffers just to be sure) not work? If the system shuts down cleanly, your application will exit and the file handle will be closed, so the OS will delete the file. If power fails or the world ends, the OS does...
5,169,558
5,170,197
C++'s out parameter object creation and JNA
Disclaimer: I ignore pretty much everything about C++, so I hope I'm not saying stupid things here, if I am, please feel free to correct me. As a Java developer, when I want to create a new object, I use a constructor method that will allocate this object in memory and return a handle on it for me, and I will store thi...
As I don't have any idea on what a Foo is, or what the Foo structure contains, I'm just going to create a JNA PointerType to declare my structure This makes it impossible to allocate memory for Foo, as you have to know how much memory you need to allocate. For c structures jna needs a java class mirroring the structu...
5,170,571
5,170,925
Showing an image using OpenCV 2.2 on a Linux Ubuntu platform with Qt
I'm using Qt as my C++ IDE platform over Ubuntu 10.10 with OpenCV 2.2. I'll just write pieces of code and show where the problem is: #include "opencv2/highgui/highgui.hpp" using namespace cv; int main(int argc, char *argv[]) { VideoCapture cap = VideoCapture(0); Mat frame; do { cap >> f...
Your problem is with Qt handling its own event loop and thus the event loop of OpenCV is starved and never get run. The way to get them to work together is quite simple: Display your OpenCV as a QPixmap (by convert your image to QImage then use QLabel to display it). Then add this QLabel to your QWidget. Your QWidget c...
5,170,670
5,170,719
include tr1::shared_ptr
I have included #include </usr/include/c++/4.4.3/tr1/shared_ptr.h> in my class file, When I attempt to compile my class I get below error: > In file included from account.h:16:0: /usr/include/c++/4.4.3/tr1/shared_ptr.h:61:46: error: '_Lock_policy' has not been declared /usr/include/c++/4.4.3/tr1/shared_ptr.h:63:30: er...
I have added #include <tr1/memory> and has sorted the issue.
5,170,736
5,170,829
Referencing elements from two-dimensional array with a single value
I am probably missing something fundamental, but i cannot find a solution to the following issue. I have a two-dimensional array of some float elements and i am trying to find a way to be able to reference them by using only a single value. Example: float test[5][50]; test[3][25] = 34.67; cout << test[3][25] << endl; i...
Without testing, I think something like this might work. Note that C++ arrays are major->minor from left dimension to right dimension. float test[5][50]; test[3][25] = 34.67; cout << test[3][25] << endl; int id = 25; float* test2 = &test[0][0] cout << test2[(3 * 50) + id] << endl;
5,170,995
5,171,532
Does a compiler collapse classes which are identical in their structure?
I hope this isn't a duplicate of a question itself, but the search terms are so ambiguous, I can't think of anything better. Say we have two classes: class FloatRect { float x,y,width,height; }; and somewhere else class FloatBox { float top,left,bottom,right; }; From a practical standpoint, they're the same, so doe...
This is completely implementation specific. For example I can use CLang / LLVM to illustrate both point of view at once: CLang is the C++ front-end, it uses two distinct types to resolve function calls etc... and treats them as completely different values LLVM is the optimizer backend, it doesn't care (yet) about name...
5,171,089
5,171,203
When do you need to use #include in c++
I've been programming for awhile now and one thing I've still never quite figured out is exactly when you need to #include something. I know to be safe you can do it whenever you use something declared in another file. However at times I find that I can remove an #include and everything will still compile just fine. Fr...
There is nothing much to it. If you use something, you have to include the header declaring the thing you use. About the only exception is forward declaring a class/struct or method like: class myclass; if you just need to declare a pointer or reference to the class. You cannot really rely on other headers includin...
5,171,221
5,260,132
C++ n-ary tree library
What is the most complete n-ary tree implementation for C++ ? I need a simple (not boost BGL please) implementation to use in a project compatible with LGPL, so the Tree.hh desn't fit.
What I have discovered from this question, is that there is no simple, documented, LGPL compatible Tree library which compares to GLib n-ary Tree implementation. In the end, I used the C API from the GLib.
5,171,502
5,171,821
.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx
Possible Duplicates: *.h or *.hpp for your class definitions Correct C++ code file extension? .cc vs .cpp I used to think that it used to be that: .h files are header files for C and C++, and usually only contain declarations. .c files are C source code. .cpp files are C++ source code (which can also be C source cod...
Historically, the first extensions used for C++ were .c and .h, exactly like for C. This caused practical problems, especially the .c which didn't allow build systems to easily differentiate C++ and C files. Unix, on which C++ has been developed, has case sensitive file systems. So some used .C for C++ files. Other ...
5,171,516
5,171,693
where is a good tutorial on creating an R package with C++ source code?
I'm at a loss when I start looking at configure scripts. I'm not sure how to go about creating an R package which has several functions built from C/C++ in such a way that it's portable between Windows & Linux. My attempts to modify the guts of existing packages have been unfruitful. Any help or links would be greatl...
I was also quite lost when writing my first package with compiled code. Here are a few tips, but there is probably better material out there. The main piece about writing R packages is "Writing R extensions". This is a very complete guide, but that also makes it abit hard to read through: http://cran.r-project.org/doc/...
5,171,529
5,171,679
Overloading operator<<
I'm making a simple class that uses operator<<. It will store two parallel arrays of data, each with a different (but already-known) datatype. The idea is that the final interface will look something like this: MyInstance << "First text" << 1 << "Second text" << 2 << "Third text" << 3; Which would make the arrays lo...
The reason ostream operators return a reference to the ostream, and the reason it somewhat helped your case to return a reference to MyClass is that an expression like A << B << C is always interpreted like (A << B) << C. That is, whatever the first overloaded operator returns becomes the left-hand side of the next op...
5,171,739
5,171,750
toString override in C++
In Java, when a class overrides .toString() and you do System.out.println() it will use that. class MyObj { public String toString() { return "Hi"; } } ... x = new MyObj(); System.out.println(x); // prints Hi How can I accomplish that in C++, so that: Object x = new Object(); std::cout << *x << endl; Will output ...
std::ostream & operator<<(std::ostream & Str, Object const & v) { // print something from v to str, e.g: Str << v.getX(); return Str; } If you write this in a header file, remember to mark the function inline: inline std::ostream & operator<<(... (See the C++ Super-FAQ for why.)
5,171,787
5,225,298
Distorting an image using a height map?
I have a height map for an image, which tells me the offset of each pixel in the Z direction. My goal is to flatten a distorted image using only it's height map. How would I go about doing this? I know the position of the camera, if that helps. To do this, I was thinking about assuming that each pixel was a point on a...
I ended up implementing my own solution: for x in xrange(cv.GetSize(image)[0]): for y in xrange(cv.GetSize(image)[1]): a = Point(x, y, heights_top[x / 2] * (cv.GetSize(image)[1] - y) + heights_bottom[x / 2] * y) b = Point() d.x = costy * (sintz * (a.y - c.y) + costz * (a.x - c.x)) - sinty * (a.z - c.z) ...
5,172,157
6,806,916
Intellisense in vs2010 with c++
I can't get intellisense to work. Even if I start with an empty project and add just one file to it with only an include for iostream and an int main() function that prints a char with cout (basically the most basic program), if I try to get intellisense to show anything (say by typing cout.) I get IntelliSense: 'No a...
I got it solved by the Microsoft team at http://connect.microsoft.com/VisualStudio/feedback/details/652838/intellisense-not-creating-ipch-folder It had to do with a certain Windows Update installed on WinXP. The solution was to install VS2010_SP1 and then a certain update over it.
5,172,231
5,182,627
Default template arguments
I am testing out a property system and I want to make sure that the root class can hold function pointers to the most derived class that there is. As a result I have something that is sort of working. The most derived class is currently working (RC2), but the current middle class (RC1) will have a compiler error. I wan...
If you can use boost then you might be able to do a cleaner approach using boost::function and boost::bind to get the pointers you want. template <typename BC> class RBase : public BC { public: typedef int FunctionSignature (void) const; typedef boost::function<FunctionSignature> Callbac...
5,172,336
5,172,360
Simple way to draw shapes in c++?
Are there any drawing libraries out there that are really simple? I literally mean functions such as "draw_circle(screen,x,y,r,colour)" or something similar. I've taken a look at SDL but it doesn't support what I want out of the box - I would like something that is really easy to use straight away, if possible.
Probably Allegro5. It's easy and great for beginners. You can simply draw shapes and sprites. Allegro5 Website
5,172,435
5,172,946
Overload C/C++ preprocessor macro on structure of its argument
I would like to write a preprocessor macro that does one thing if it's argument is a parenthesized tuple of tokens, like this: MY_MACRO((x, y)) and something else if it's just a single token, like this: MY_MACRO(x) Is that possible? How about distinguishing between the number of space-separated tokens, i.e. between M...
As for your first question, the following macros might meet your purpose: #define CONCAT_( x, y ) x ## y #define CONCAT( x, y ) CONCAT_( x, y ) #define IS_SINGLE_1(...) 0 #define IGNORE(...) #define IS_SINGLE_2_0 0 IGNORE( #define IS_SINGLE_2_IS_SINGLE_1 1 IGNORE( #define IS_SINGLE( x ) CONCAT( IS_SINGLE_2_, ...
5,172,458
5,172,524
Getting debug symbols on UNIX
On windows we can get the debug symbols using the dbgHelp library. How can we do it on UNIX/linux (with c++)? thanks :)
This is dependent on exactly which Unix version or Linux distribution you are using. For Debian and Debian derived distributions such as Ubuntu you need to install the debug packages using your normal package manager. Fedora uses debuginfo rpms to add the debugging symbols. For other systems I'm afraid you'll have to ...
5,172,854
5,172,873
Creating an object on the heap without new
In C++, is it possible to create an object on the heap without using new or malloc ? I think if I use an STL container like a vector it will be put on the heap. If I do: vector<Object> listObjs = vector<Object>(); Object x = Object(...); ... listObjs.push_back(x); Where do the Objects created here reside?
The object denoted by x resides on the stack. vector::push_back will copy it to the heap. The allocator object inside the vector will probably be implemented using new or malloc, although it is possible that it uses another, low-level API. For instance, both Unix and Windows offer memory mapping APIs, which in turn may...
5,173,432
5,173,473
C++ Is the copy constructor called here?
Suppose you have a functions like this: Foo foo() { Foo foo; // more lines of code return foo; // is the copy constructor called here? } Foo bar() { // more lines of code return Foo(); // is the copy constructor called here? } int main() { Foo a = foo(); Foo b = bar(); } When any of the functions ...
It might be called, or it might not be called. The compiler has the option of using the Return Value Optimization in both cases (though the optimization is a bit easier in bar than in foo). Even if RVO eliminates the actual calls to the copy constructor, the copy constructor must still be defined and accessible.
5,173,498
5,173,539
Why does ofstream insert a 0x0D byte before 0x0A?
I'm outputing an array of unsigned characters in C++ using ofstream fout("filename"); but it produces a spurious character in between. This is the part of the code that makes the problem: for(int i = 0; i < 12; i++) fout << DChuffTable[i]; and this is the definition of the array: unsigned char DChuffTable[12] = {0x00,...
Your stream is opening in text mode, and since 0x0A is the line feed (LF) character, that's being converted by your stream to 0x0D 0x0A, i.e. CR/LF. Open your stream in binary mode: std::ofstream fout("filename", std::ios_base::out | std::ios_base::binary); Then line ending conversions should not be performed. This is...
5,173,618
5,173,704
Externalize rendering of polymorphic objects
Let's say we have a classical polymorphic architecture : class Animal { virtual void eat() = 0; }; class Frog : public Animal { virtual void eat() { ... } }; class Chipmunk : public Animal { virtual void eat() { ... } }; This is fine. But when it comes to rendering, I could add a virtual render method to...
Have a look at the Visitor Pattern - The virtual render() function is passed an instance of a Visitor, and then calls Visitor.renderMe(this). Visitor then overloads renderMe as needed and contains the rendering specific code.
5,174,115
5,174,694
Sorting a vector of objects by a property of the object
I'm working on a project for school and need to sort some data. I've been given a vector of objects and I have to sort the objects (either in place or using an index) based on one of their properties. There are several different objects and several different properties that could it be sorted by. What's the best way to...
There are several different objects and several different properties that could it be sorted by. While the solution Erik posted is correct, this statement leads me to think that it's impractical at best if you are in fact planning to sort by multiple public data members of multiple classes in multiple ways in the sam...
5,174,385
5,174,780
Qt Socket blocking functions required to run in QThread where created. Any way past this?
The title is very cryptic, so here goes! I am writing a client that behaves in a very synchronous manner. Due to the design of the protocol and the server, everything has to happen sequentially (send request, wait for reply, service reply etc.), so I am using blocking sockets. Here is where Qt comes in. In my applicati...
I'm assuming that you're using QThread for the threading operations. If so, you can either a) use queued signal-slot connections; or b) explicitly use the QThread's event loop by creating a custom event type, posting that event in your scripting engine, and then having the client class handle those events. example for ...
5,174,428
5,176,056
How to change QGLFormat for an existing QGLWidget at runtime?
In my application, the user may change the properties of the OpenGL format (i.e. double buffering, multisampling, depth of various buffers, ...). For now, there is only one QGLWidget in my application, and if the user changes anything, I destroy and recreate the widget. Now, I would like to have more than one widget. S...
This may work: QGLFormat newFormat; newFormat.setDoubleBuffer(true); // ... theGLWidget->context().setFormat(newFormat); Edit: You can also call QGLWidget::setFormat directly, but it's obsolete and may not always work. I think it's safer to recreate the widget. Here's how: Put your GL widget in a sublayout (any kind -...
5,174,462
5,174,489
what is the best way to pass arguments to thread in C windows?
Hi I have a thread that uses couple of variables. variables are determined in runtime from argv[]. My options as i see them: make the variables global so the threads can use them (don't need to protect them since the thread doesn't change them). i'm reluctant to use this since global variables are not so good create a...
it would be a "forced" struct with no meaning other than argument for the thread That sounds like a pretty good use for a struct. The data members are all related by virtue of the fact that they all need to be passed to the thread. It's not really more complicated than the first option (unless one considers defining...
5,174,593
5,174,602
What does ^= mean in C/C++?
I have the following line of code: contents[pos++] ^= key[shift++]; What does operator ^= mean?
It is the XOR assignment operator. Basically: x ^= y; is the same as: x = x ^ y;
5,174,725
5,174,827
How do you explain C++ pointers to a C#/Java developer?
I am a C#/Java developer trying to learn C++. As I try to learn the concept of pointers, I am struck with the thought that I must have dealt with this concept before. How can pointers be explained using only concepts that are familiar to a .NET or Java developer? Have I really never dealt with this, is it just hidde...
Java objects in C++ A Java object is the equivalent of a C++ shared pointer. A C++ pointer is like a Java object without the garbage collection built in. C++ objects. C++ has three ways of allocating objects: Static Storage Duration objects. These are created at startup (before main) and die after main exits. There a...
5,175,057
5,175,096
error expected ';' before instance
Quick overview of how I got to this. Created the structure Created the .cpp file Used CMake to create Make file Ran Make and received error I'm trying to compile the following code: #include <iostream> using namespace std; enum UnitType { Meter, Inch }; class Meter { double value; public: Meter(doub...
enum UnitType { Meter, Inch }; Here you've defined Meter as a enumeration value. class Meter { ...but here (at the same scope) you're trying to re-define it as the name of a class. That's legal, but to make use of it later, you have to use class Meter, instead of just Meter: class Meter meter(1.0); IMO, even though ...
5,175,256
5,175,284
Array Initialization
I am trying to assign values within an array within the condition of a for loop: #include <iostream> using namespace std; int* c; int n; int main() { scanf("%d", &n); c = new int[n]; for (int i = 0; i < n; c[i] = i++ ) { printf("%d \n", c[i]); } return 0; } However, I am not obtaining ...
The value of the expression ++i is the value after i has been incremented. So if it started at 0, you assign value 1 the first time and so on. You can see where the value got assigned, but asking why it got assigned there opens a can of worms. Using i in an expression where i is modified via i++ or ++i is undefined beh...
5,175,325
5,184,434
Crash when running application due to existence of unexecuted code in source file - c++
I'm working on a pretty tricky problem that I've been on for literally a week now. I've hit a very hard wall and my forehead hurts from banging it so I'm hoping someone can help me out. I am using Visual Studio 2005 for this project - I have 2008 installed but was running into similar issues when I tried it. We have an...
ARGH! Solution figured out. In our solution we had defined _SECURE_SCL = 0, but in the 3rd party libs we had build, that was undefined (which means = 1). Setting _SECURE_SCL to 0 supposedly reduces runtimes drastically, but it has to be done the same across all included libs otherwise they will treat array sizes differ...
5,175,344
5,175,483
Nested Dictionary/Array in C++
Everybody, I am a Python/C# guy and I am trying to learn C++. In Python I used to do things like: myRoutes = {0:[1,2,3], 1:[[1,2],[3,4]], 2:[[1,2,3],[[1,2,3],[1,2,3]],[4]]} Basically when you have arrays of variable length and you don't want to wast a 2D matrix for them, nesting arrays into a dictionary to keep track o...
Many of us share the pain you're experiencing right now but there are solutions to them. One of those solutions is the Boost library (it's like the 2nd standard library of C++.) There's quite a few collection libraries. In your case I'd use Boost::Multi-Dimentional Arrays. Looks like this: boost::multi_array<double,...
5,175,414
5,175,429
C++ members available after deletion?
I compiled & ran the code pasted below and surprisingly it worked without errors. (g++/linux) How can a deleted object have some members still available ? Is it a normal behaviour ? #include <iostream> using namespace std; class chair { public: int height; int x; int y; chair() { before =...
What you are doing is undefined behavior you are accessing a deleted object. The data you are looking at is still available and the area of memory where that information is stored hasn't been overridden yet but nothing is stopping that from happening.
5,175,498
5,175,773
Does the Euler sequence of axis interfere in a Quaternion result
This is a thing that puzzles me. I know that when you use Euler angles and apply rotations to objects you have to stick to one axis sequence, for example, XYZ, in order to avoid gimbal lock. My question is the reverse. Imagine I have quaternions that I want to convert to Euler angles. So, I take all those quaternions a...
I know that when you use Euler angles and apply rotations to objects you have to stick to one axis sequence, for example, XYZ, in order to avoid gimbal lock. That's not entirely right. Not only do you have to stick with a particular axis sequence, you also have to stick with a particular reference frame for t...
5,175,628
5,175,833
How to overlay text on image when working with cv::Mat type
I am using opencv 2.1. In my code I have a few images stored as Mat objects initialized like this: Mat img1 = imread("img/stuff.pgm", CV_LOAD_IMAGE_GRAYSCALE); I can display them properly using imshow() after my matrix operations are done. Now I want to add some text on the image to describe what has happened. Looking...
I was looking at the wrong place. I found the answer in the newer OpenCV documentation for cpp. There is a new function called putText() that accepts cv::Mat objects. So I tried this line and it works: putText(result, "Differencing the two images.", cvPoint(30,30), FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(200,200...
5,175,650
5,175,695
Structure C++ , dynamic names construction
I have constructed a struct in a C++ class, Lets sat it is called Task I would like to initiate a new constructed based on an index that might change every time I run the program, for example for ( i=1; i<=index,++i){ Task ai; } this way after the loop I would like to have structures named a1, a2, a3 ,a4,...an How ...
As mentioned you could use an std::vector<Task>, although I would probably just use a dynamically allocated array: Task* tasks = new Task[index]; task[0] ... task[1] ... delete[] tasks;
5,175,723
5,175,793
c++ compiling: error: expected constructor, destructor or type conversion before '*'
I have been doing some research about this and have found a few similar questions on stackoverflow talking about the visibility of types, but this doesn't seem to be exactly the same problem (or at least that's what I think after some hours working on it). Let's focus: The problem C++ compiler reports "abc.cpp:132: err...
A qualified type name that includes template parameters must be prefixed with the keyword typename : typename ABC<C, I>::Node * You can read more about about the necessity of this typename keyword here.
5,175,831
5,175,888
Why is this IO operation looping infinitely?
I am trying to read from a text file and tokenize the input. I was getting a segmentation fault until I realized I forgot to close my ifstream. I added the close call and now it loops infinitely. I'm just trying to learn how to use strtok for now, that is why the code doesn't really look complete. void loadInstruction...
This while(input.good()); is probably not what you intended...
5,175,841
5,175,856
error in c++ main file int expression
I am making a new program in c++ i get the current error expected primary-expression before ‘int’ about this line p1::pascals_triangle(int depth); My code is: this is my functions.cpp using namespace std; /** * Note the namespace qualifi...
p1 needs to be an existing namespace or class name. If that does not solve the problem you will have to give some surrounding code to make sense of your question ;) Good luck.
5,176,012
5,176,852
When would I use bad_typeid?
When exactly would a bad_typeid exception be used?
This type of exception generally wouldn't be used. Instead, it only exists so that you can recognize it. If a tester or user sends you a crash report that mentions bad_typeid, you'll know what sort of bug to look for when you start debugging. You're not really meant to throw this exception yourself, and I don't think y...
5,176,096
5,176,255
Cannot access file in Network Attached Storage (NAS) by using C++ access() function?
I have an Isilon NAS in 10.20.30.11 for example, and I mounted it like following: mount 10.20.30.11:/folder /content I could use ls command to find the file in folder or /content. Its mod is 777. bash-3.00# ls -l /content/a/b/1.txt total 344131 rwxrwxrwx 1 1005 65533 140750 Feb 28 00:58 1.txt But I cannot ...
From the Linux man pages. access() may not work correctly on NFS file systems with UID mapping enabled, because UID mapping is done on the server and hidden from the client, which checks permissions.
5,176,249
5,176,267
Defining operator<< Inside Class
Consider the following code: class MyClass { template <typename Datatype> friend MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData); // ... }; template <typename Datatype> MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData) { // ... } How can I define operator<< inside the...
You have template <typename Datatype> MyClass& operator<<(MyClass& MyClassReference, Datatype SomeData); inside of the class. It is a method of the class MyClass. Non-static methods have an implicit parameter called the this pointer. The this pointer is a pointer to the object the method was called on. You do not need...
5,176,278
5,176,321
write text file with simultaneous random access and append
The following piece of code tries to overwrite to different locations in a file and also to append to the file. However, it does not seem to work. I have tried several modes and the result is either overwriting or simply appending everything to the end of the file but not both together. Is it possible to do such a thin...
If you specify ios::app when you open the file all writes will always go to the end of the file -- it's basically as if every write was preceded by f.seekp(ios::end). It sounds like what you want is ios::ate instead. This will seek to the end of the file immediately after it's opened, but when/if you seek to somewhere ...
5,176,496
5,176,534
istream and ostream problem - C++
I am using two compilers g++ and Dev - C++. when I compile my program on Dev-C++ it compiles perfectly. but when i try to compile it on g++ it gives me two errors: In file included from a2test.cpp:27: ----.h:25: error: 'ostream' has not been declared ----.h:26: error: 'istream' has not been declared Can anyone tell m...
Make sure you include fstream. Also, put "std::" before ostream or put "using namespace std" somewhere. It would help if you posted the code, as right now I'm just guessing based on common mistakes. I would guess you forgot to include fstream because different compilers may use different header files and it may be the ...
5,176,768
5,176,796
Help with first C++ class/pointers
Hey guys, I taught myself PHP a few years back and am now in college and am relatively well versed in Java (and by that I really mean I'm a beginner but did my data structures course in it. I'll be taking Algorithms next semester) In any case...I want to learn C++ and stumbled upon this: http://newdata.box.sk/bx/c/ Wha...
You didn't allocate memory locations to point to for num, twice,owner. So, in your constructor - Number(int our_num, string me) { num = new int; twice = new int; owner = new string; *num = our_num; *twice = 2 * (*num); *owner = me; } Since, the class is managing resources, class Number should...
5,177,046
5,178,489
How to use precompiled headers efficiently (using /Yc and Yu options)?
We are using Visual Studio 2003 (VC71) for compilation. In order to reduce the compile time we changed the build script such that it generates the precompiled header (.pch) file for each CPP file. The option used in makefile: /Yc"StdAfx.h" /Fp"StdAfx.pch" With this the compile time for the target got reduced by 30%. B...
The problem Let's say you have a list of headers you use that you know won't change. For example, the C headers, or the C++ headers, or Boost headers, etc.. Reading them for each CPP file compilation takes time, and this is not productive time as the compiler is reading the same headers, again and again, and producing ...
5,177,119
5,177,199
Can I speed up callbacks from C++ Dll to C#?
We've implemented our main code functionality in a C++ Dll then written a C# UI on top. This works fine most of the time, but in areas where we want the UI to report the progress of a function in C++ we're having some performance problems. We pass a pointer to a C# function down to the Dll to use for progress updates. ...
You can use BeginInvoke instead of Invoke. Invoke waits for the function to return, while BeginInvoke allows the function to run parallel to the current thread.
5,177,167
5,177,289
Why does my C++ compiler allow recursive calls to main?
Possible Duplicate: Is it legal to recurse into main() in C++? #include <iostream> using namespace std; int main() { static int var = 5; std::cout << --var; if(var) main(); } gcc compiles the code http://ideone.com/lIp3A . I know that main cannot be used inside main in C++. How come this code compiles?
The code is ill-formed because it violates the shall construct of §3.6.1.3 §3.6.1.3 says : The function main shall not be used within a program. The shall construct A diagnosable rule is defined as (§1.4.1): The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard exc...
5,177,951
5,177,973
How do I recursively access different classes?
I want to have a set of interchangeable classes to perform operations on a dataset. I "think" what I'm trying to do is called Polymorphism but I'm unsure. This is an example of what I'm trying to do. I want to create an object which contains the initial values, then initialize another class to use the data in the first...
Your description sounds like you might want to check the following design pattern: Chain of Responsibility. I'd probably come up with something like this: command interface / abstract base class with public method exec (non-virtual!) that calls a protected abstract virtual method execLocal that implements the behavio...
5,177,963
5,178,300
adding filtering functionality on-the-fly in c++
I have the following (simplified) architecture: client(s) --> bouncer --> server The clients send commands to the server. The 'bouncer' performs sanity and other checks on the commands issued by the client, and prevents faulty commands from reaching the server. For example, the bouncer may have the following code: bool...
Choices include: create an interpretive environment, communicate the testable aspects of the incoming message to it, and load some predicate expression/function from your config to be evaluated embed a language (e.g. LUA, ruby) download any of many simpler expression evaluation libraries create your own (perhaps usin...
5,178,031
5,322,369
Using different incompatible versions of a CORBA Interface in the same app/module?
Given two IDL definitions: (I'm only implementing a client, the server side is fixed.) // Version 1.2 module Server { interface IObject { void Foo1(); void Foo2() raises(EFail); string Foo3(); // ... } }; // Version 2.3 module Server { interface IObject { // no longer available: void Foo1(); ...
(Adding answer from one Stefan Gustafsson, posted in comp.object.corba 2011-03-08) If you look at it as a C++ problem instead of a CORBA problem, the solution is C++ namespaces. You could try to wrap the different implementations in different C++ namespaces. Like: namespace v1 { #include "v1/foo.h" // From f...
5,178,330
5,178,540
C++ Alignment/Shift issue
I have a string: "the quic" Which is passed on to a function where the bits that make up the string are stored in an unsigned __int64. Resulting in the following output: 0111010001101000011001010010000001110001011101010110100101100011 However when I pass a string containing these values: 0xDE, 0x10, 0x9C, 0x58, 0x...
I guess you did something like this, char a[] = {0xDE, 0x10, 0x9C, 0x58, 0xE8, 0xA4, 0xA6, 0x30}; change it to unsigned char will solve your problem, unsigned char a[] = {0xDE, 0x10, 0x9C, 0x58, 0xE8, 0xA4, 0xA6, 0x30}; I've tried both, the char version will be wrong in VC++, but unsigned version will be correct. If ...
5,178,403
5,178,450
How to get File Time in C++
i am having a problem in getting the File Time Creation.. could anyone know how to get the FILE time?? I got a code that gets the file name of a certain directory my problem is i dont know how to put the filetimes on each file in the directory... here is my code: #include <vector> #include <string> #include <windows.h...
I think windows API has GetFileTime function, look it up, I haven't seen windows for a while. UPDATE: Look here and here
5,178,940
5,179,855
Differences between type variables and C++’s templates
what is the Differences between type variables and C++’s templates? thanks in advance edited you can see type variable in ML when function fun foo x = x have the type a->a a is type variable, can be any type
I think you mean "what's the difference between ML's polymorphism and C++'s templates?" They are almost entirely different, although they have some superficial similarities. In ML, fun id x = x is one polymorphic function which has the type a->a (for any a). In C++, template<typename a> a id(a x) { return x; } is a t...
5,178,948
5,179,005
Start external application maximized over taskbar (fullscreen)
How can i start external application in "fullscreen" mode (without borders and over taskbar)? And is it possible to do this using only .Net Framework library? Thanks for help.
As Raymond Chen suggests, the best way to create a fullscreen window that covers up the taskbar is simply by creating a fullscreen window without a border. Since your question is tagged C++, I'll assume you can translate this code into its .NET equivalent: HWND CreateFullscreenWindow(HWND hwnd) { HMONITOR hmon = Mo...
5,179,384
5,182,960
What happens with adjacent string literal concatenation when there is a modifier(L, u8, etc.)
It is valid in C and C++ to break a string literal because the preprocessor or the compiler will concatenate adjacent string literals. const char *zStr = "a" "b"; // valid What happens when string literals are prefixed with L (wide characters), u (UTF-16), U (UTF-32), u8 (UTF-8), and raw string literals (R"foo(this is...
In C++0x your example is valid according to [lex.string]/p13: ... If one string literal has no encoding-prefix, it is treated as a string literal of the same encoding-prefix as the other operand. ... In C++03 this same section said that this code had undefined behavior: ... If a narrow string literal token ...
5,179,491
5,179,592
Boost threads running serially, not in parallel
I'm a complete newbie to multi-threading in C++, and decided to start with the Boost Libraries. Also, I'm using Intel's C++ Compiler (from Parallel Studio 2011) with VS2010 on Vista. I'm coding a genetic algorithm, and want to exploit the benefits of multi-threading: I want to create a thread for each individual (objec...
If that's your real code then you have a problem. for(i = 0; i < _tamano_total; i++) { Individuo nuevo(true); nuevo.Start(); // Create and launch new thread _individuos.push_back(nuevo); } void Start() { _hilo = boost::thread(&Individuo::Run, this); } This code creates ...
5,179,522
5,180,302
Why does writing to temporary stream fail?
Consider the following code: #include <sstream> #include <iostream> class Foo : public std::stringstream { public: ~Foo() { std::cout << str(); } }; int main() { Foo foo; foo << "Test1" << std::endl; Foo() << "Test2" << std::endl; return 0; } When I execute this, it gives me: 004177FC Test1 I ...
I tested it. I can guess that operator<< cannot bind a temporary to a non-const reference, so any externally defined operator<< functions will not work on the Foo temporary, but any class member ones will so if ostream or ostringstream has any internal operator<< members they will work. Therefore it may be that the ove...