question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
6,429,115
6,429,210
c++ print out bitset of vector<unsigned char>
I am copy the double value to the vector of unsigned char. It will be my buffer for socket, which should contain values of different types. I wanted to test if the coping works correct. I wrote a small code. vector<unsigned char> buffer(8); double doubleValue_1 = 8.0; memcpy(&buffer[0], &doubleValue_1, sizeof( doubleV...
bitset<64>bitset_1(doubleValue_1); is casting your double to an unsigned long (because that is what the bitset<64> constructor takes.) Similarly for bitset<64>bitset_2(doubleValue_2);. Neither one is actually winding up with the bit representation for a double.
6,429,251
6,549,295
VS2010 - Structure change in CryptoAPI - v7.0A Vs v6.0A - WinCrypt.h
In C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\WinCrypt.h, the definition for CERT_CHAIN_ENGINE_CONFIG is typedef struct _CERT_CHAIN_ENGINE_CONFIG { DWORD cbSize; HCERTSTORE hRestrictedRoot; HCERTSTORE hRestrictedTrust; HCERTSTORE hRestrictedOther; DWORD cAdditionalStore; ...
The problem which you have can be very easy explained. If you use v7.0A or v7.1 you are able to compile your project so that it will run under Windows 7. So the default value for the _WIN32_WINNT is 0x0601. If you want co compile the program so that it will run on Windows XP you can define WINVER and _WIN32_WINNT expli...
6,429,460
6,429,591
Should one keenly & consciously attempt to postpone variable definitions as long as possible?
In his book Effective C++ Scott Meyers brings out one interesting guideline, Item 26: Postpone variable definitions as long as possible. It increases program clarity & improves program efficiency. The argument he puts forward to support the above is that, whenever a variable is created or destructed we incur some cos...
I certainly do. It indeed takes some adaptation to the new habit (coming from other languages myself I know what you mean), but once you're there, it's much more convenient. I see 2 more benefits in addition to what you mention: improved readability: you need less "cache" in your brain to remember the variables used i...
6,429,752
6,429,819
g++ misunderstands c++ semantics
There are two possible solutions to the problem: I don't understand the c++ semantics or g++ does. I am programming a simple network game now. I have been building a library the game uses to communicate over the network. There is a class designated to handle the connection between the apps. Another class implements ser...
First, returning by reference something allocated on the heap is a sure recipe for a memory leak so I would never suggest actually doing that. The second case can still result in a leak unless the ownership semantics are very well specified. Have you considered using a smart pointer instead of a raw pointer? As for why...
6,429,805
6,430,436
Inline function returning statically created object
inline Config& config() { static Config *c = new Config(); return *c; } The function above returns a pointer to class Config, created once when function calls. Will the C++ compiler be able to inline this function correctly? I mean c is static object, and creating it at first time will lead to inlined new Co...
You seem to have a slight misunderstanding about how such static variables work. It seems like you're thinking the compiler emits one set of code the first time the function is called, and another set every other time. That's not the case. You might consider the following transformation. bool initialized = false; Co...
6,429,881
6,447,506
Rich Edit Control changes the DialogBox return value behavior?
I'm a bit puzzled: i created a dialogbox with Edit Control, then i noticed the text isn't word wrapped, so i googled and found out that i should use Rich Edit Control instead. So i did. Now, when ever there is a Rich Edit Control in my dialog box, the functionality changes: without Rich Edit Control the dialogbox retur...
This thread has some good tips for resolving this problem. To summarize: If using pure WinAPI: Make sure to call LoadLibrary("RichEd20.dll"); or LoadLibrary("Msftedit.dll");. The latter is the newer version of the control. According to Rich Edit Control in raw Win32, you can also call InitCommonControlsEx() with the a...
6,429,915
6,429,939
Find regular polygon's vertices
I have some properties defined by the user, and then I want use them to automatically generate a regular polygon. The properties are centre x, centre y, radius and number of vertices. I would like to know how to calculate the x and y coordinates of all vertices of a regular polygon. I've already tried to do as Calculat...
There's an error in your angle calculation. The angle between each vertex should be 2 * M_PI / vertices. Obviously your macro: #define DOUBLE(a) ((a)*(a)) is incorrect. However in C++ you really shouldn't use macros for such trivial operations anyway - it should at the very most be an inline function, or just the dire...
6,430,228
6,797,428
CERN ROOT Graph Style Issues
Is there a way to center the titles of a graph along the length of the axis they describe? I am using C Scripting with the root command line to create a graph from a TNtuple and I have formatted everything else properly by using the TStyle and TGaxis classes to set the rest of the parameters. My problem is that the Off...
I think you cannot set globally from TStyle TCanvas canvas; TGraph g; g.SetPoint(0, 1, 1); g.SetPoint(1, 2, 2); g.Draw("APL"); g.GetXaxis()->SetTitle("my title"); g.GetXaxis()->CenterTitle();
6,430,303
6,430,365
Fixed length structure re-arrange: should I use array or linked list?
This structure will only contain exactly 256 unsigned chars. The only operation possible is taking random characters from it and putting them in front of the structure. For example: A= 'abcdef' Move character 2 to front A= 'cabdef' I first thought of using linked link so that it could work as a queue. Thing is I hea...
A linked list will be O(1) and an array will be O(n) for a move operation as you have described. For small n the array will probably be faster, but the only way to know for sure is to benchmark. In a case like this I would code what's clearest and only worry about efficiency if it proves to be a bottleneck. P.S. I made...
6,430,349
6,439,744
Using Blender for physics simulations
I've been looking at different ways of creating a certain physics simulation. What I am trying to do is to 3D model the motion of a body under the effects of various forces over time. I was originally looking at coding something in c++ using a physics engine (Bullet) and a 3d engine (Irrlicht). However, I noticed th...
I would use a Python script for that task, as Blender has a nice interface getting/setting the objects and their properties programmatically through .py files. So after you are done with your animation you can call a script to walk through the frames and save the required data into a file. A getting started doc can be ...
6,430,354
6,430,499
Shader from a file, program stopped working
Following an OpenGL tutorial, in a part, where it creates a vertex shader, it uses the following method, const GLchar* VertexShader = { "#version 330\n"\ "layout(location=0) in vec4 in_Position;\n"\ "layout(location=1) in vec4 in_Color;\n"\ "out vec4 ex_Color;\n"\ "void main(void)\n"\ "{\n"\ ...
You don't have to split the read file into lines, just pass the whole file as it is. Also those '\n' are in the C code, because you can't have ordinary newlines in a C string. You must escape them. But this is not neccesary reading from a file. And then you have a problem here: const GLchar *VertexShader = readShaderFi...
6,430,932
6,431,037
VS2008 Passing Variables - struct vs struct components - advantages/disadvantages?
I really hope this isn't one of those super basic questions. Anyway, I've got a struct with 47 components, and I'm calling various functions that use anywhere from 3 to 10 of these components at once. Is it better to call the function like: foo(pParam->variable1, pParam->variable2, pParam->variable3) or foo(pParam) ...
You should pass the struct by reference, that way you don't need to copy all the values: void foo(mySturct pParam); //Here the struct will be copy constructed.. relatively large overhead void foo(Val1 param1, Val2 param2, Val3 param3); // 3 parameters passed by value, the value will be copied. void foo(mySturct &pPar...
6,430,950
6,431,067
Correctly handling std::list erase with list size 1
Consider the following: for (it = list.begin(); it != list.end(); ++it) { if (!(*it)->alive) { it = list.erase(it); } } this works fine as long as list.size() > 1. Once the list contains only one element, the call to erase segfaults. I am assuming because there is no next element. At least, that's the ...
The following will work correctly: for (it = list.begin(); it != list.end(); ) { if (!(*it)->alive) { it = list.erase(it); } else { ++it; } } The problem is not just with certain sizes. In your example, you are skipping an element every time you remove one. Think about it. If the element is...
6,430,960
6,431,359
Iterator for second to last element in a list
I currently have the following for loop: for(list<string>::iterator jt=it->begin(); jt!=it->end()-1; jt++) I have a list of strings which is in a larger list (list<list<string> >). I want to loop through the contents of the innerlist until I get to the 2nd to last element. This is because I have already processed the ...
Requisite recommendation to use the standard library: std::for_each(lst.begin(), --lst.end(), process); If you don't want to hassle with creating a functor [I almost never do], and you can't use reverse iterators, hoist the end check out of the loop: for(iterator i = lst.begin(), j = --lst.end(); i != j; ++i) { //...
6,431,186
6,432,569
set the base object of derived object?
This is a basic concept question. If I have a class that Derived that inherits from Base, and I instantiate a new Derived object, can I set it's Base object to a specific Base object of my choosing so that all calls base class methods are redirected to this particular base object? something like this: class Base { prot...
I'm not questioning why you want to do this, but it's perfectly safe do it unless your inheritance breaks the ISA relationship (eg Derived is a restricted subset of Base, eg a Square is not a Rectangle since it is possible to resize only one dimension of a Rectangle but impossible to do so with a Square). *static_cast<...
6,431,229
6,431,494
How Do I Launch a Dialog in MFC?
I'm fairly new to VC++ and MFC, so bear with me. I have created a new dialog, and I want to figure out how to display it when the user clicks a button. I have not create a class or header file for the dialog -- I tried using the class wizard, but it pretty much sucked and didn't work. That, or I was doing something wr...
Right click the project and select Add | Resource... Select Dialog under Resource type and click New. Select Project | Add Class... Enter CMyDialog for the Class name, CDialog for the Base class and Click Finish. Read more: How to Make MFC Dialog Boxes
6,431,262
6,447,997
Same game in OGL ESv2 doesnt work with OGL3
I've coded a engine which is able of drawing with OpenGL ESv2 or OpenGL 3 Core Profile API. But recently the OpenGL 3 part got broken and I can't remember what I changed nor can I look in the svn commitlog, cause I did host it at bountysource which is down now and I carried it over to Google (but with broken OGL3 port)...
I'm so dumb..it was cause I have 2 class. 1 base class and 1 plattform specific implementation which derived from the base class. All variables were created in the base class AND in the other. So, I had handles for the matrices in the base class and in the other class. The OpenGL handles were initialized in the base cl...
6,431,308
6,431,735
interrupting boost::asio::async_receive_from from another thread
I am reading multicast input using async_receive_from. So the idea is that when I detect a gap, I will notify another helper thread to request/get the gap filling messages. While this is in the works the main thread will continue to receive and queue any incoming messages. This part I can implement. The other thread ca...
Why are you using shared memory between threads? That aside, the mechanism you should use for executing something in the context of the io_service which is managing the socket is post(). You can post any arbitrary event to the io_service, and it will execute in that context. Quite easy really... Because you are callin...
6,431,386
6,431,445
UDP Socket programming in C++ in linux
I am completely new to socket programming and beginner-intermediate in c++. I have written a code in c++ and also another application in java. The java program will get data from the c++ code which generates data in seconds. I am trying to use socket programming to transfer data between these two. I have found some cod...
You must declare addr_len as socklen_t, not int. That is, the first few lines in main should read something like: int sock; int bytes_read; // <- note how this is now on its own line! socklen_t addr_len; // <- and this too, with a different type. char recv_data[1024]; ... Leaving everything else as it were.
6,431,404
6,450,730
how to parse and verify an ordered list of integers using qi
I'm parsing a text file, possibly several GB in size, consisting of lines as follows: 11 0.1 14 0.78 532 -3.5 Basically, one int and one float per line. The ints should be ordered and non-negative. I'd like to verify the data are as described, and have returned to me the min and max int in the range. This is what I've...
This is at least a lot shorter already: down to 28 LOC no more locals no more fusion vector at<> wizardry no more inherited attributes no more grammar class no more manual iteration using expectation points (see other) to enhance parse error reporting this parser expressions synthesizes neatly into a vector<int> if yo...
6,431,698
6,431,724
Is it bad manners to return a heap allocated pointer from a function?
Before boost::shared_ptr, was it considered a bad practice to return a heap allocated pointer from a function, since the caller will be required to remember to free() that object? Or, was it considered "normal"?
I don't consider it bad practice, so long as your API also provides an equivalent XXX_free (or XXX_close, XXX_clearup, or whatever) function, that the client code can call when finished with the pointer. That way, you have a consistent, symmetrical API, in the sense that responsibility for the lifetime of a heap object...
6,431,788
6,432,553
How do you format with Boost.Date_Time without leading zeros?
How can you format a boost::posix_time::ptime object without padding the numbers with zeros? For example, I want to display 6/7/2011 6:30:25 PM and not 06/07/2011 06:30:25 PM. In .NET, the format string would be something like "m/d/yyyy h:mm:ss tt". Here is some code to do it the wrong way, just to get an idea: boost::...
To my knowledge this capability is not built into Boost.DateTime, but it's pretty trivial to write your own formatting functions, e.g.: template<typename CharT, typename TraitsT> std::basic_ostream<CharT, TraitsT>& print_date( std::basic_ostream<CharT, TraitsT>& os, boost::posix_time::ptime const& pt) { boo...
6,431,942
6,432,103
Undefined reference to `yylex' in yyparse() while compiling using g++, bison and flex
I have a problem while compiling my code (undefined reference to 'yylex'). Let's start off with the snippet and I'll describe the details below: Flex: %{ #include <stdlib.h> extern int yylex(); %} %% "=" {return EQ;} "!=" {return NE;} "<" {return LT;} ">" {return GT;} ":=" {return ASSIGN;} ";" {return SEMICOLON;}...
In your Flex file, you declare this: extern int yylex(); When compiled as C++, that declares a function with C++ linkage. In your Bison file, you declare this: extern "C" { int yylex(); } That gives it C linkage. They're two different functions. You define the C++ version (or, rather, Flex defines it for you), but ...
6,432,004
6,432,081
g++ won't play nice with wx-config
I'm on windows using mingw and when i use the following to try and compile my wxWidgets code g++ main.cpp `wx-config --libs` `wx-config --cxxflags` I get the following error g++: `wx-config: No such file or directory g++: `wx-config: No such file or directory cc1plus.exe: error: unrecognized command line option "-flib...
What shell are you using? Back quotes don't work on the Windows command prompt. You may need to use msys and bash.
6,432,348
6,432,432
shared data between objects via a pointer in C++
I have several objects which share a data via a pointer. The pointer parameter was sent via in the constructor functions, as follows. class A { public: Shared* pB = new Shared(); User* object1 = new User(pB); User* object2 = new User(pB); } class User { public: User(Shared* pB) {m_sharedB = pB}; priva...
If you have a class that contains a member that is a pointer, class Foo { Bar * mp_bar; }; then upon destruction of a Foo object, nothing happens other than that the pointer, along with its containing object, goes out of scope. It's the same as what happens to p at the end of the following function: void bar() { i...
6,432,508
6,433,128
Boost.Range algorithm for getting the nth element of a range
Is there a way to get the n'th element of a range using Boost.Range? (I am not talking about the nth_element algorithm which returns the element that would be in n'th position if the range were sorted. I simply want the n'th element according to the current order of elements in the range). I would expect this function ...
I don't see anything like that built in, but it seems pretty easy to implement: namespace details { template<typename RangeT, typename IterCatT> typename boost::range_reference<RangeT>::type nth_impl( RangeT& range, typename boost::range_difference<RangeT>::type n, IterCatT const) { typedef typename bo...
6,432,577
6,432,606
.NET C++ writing UI from other thread
In .Net C++, I want to write the serial input to a textBox on the UI. But of course the serial input is on another thread. I am guessing that I need to pass in a delegate to the serial thread when I create it to run the function below called updateTextBoxes. I tried making a delegate as below but I am stuck at what ...
you would pass the arguments that are required for the constructor
6,432,631
6,432,753
Is it possible to use pthreads without pthread_join()?
What I've noticed recently in attempting to add some multithreaded functionality to some code of mine for a project at work is that pthreads are a huge pain in the ass to deal with logistically... Here's the scenario... I have an infinite loop in my main method (a server) spawning threads to deal with data whenever it ...
You're never giving the thread a chance to execute with that while(1){continue;}. One of two things will happen here. You've compiled with high enough optimization that the compiler makes that entire loop vanish. The thread never gets a chance to execute because main starts the thread and then immediately returns zero...
6,432,658
6,433,019
Strange error C2275 ... illegal use of this type as an expression with member function template and lambdas
Summary For some reason, my member function template that invokes a lambda function fails to compile with error C2275 ... illegal use of this type as an expression, but when the function is moved out to be a free function it compiles correctly. Details First I have a base class that keeps function instances in a vector...
Thanks to @sehe's answer, I could test this myself on VS2010. The following code works: derived() { // vvvvvvvvvvvvvv add_external([this] () { this->template invoke_internal<logic_error>([]() { throws_logic_error(); }); }); add_external([this] () { this->template invoke_internal<runtime...
6,432,669
6,432,866
Variance in RDTSC overhead
I'm constructing a micro-benchmark to measure performance changes as I experiment with the use of SIMD instruction intrinsics in some primitive image processing operations. However, writing useful micro-benchmarks is difficult, so I'd like to first understand (and if possible eliminate) as many sources of variation and...
RDTSC can return inconsistent results for a number of reasons: On some CPUs (especially certain older Opterons), the TSC isn't synchronized between cores. It sounds like you're already handling this by using sched_setaffinity -- good! If the OS timer interrupt fires while your code is running, there'll be a delay intr...
6,432,709
6,433,402
Arguments to a template function aren't doing any implicit conversion
For some strange reason, I can't get the template arguments in this one piece of code to implicitly cast to a compatible type. #include <type_traits> template <typename T, unsigned D> struct vec; template <> struct vec<float, 2> { typedef float scalar; static constexpr unsigned dimension = 2; float x, y...
I'm going to side-step your actual problem and instead make a recommendation: Rather than writing all of this complicated boilerplate from scratch, have a look at Boost.Proto, which has taken care of all the tricky details for you: Proto is a framework for building Domain Specific Embedded Languages in C++. It provide...
6,432,771
6,432,803
Private Inheritance: How do I make object of the Base Class ( which has got pure virtual methods)?
Consider the following code: class Base { protected: virtual void methodDefinedInBase() = 0; } Class Derived: private Base { public: void someMethod(); protected: virtual void methodDefinedInBase() { std::cout<<"From B"<<std::endl; } } In the above code, I can create object of type "Derived". C++ ...
As Beta noted in a comment, you can't instantiate an abstract base class (one with pure virtual methods.) You can only instantiate derived classes that implement those pure virtual methods. That's true regardless of whether you're using public or private inheritance.
6,432,781
6,433,249
Including functions with extern C linkage in library
I have included some C functions with extern c linkage in c++ code. E.g. // File Y.cpp: extern C { void fnA(void) { } void fnB(void* a, void* b) { } } class test { .... }; // end of file File Y is under module Mod. While building library libMod-O.a for module Mod, I don't see the functions under extern bl...
You mean extern "C" of course. You need to have a clean separation between your C code and your C++ code. In YourCCode.h: #ifdef __cplusplus extern "C" { #endif void fnA(void); void fnB(void* a, void* b); #ifdef __cplusplus } #endif In YourCCode.c: void fnA(void) {} void fnB(void* a, void* b) {} Make sure your comp...
6,432,923
7,925,005
wxSocket wxWidgets failing
Can someone provide just a simple example of how to use wxSockets write, because every time I try to use it to write to a connection I get windows coming up with this program has stopped working crap and the only thing I'm doing is using wxSocketBase::Write. Or does anyone know why it is failing? I have even tried to h...
Can someone provide just a simple example of how to use wxSockets write? Yes, I can: #include <wx/wx.h> #include <wx/socket.h> #include <iostream> int main () { wxInitialize(); wxSocketClient * sockConn = new wxSocketClient(wxSOCKET_WAITALL); wxString url = wxT("localhost"); wxIPV4address addr; addr.Hostna...
6,433,132
6,572,232
Algorithm for struct/class data alignment and padding?
I can't seem to find any information on how to calculate padding within a struct or a class within C, C++. In HLSL there are data structures called "Constant Variables" and they are very much like C structs with #pragma pack (4) enabled. Here is a link for more information with regards to Constant Variables in HLSL. Th...
My question is asking for the algorithim used to make #pragma pack 4 work. (e.g. does it look at one variable at a time within a struct and use some sort of max size test to determine where to pad or does it analyses the entire struct and somehow shuffle data around.) The compiler cannot shuffle data around in a C-s...
6,433,246
6,433,360
can I write a variable from thread A while I read the same variable from thread B
This would be done without mutexes. I just want to know if it is thread safe ie the program will not crash or something similar. I do not really care that the variable could be in the wrong state when it is read as the consequence is not fatal (only impact would be making a copy of a small data structure when not ne...
You seem to be asking about what are called benign races. For example consider an integer variable representing a progress value in the range 0 to 100. You read it from one thread at the same time as you are incrementing from another. You don't mind whether you read the value before the write or the value after the wri...
6,433,336
6,433,522
Is there a good way to make sure a C++ function result is not ignored?
I ran into a case recently where I had a const member function performing an operation and returning a result. For example, class Foo { ... Foo add(Foo const & x) const; } But someone else was inadvertently calling it like it was updating the this object (ignoring the result): Foo a = ...; Foo b = ...; a.add(b); ...
This is what function attributes are for (documentation) in GCC and Clang, but it's not portable to e.g. MSVC. class Foo { ... __attribute__((warn_unused_result)) Foo add(Foo const & x) const; } The documentation says it's used on realloc for example, but it doesn't appear on any other standard functions on my...
6,433,339
6,433,724
Does the 'offsetof' macro from <stddef.h> invoke undefined behaviour?
Example from MSVC's implementation: #define offsetof(s,m) \ (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m)) // ^^^^^^^^^^^ As can be seen, it dereferences a null pointer, which normally invokes undefined behaviour. Is this an exception to the rule or...
Where the language standard says "undefined behavior", any given compiler can define the behavior. Implementation code in the standard library typically relies on that. So there are two questions: (1) Is the code UB with respect to the C++ standard? That's a really hard question, because it's a well known almost-defect...
6,433,390
6,433,631
Fail to compile QT 4.7.3 with Visual Studio 2010
After following guide on how to compile QT with Visual Studio 2010 I still havent managed to make it work. I get the following error during the "configure" process. LINK : fatal error LNK1104: cannot open file 'libcpmt.lib' NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 10.0\VC\BIN\link.EXE"' : r...
Make sure you Open a Visual Studio command prompt, or run vcvars32.bat to set up Visual Studio's environment vars properly Extend the PATH variable to include $(QTDIR)\bin, where $(QTDIR) is where you installed Qt Just for comparison, here's my configure string: configure -debug-and-release -opensource -shared -ltcg -...
6,433,416
6,433,448
Help Setting/Constructing Static Array Size in Classes and Objects in C++
Have a homework assignment, I thought was simple and can do it not using classes/objects, but I guess I'm just not understanding classes/objects well enough to complete it the way my teacher is asking me to do. All of this will be done with an array of integers with a length that will always be 20. Assignment calls fo...
Try this: //book.h class Shelf{ public: static const int shelfSize = 20; Shelf(); void insert(int); int bookshelf[shelfSize]; }; (You'll need to remove the bookshelf[shelfSize]; line from your constructor.) Your constructor can be simplified, by taking advantage of initializer lists: Shelf::Shelf() :...
6,433,573
6,433,586
In the array of objects, constructor is called many times but operatror new[] only once , why?
When object is created in the heap, it (new) does two things. 1: calls operator new 2: calls constructor to initialize the obejct. I am trying to create array of objects, for example 4 objects , so it calls constructor and destructor 4 times that makes sense but it only calls one time operator new[] ?? why? Following i...
operator new[] is only there to allocate the necessary space, nothing else. Of course, it will do so only once, as anything else would be nonsens and wouldn't get a contiguous buffer. The size parameter you're getting, in the case of new test[4], should be 4 * sizeof(test).
6,433,741
6,433,757
Can't define templated types for my LruCache class
#include <map> #include <list> template < typename K, typename V> class LruCache { private: typedef std::pair< K, V > EntryPair; typedef std::list< EntryPair > CacheList; typedef std::map< K, CacheList::iterator > CacheMap; public: LruCache(){} ~LruCache(){} }; if I try simply LruCache cache; I ...
Use typename as: typedef std::map< K,typename CacheList::iterator > CacheMap; //^^^^^^ Its because iterator is a dependent name on the template argument. Its value depends on CacheList which in turn depends on the T which is in fact a template argument. That is why typename its needed here which tel...
6,433,746
6,433,865
Template specialization for an empty parameter pack
I have a variadic template function which calls itself to determine the largest number in a list (constituted by the templatized arguments). I am trying to make a specialization for when the parameter pack is empty so I can just return the number at the front of the list, but I don't know how to do that. I am just beco...
I see two mistakes using clang. Put the overload taking a single int first. Make things unambiguous for lists of length 1. Recall that variadic lists can have zero size and when they do, it seems to me you have an ambiguity. This compiles and runs correctly for me: #include <iostream> using namespace std; template...
6,433,933
6,443,726
QTcpClient successfully connects, but not to my server. Where is it connecting?
I have successfully built a thin client/server using Qt's Tcp Sockets API. I know it works very well, because I have sent plenty of data over the wire and verified it. However, my project manager wants a suite of unit-tests, and I'm implementing them using Qt's Test Library. Anyhow, I'm trying to set up some dummy se...
While QTEST_MAIN creates a QApplication and runs all your tests, it does so sequentially and not with an event loop. Therefore, while your socket can indeed connect to the server (meaning qTestSocket->waitForConnected() returns true), since the app doesn't return to an event loop, the QTcpServer's signal will not get e...
6,433,935
6,434,033
Where to define static const member variables of a template class
According to this question's answer: According to the standards you must define i (which is a static const member) outside of the class definition ... but if I do that for static const member variables of a template class which are themselves generic, then I get linking errors (similar to getting linking errors if the ...
Static data members of a class template have to be defined in a header file. Only when you are defining static members of an explicitly specialized template, you have to define them in an implementation file. In other words, the rule is the same as for member functions of class templates.
6,434,006
6,434,085
Quick question about Qt with C++
I can't download the Qt IDE right now as it is about 1.5GBs, and my internet connection is limited to 60Kb/s with a download limit of 500MBs. So, excuse my curiosity as I won't be able to try Qt before quite some time. The question is: If I want to use the DB, GUI, and Networking features of Qt, what is the typical siz...
A "hello world" application using those modules on Windows would probably come in over 5 MB. It really depends on the Qt configuration. You can statically link only what you need and compress the executable (see UPX) to get a much smaller output. As for installation, there is no framework to install. Just bundle the ap...
6,434,251
6,476,333
Set a image(jpeg | png) backgound using GLX ( opengl and Xlib)
I create a x11 window with opengl functionality, i need to load a image(jpeg | png) on its background where size of window be bigger than image, it doesn't matter. I surfed to get resylts like use DevIL or free image. I dont know which one to use. I set up the opengl window with the sample code given in a link to sampl...
I'm not much of a opengl programmer, but somehow i did this and its workinh ilInit(); /* Initialization of DevIL */ ilGenImages(1, &texid); /* Generation of one image name */ ilBindImage(texid); /* Binding of image name */ success = ilLoadImage(backgroundimage); /* Loading of image "image.jpg" */ iWidth = ilGetIntege...
6,434,264
6,434,318
C++ destructors as virtual functions?
I just read recently that its a good practice to implement C++ destructors as virtual functions[1]. Why is this so? Is this a general good practice? If not, in what conditions/cases is a destructor to be made a virtual function? Reference https://www.blackhat.com/presentations/bh-usa-07/Afek/Whitepaper/bh-usa-07-afek-...
If a base class has a destructor and it is NOT virtual, then any child class's destructor will not be called if delete is invoked on the base class's pointer. This can result in memory leaks. class Shape { public: Shape() { cout << "Shape constructor called" << endl; } // This destructor should ...
6,434,341
6,461,711
What are the threading guarantees of nowadays C and C++ compilers?
I'm wondering what are the guarantees that compilers make to ensure that threaded writes to memory have visible effects in other threads. I know countless cases in which this is problematic, and I'm sure that if you're interested in answering you know it too, but please focus on the cases I'll be presenting. More preci...
I'm writing this answer because most of the help came from comments to questions, and not always from the authors of the answers. I already upvoted the answers that helped me most, and I'm making this a community wiki to not abuse the knowledge of others. (If you want to upvote this answer, consider also upvoting Billy...
6,434,357
6,434,403
Sorting a vector of objects
I have a vector filled with some vertex object instances and need to sort it, according to its 'x' and after it its 'y' coordinate. vertex.h #ifndef VERTEX_H #define VERTEX_H 1 class Vertex { private: double __x; double __y; public: Vertex(const double x, const double y); bool operator<(const Vertex &b) const;...
You are storing Vertex * in the container not Vertex. When you call std::sort, you're actually sorting the value of the pointers, not the items themselves. If you really need to be storing pointers (which I doubt), you can use a workaround like this (untested): struct less_than_key { inline bool operator() (const V...
6,434,438
6,434,471
How do I get char * from vector<char>?
I have declared a vector like this vector<char> vbuffer; and used it as a receive buffer like this.. recv = read(m_fd, &m_vbuffer[totalRecv], SIZE_OF_BUFFER); It seems like working and now I want to get the raw char data for parsing.. If I have defined a function like this.. char* getData(){ //return char data from t...
As long as you don't resize the vector in any way, you can use &vbuffer[0] as a pointer to the array. There are many operations that will invalidate pointers to a vector though, make sure you don't call any of them while you have a pointer in use.
6,434,479
6,434,603
What is #pragma weak_import?
And what is the best way to look up these pragma information in the internet? Google search comes up with a lot of noise (mainly the occurrence of the pragma in various source code repositories)
It's something for Mac OS X, documented here: http://developer.apple.com/library/mac/#technotes/tn2064/_index.html
6,434,493
6,434,527
What difference it will make, if we have uniform extension (.c/.cpp) for all C/C++ files?
In C/C++ project, mostly the file can be of either types .h or .c/.cpp. Apart from their naming difference such as header and implementation files; is there any functionality difference ? In other words: if in a working C/C++ project what difference it makes if we change all files with .c or .cpp extension ? [Note: We ...
What difference does it make? The compiler is perfectly happy about it. To it, it's just files. But to you? You makes a lot of difference: you're no longer able to immediately figure out which one is the header and which one is the implementation; you can no longer give header and implementation the same name;
6,434,549
6,442,631
Does C++11 add the C99 restrict specifier? If not, why not?
restrict is a C99 feature which is getting a lot of attention lately by allowing the compiler to perform "previously-fortran-only" optimizations to pointers. It's also the same keyword announced by Microsoft recently to be the underpinnings of the C++AMP specification. Is that keyword actually in the FCD? If not, is th...
One argument is that C needs restrict more than C++, because many operations are done with pointers to primitive types and therefore C code has more aliasing problems than C++. The aliasing rules say that pointers to different types cannot alias, so if the parameters to a function are of different class types they jus...
6,434,678
7,151,068
Iterating over the dimensions of a boost::multi_array
I'm trying to write some dimension-independent code for a template class in c++, using a boost::multi_array (though if other containers/data structures are better at this, I'd be happy to hear about it). Given a dimension, I would like to iterate over the full range of every other dimension, returning a 1d view along t...
Normally you can do it with boost::multi_array, heres some sample code to create a 2D view of a 3D multi_array: #include "boost/multi_array.hpp" #include <cassert> #include <iostream> int main() { typedef boost::multi_array<double, 3> array_type; typedef array_type::index index; array_type myArray3D(boost...
6,434,830
6,435,482
How do I analyze a crash dump from a binary built with optimizations enabled (release mode)?
Till now I was using debug mode binaries in project. So it was easy to analyze crash dump using symbol files preserved. Now i have to ship binaries in Release mode. How we can analyze dump files generated by release mode binary. Is it possible at all ? How i identify functions in release mode ? (Do in need to gener...
You need the .pdb file that corresponds to the executable. That'll give you the symbols. There are a couple tricky parts to debugging a release build: The order of operations may be off due to optimizations Whole functions/variables/etc. may be optimized away In particular, the arguments passed into functions may not...
6,434,971
6,435,036
How much is too much with C++11 auto keyword?
I've been using the new auto keyword available in the C++11 standard for complicated templated types which is what I believe it was designed for. But I'm also using it for things like: auto foo = std::make_shared<Foo>(); And more skeptically for: auto foo = bla(); // where bla() return a shared_ptr<Foo> I haven't see...
I think that one should use the auto keyword whenever it's hard to say how to write the type at first sight, but the type of the right hand side of an expression is obvious. For example, using: my_multi_type::nth_index<2>::type::key_type::composite_key_type:: key_extractor_tuple::tail_type::head_type::result_type ...
6,435,032
6,435,103
How do I clone vector?
I am using vector as an input buffer... recv = read(m_fd, &m_vbuffer[totalRecv], SIZE_OF_BUFFER); After it reads all data from the input buffer then it will put the data inside of the vector into the thread pool. So I was trying to do clone the vector. I think I cannot just pass the pointer to the vector because of t...
You can easily copy a vector using its copy constructor: vector<T> the_copy(the_original); // or vector<T> the_copy = the_original;
6,435,052
6,435,260
Overriding operator new/delete in derived class
I have a stateless, abstract base class from which various concrete classes inherit. Some of these derived classes are stateless as well. Because many of them are created during a run, I'd like to save memory and overhead by having all stateless derived classes emulate a singleton, by overriding operator new()/delete()...
I would say the best solution here is to make your derived class an actual singleton. Make your derived constructor private and just provide a static Base* getInstance() method that either creates the required object or returns the static instance. This way the only way to get a D1 object would be via this method since...
6,435,131
6,435,167
Indexed array quicksort debug
I'm going nuts over this special quicksort algorithm and I don't know where is the problem. I've found an example on a forum that explains very well what I'm trying to do. Given an index array of contiguous, ordered numbers (representing elements in the data array), you still have to compare the data values; you...
Uhh you can't store numbers larger than 255 or lower than 0 in an unsigned char. An unsigned char can store the range defined by one unsigned byte, so 8 binary digits. 2^8 = 256, and since we include 0, we have 256 - 1, giving us 255. (or in hex, 0xFF) Try using ints, or even shorts. (keyword short)
6,435,171
6,435,257
What is the advantage of using vector<char> as input buffer over char array?
I am working on a network programming and I have seen people using vector as the input buffer for socket instead of char array. I was wondering what it the advantage of doing this. Thanks in advance..
A vector<char> is essentially just a managed character array. So you can write: { vector<char> buf(4096); ... int result = recv(fd, &buf[received_so_far], buf.size() - received_so_far); ... } The vector "knows" its size, so you can use buf.size() everywhere and never have to worry about overrunning you...
6,435,404
6,435,443
C++ error: double free or corruption (fasttop)
I'd like to know why the following program gets the error "double free or corruption (fasttop)" when I run the program. I know I can use string instead of character array. But I'd like to use character array with dynamic memory allocation. Could you please let me know how I can fix this problem? #include <iostream> #i...
You forgot to define operator= for your class. This is the rule of Big Three (copy ctor, dtor, assignment must all be defined).
6,435,460
6,435,540
a point from ISO document: based on Anonymous Unions
Point from ISO C++ Standard: section 9.5, para 4, line 1: "A union for which objects or pointers are declared is not an anonymous union." Example : struct X { union { int i; double d; } ; int f () { return i;} }; int main() { ret...
This would make the union not anonymous: struct X { union { int i; double d; } *p; int f () { return i;} // !Nyet. }; Cheers & hth.,
6,435,462
6,435,622
DirectX with c++ in web development
I wonder if it possible to make a game by c++ with directx(in GFX) so that it could be put in my web (php , asp.net, java or other I don't care about the web language or technology, you chose one for me) and be played online or I have to change something directx or C++. if it possible tell me how? thnx in advance
If you mean browser based, I'm not sure it's possible with C++. You might want to look into webGL. If you're feeling very adventurous, I am aware of an open source project that is essentially a .NET to JS compiler. You can check it out on github here If you mean "online" as in a MMO type of game, or a game that is play...
6,435,521
6,435,550
Does dynamic_cast work inside overloaded operator delete?
I came across this: struct Base { void* operator new (size_t); void operator delete (void*); virtual ~Base () {} // <--- polymorphic }; struct Derived : Base {}; void Base::operator delete (void *p) { Base *pB = static_cast<Base*>(p); if(dynamic_cast<Derived*>(pB) != 0) { /* ... NOT reaching here ? ... */...
Function operator delete is a raw-memory deallocation function. It is invoked when the actual object (that used to reside in that memory) has already been destructed. I.e. by the time you get into operator delete you object has already been wiped out. The memory the pointer points to is essentially "raw", it no longer ...
6,435,696
6,435,740
c++ Copy file \ Generic implementation
I'm looking for a good C++ copy function that encapsulate inside local copy, UNC copy, and HTTP download copy. something like bool copy(string path1, string path2) {} I'm not strong at c++ and have tendency to create memory leaks more than are needed. Is there a complete implementation out there? Thanks!
Basically you are asking someone to implement a generic copy function that is able to take various different URI's? For example, if you want to do HTTP downloads you will need a library that knows HTTP, such as cURL. The other two, (local path and UNC) should work on Windows, look at using fstream. There are plenty of ...
6,435,929
6,436,726
Simple C++ File I/O issue
It's been a while since I've worked with File I/O in C++ (and just C++ in general) but I recently decided to use it to make a small console project for a friend. My issue is that I'm having some issues with a string array and File I/O (I'm not sure which is causing the problem). My code is as follows (ReadPSWDS is an i...
The loop you've written is clearly wrong: you're testing eof() before failure, and you're not testing for failure after the getline. C++ I/O isn't predictive. (I can't be, since whether you're at eof() will depend on what you try to read.) The correct pattern would be: while ( i < size(str) && getline( readSWDS, str...
6,435,955
6,436,076
Where should I free the object?
void ServerManager::addWork(SocketClient *clientSocket, vector<char> data){ Work *work = new Work(clientSocket, data); m_workHandler->addWork(work); } Here I created Work instance and hand the work to the WorkHandler. m_workHandler->addWork(work); This code is inserting the work into the queue. This is one ...
Judging by your second bit of code, it looks like the memory leak might actually be from the Packet allocation, because the Work instance is being deleted in what seems like a correct place (in workLoop, not addWork). But I can't be certain without seeing more of your code. Allocations in C++ don't have a reference co...
6,436,257
6,436,321
How do you copy/paste from the clipboard in C++?
I'm still a C++ newbie who has only recently learned some file manipulation. I looked it up online and the codes given are way beyond my current skill. Is there a simple way to do this, or are there any good tutorials that can explain this from the very basics?
In windows look at the following API: OpenClipBoard EmptyClipboard SetClipboardData CloseClipboard GetClipboardData An extensive discussion can be found here. Obviously this topic is strongly operating system related. And if you are using some framework (ie MFC/ATL) you generally find some helper infrastructure. This...
6,436,481
6,436,514
Template explicit instantiation of a method with a different body
I have a template class with a constructor that takes a std::vector<T>. For every object except one I want it to make operation A. But for that one object, I want it to do some other stuff B. Is there a possibility to create an explicit instantiation of only the constructor for a template class? I hope its described pr...
Your question isn't clear. Perhaps you mean something like the following? template <typename T> class Foo { public: Foo() { std::cout << "standard" << std::endl; } }; template <> Foo<float>::Foo() { std::cout << "random" << std::endl; } // Special case ... Foo<int> f1; // Prints "standard" Foo<float> f2; ...
6,436,554
6,436,615
Value initialize aggregate
Tried C++ standard, but couldn't figure it out. Are these equivalent? double x[2] = {0.0, 0.0}; and double x[2] = {}; How about these? struct A { double x[2]; }; A a = {0.0, 0.0}; and A a = {}; Thank you!
The C++ standard says (8.5.1): If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized and value-initialization of a double is to set it to 0.0. So yes! In C++ they are equivalent. [I haven't had time to check...
6,436,760
6,436,814
Retrieve the mac address of a remote pc Qt C++
I just want to know how to get the mac address of a remote computer. void LocateAddress() { QString host = "192.168.1.1"; .....function for getting the mac address.... } Is there a way to create a function that retrieves the Mac Address of a remote pc??? Using ng Windows OS
Using arp -a 192.168.1.1 on the command line you can get that information if you just need it once. If you want to do it programmatically, there is a SendARP function in the windows API, documented here Note that this only works on your local network, there must be no routers between you and the target computer.
6,436,776
6,436,890
c++ class disassembly
I have the following code: class Base { public: int x,y; Base() { x=10; y=20; } virtual void myfunction() { } }; int main() { Base *b = new Base(); return 0; } The disassembly gives me something like: push 0Ch ; size of Base call j_<some giberrish> ; IDA gives the comment "operator new(uint)" add esp, ...
This is almost certainly a debug build you're looking at and debug builds are very conservative with what they do. Creating an object is a two stage process: allocate memory and then construct the object. Your compiler is putting the allocated memory pointer into a temporary variable. If you build an optimised version,...
6,437,089
6,437,148
what is the uses cases in which order in key value associative container is useful
I am wondering in which uses cases, we can be interested by having an ordered associative container. In other terms, why use std::map and no std::unorderd_map
You use an ordered map when you need to be able to iterate over the keys in an ordered fashion.
6,437,145
6,437,449
Comparing to a string literal in a console application
I have a simple native C++ console app. I want to stay something like this: Quit? (Y/N) and be able to type in Y or N to tell the program what to do? So far I have this code: std::string whetherToQuit; std::cout<<"Quit? (Y/N): "; std::cin>>whetherToQuit; if(whetherToQuit == "Y"){ exit(EXIT_SUCCESS); } else if ...
There are three points worth mentioning: Why are you using string? Use char instead: char ans; if (ans == 'Y') { // op } else if (ans == 'N') { // op } Why are you using "break" inside else if. A break statement may only be used within a switch or loop. [ADDED] Use return instead of Exit. Exit circumvents RAII. Final...
6,437,224
6,437,292
Getting auto-vectorization with gcc?
In the context of evaluating negative-log-likelihoods, I have to perform a bunch of operations that could benefit from vectorization 0) for (i = 1...n) { a[i] = 0; } // but this I think std::fill( a.begin(), a.end(), 0 ) is already optimal 1) for (i = 1...n) { a[i] += b * c[i]; } 2) sum = 0; for (i = 1 .. n) { s...
http://gcc.gnu.org/projects/tree-ssa/vectorization.html Use the required options, -O3 -msse2 For more options, read the documentation above.
6,437,333
6,437,366
Tool to decipher C/C++ function pointer typedefs
I remember once seeing a website, which deciphered complex C++ typedefs including function pointers returning function pointers to functions which return an array with … It would turn such definitions into readable English text: »Pointer to function, returning an array of int-pointers, taking a long and a callback func...
I think you are looking for https://cdecl.org/. You can find the program itself at https://github.com/ridiculousfish/cdecl-blocks
6,437,466
6,437,535
`shared_ptr` breaks constness of the object
Consider the following code: class B { int x; public: B() : x( 10 ) {} int get_x() const { return x; } void set_x( int value ) { x = value; } }; class A { boost::shared_ptr<B> b_; public: boost::shared_ptr<B> get_b() const { return b_; } // (1) }; void f( const A& a) { boost::shared_ptr<B...
This doesn't actually have anything to do with shared pointers per se. I mean if you had a plain pointer you'd have exactly the same problem and would solve it in exactly the same way, that is const B* get_b() const {return b_; } If you left it like B* get_b() const {return b_; } you'd have the same problem. Well, yo...
6,437,538
6,438,307
VS2010 static linking issue
my company has recently upgraded from VS2005 to VS2010. We have a huge project which uses a lot of modules which are being linked statically into the exe. But there seem to be some issues with linking in VS2010. To explain our problem, we've built a minimal example project which is composed as shown on this graphic: T...
Have a look at following links: Visual Studio 2010 not autolinking static libraries from projects that are dependencies as it should be supposed to Behavior of Link Library Dependencies in 2010 Unresolved Externals When Build a VC++ Project with Chained Static Lib Dependencies Flexible Project-to-Project References
6,437,619
6,437,967
inheritance, policy mixed with templates
I want to do something as the following. I have a class as follows with some elements which are not our concern right now. template<class A> class Domain { }; My issue is, I want some new objects to be members of this class. But I cannot specify them in this definition. I have to specify it in some other file. My fir...
A::ctype is seen as a member call, not a type. You should use the typename keyword: template<class A> class Domain : public Data<A,typename A::ctype> { public: Domain(A& a); };
6,437,848
6,437,875
how to execute c++ code at server side using tomcat server?
I am a beginner in writing web application, so please co-operate if its a silly question. Our web application is hosted using tomcat 6. I have some C++ code to be executed in server when user click on corresponding button. Client side is written in html/JS and hosted using tomcat. So, My problem is I dont know how thi...
Tomcat, a Java Servlet container is definitely not the most appropriate vehicle to execute C++ code in. You could try to use JNI to make a servlet run the C++ code, but it seems to me that there are much easier and reliable ways, like good old CGI's. Tomcat can do CGI, as explained here, with some limitations and res...
6,437,969
6,528,584
CORBA : how does client poll from server?
I am a total newbie in CORBA. I have written a simple c++ CORBA CLIENT and a CORBA SERVER. I would like the client to ask a status from time to time from the server. However, I have no idea how to do that and my google searches give me no luck. Can anybody tell me how to perform polling of client to server? or perhaps ...
In addition to the answers above, you could also use the CORBA event or notification services to receive asynchronous notifications from a remote server to avoid polling.
6,438,070
6,560,283
Pthreads and classes
I have made a Queue-class containing storage vectors and mutexes. To initialise the queue, a thread needs to be started. To make sure the thread is started correctly, the constructor waits for a signal. The thread function is a friend of the Queue-class. However, the signal is not registered when sent by the thread fun...
Have you initialised cond_init? Your code only shows initialisation of mutex_cond_init.
6,438,100
6,438,115
how find an object in std::vector
I have an object like below class MyClass{ int a; double b; }; and vector<MyClass> vMyClass; then I want search in vMyClass try to use algorithm function: if( std::find(vMyClass.begin(), vMyClass.end(), aiField) == vMyClass.end()) I also defined operator== int operator ==(Field &Left,Field &Right) { ...
They need to be const references. And memcmp is really, really bad- just perform a member-wise comparison.
6,438,174
6,438,252
Why is forward declaration of a class which will be a typedef not allowed?
If I want to use a pointer to a class and I dont do any operations on it, we can forward declare the class. But if that happens to be a typedef, why is it not allowed? In the following example, it compiles only i include the commented code but why does compiler wants to know about it at that point? How do I forward dec...
A typedef does not create a type it just adds a new name to an existing type, and you cannot forward declare it. I recommend that you read this answer to a different related question, I think it can help in understanding the differences between a typedef and a declaration of a user defined type. You can, on the other h...
6,438,188
6,438,440
C++ Container selection/choices
There is plenty of discussion on StackOverflow and other sites on what type of C++ container to use, with the not so shocking conclusion "it depends on your needs". Currently i'm using std::list on my interfaces, however i have no direct requirement on lists as opposed to vectors or deques; and in there lies my questio...
You should write such class if only you are going to make an option in your program to use different container type or create some kind of run-time optimization but in general you should know what the container is used for and so you know how it's used and that leads to what your needs are. Don't make a class that you ...
6,438,293
6,438,334
Implementing interface correct terminology
If I have a method that has as argument a Base class type I can pass it every object of a class that has extended that base class because a derived class is also a base class. So if I have a method that has as argument an Interface type I can pass it every object of a class that has implemented that interface because ...
Correct terminology would not be that class is also an interface but that class can behave exactly as the interface promises instead. With bases classes, it is like "I can work with any hard worker." With interfaces, it is like "I can work with anything that works hard."
6,438,402
6,438,431
Are (bool)(i & 1) and i % 2 == 1 same?
Are (bool)(i & 1) and i % 2 == 1 always same where i is int? Note: saying always I mean for all platforms (even when a byte is 16 bit) and for all standards of C and C++. Edit: For all standards of C and C++ where bool exist.
No. 1s' complement representation of int, the representation of -1 is 1 ... 10, so they differ. Anyway, i % 2 can be negative for negative i (indeed it's required to be in C99 when it's not 0), and hence not equal to 1 for negative odd numbers.
6,438,563
6,438,624
error: expected unqualified-id before '<' token|
I'm getting the following errors: preprocessor_directives.cpp|15|error: expected unqualified-id before '<' token| preprocessor_directives.cpp|26|error: expected `;' before "int"| ||=== Build finished: 2 errors, 0 warnings ===| #include <iostream> using namespace std; // Avoid. Using #define for constants #define MY_...
Move the inline keyword after the template keyword. template <typename T> inline T SQR2 ( T a ) { return a*a; }
6,438,641
6,438,714
Passing bit value from C#
I've a C++ interface having a public property "P" which accepts bit value like 5, 6,7 etc. Its documentation says:"Set bit mask of group type. Bit 5 is for 'a', Bit 6 is for 'b',etc." Am using this interface in my C# class and the type of this property "P" shown in the metadata is "char" in VS.Net. How do I pass the b...
The char type in C++ is always 8 bits, which presumably means that you'd use a byteto represent the same thing in C#. (This assumes that your C++ platform uses standard 8-bit bytes, since a C++ char is defined as being 1 byte, but a C++ "byte" isn't necessarily guaranteed to be 8 bits!) byte b = 0; b |= 1 << 5; // s...
6,438,648
6,439,102
Use strings to describe function parameters
I'm not sure if my Title for this question entirely describes accurately enough what I am trying to do but hopefully I'll explain myself better in this description. I want to be able to configure a CEdit control by reading in its dwStyle parameters as a string from an XML file i.e. :- CreateEx( WS_EX_CLIENTEDGE,L"EDI...
There is no built-in way, you have to do it yourself. Fist tokenize the string using | as delimiter, trim whitespace from substrings, determine the int value of each substring (follow up sbi's links for that, but plain old if-else-if will do as well), and finally combine all values with bitwise OR operator.
6,438,761
6,438,805
C++ inheritance and templates
I have a List template. I want to make a list of Jobs. However, I have different jobs when the only different thing is the function executeJob(). So I have a class Job: class Job{... ... public: .. virtual SomeType executeJob() = 0; } So it's actually an abstract class and in the derived classes all the private fields...
Simple, you can't take T in the constructor. You need a templated constructor, that takes the real class. Then you will call the constructor on the type of the parameter. If you don't have the type, and only pass around "Job", then you will have to switch to prototype based design with a virtual clone() method (instead...
6,438,792
6,438,838
Are there any free C++ compilers for MacOSX?
Is there any free C++ compilers to install in Mac OS (apple machine) please ..tell me the links to download & procedure to INSTALL.Since iam an new use for mac OS
The native compilers are gcc and llvm which are part of the XCode environment. While the compilers are free, the latest IDE is not but can be bought from the app store for something like $5.99 $4.99. If you don't need the latest version, a 3.x version of XCode, including gcc, should be on your OSX DVD. Just install i...
6,438,851
6,438,889
param and params usages in c++
I am studying classes in c++ and i came across this snippet of code and i wondering what param was used for. // vectors: overloading operators example #include <iostream> using namespace std; class CVector { public: int x,y; CVector () {}; CVector (int,int); CVector operator + (CVector); }; CVector:...
Param is the right operand of the + operator. Here is cleaner version of the code: #include <iostream> using namespace std; class CVector { public: int x,y; CVector (); CVector (int,int); CVector (const CVector&); CVector operator + (const CVector&) const; }; CVector::CVector() : x(0), y(0) {} C...
6,439,490
6,439,588
Is this an insertion sort?
I am reading "Introduction to Algorithms" and read about the insertion sort. I tried to implement it myself without first reading their solution. Here is my solution, is this insertion sort? #include <iostream> using namespace std; int main() { // initialize an unsorted array int a[] = {5,6,4,7,3,8,2,9,0,1};...
Your solution seems to be bubble sort, not insertion sort.
6,439,547
6,439,613
Why does this pointer/integer comparison generate a segmentation fault?
I am working on a program which generates a segmentation fault and I cannot understand why. If I remove the pointer declaration from "lowest" and "largest" variables and use them as pointerless integers the program works fine. However, as soon as I try to use pointers, problems arise and I receive a segmentation fault....
You are initialising lowest and largest to 0 and the dereference is accessing memory via a null pointer and so it falls over. Try this instead: if (!lowest || *i < *lowest) lowest = i; if (!largest || *i > *largest) largest = i; or: int *numbers = new int[arrLength]; lowest = largers = numbers; // initialise ...
6,439,626
6,440,089
Would randomising the seed create a more random number?
I have three questions about RNG. The first is what data is available to use as a seed. I have always used the time but there must be other easily available seeds. What easily available seeds are there in c++? If I reseeded the RNG at random intervals based on the next value to come out of the RNG and chose the seed a...
It depends on what you need rand for. For a lot of uses, time is perfectly adequate. For others less so. I'll usually read four bytes from /dev/random on a Unix machine, reverting to time if /dev/random isn't available. A more effective solution would be to use a higher resolution timer, and to hash in things like...
6,439,694
6,445,399
How to get GMT time in milliseconds using boost Date_Time?
Is there a simple way to get from boost Date_Time library a current GMT time in milliseconds? Here is one example which uses time_of_day, I don't want time_of_day but total time in GMT as long long int: boost::posix_time::ptime time = boost::posix_time::microsec_clock::universal_time(); boost::posix_time::tim...
There's nothing built-in that I can see, but as usual, it's trivial to implement: boost::posix_time::time_duration::tick_type milliseconds_since_epoch() { using boost::gregorian::date; using boost::posix_time::ptime; using boost::posix_time::microsec_clock; static ptime const epoch(date(1970, 1, 1)); ...
6,439,769
6,440,501
How to automatically infer the return type from a function type?
I'm using boost::python to create a Python wrapper of a C++ library. At some point, boost::python needs a pointer to a member function (or something compatible), like: template <class MyClass, typename ValueType> void (*setter_function)(MyClass&, ValueType) // This doesn't compile, but you got the idea. my_boost_pytho...
The return type cannot be automatically deduced in C++ and you cannot overload functions based on return type. In C++0x there is a new feature called decltype that might be of interest.
6,439,949
6,440,041
Setting bits in a double and compiling with optimization flags of g++
I am trying to set the bits in a double (IEEE Standard 754). Saying I want to 'build' a 3, I would set the 51-th and the 62-nd bit of the double floating point representation, so that I get in binary 1.1 * 2 that in decimal is 3. I wrote this simple main: int main() { double t; uint64_t *i = reinterpret_cast<uint64...
Yes, you are violating the alias rules of the language. Writing to an object of one type through a pointer to another type is not allowed (with some exceptions for char*). As you never write to any doubles in the code, the compiler is allowed to assume that t is never assigned a value. (And outputting that is wrong in ...