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 |
|---|---|---|---|---|
3,393,294 | 3,394,103 | Cross platform hardware accelerated 2d C++ app? | I know a decent amount of C++, and now I wanted to explore making a game. I was wondering what the best approach would be in terms of writing a hardware accelerated game that's still cross-platform (Windows/OSX/Linux). It's going to be a 2d game, but intensive enough that a CPU renderer probably wouldn't cut it.
I know... | That's nonsense guys
OpenGL IS cross-platform. No need for Qt or such. Only a few part must be adapted : the windowing API and the input API, which are the only functions that depend on OS-specific routines.
You have several possibilities :
roll your own. I don't recommend this, since you won't learn anything interes... |
3,393,434 | 3,394,036 | strftime/strptime problem | I've written a function to convert datetimes from one format to another -
int convertDateTime(char* source_fmt,char* dest_fmt,char* source,char* dest)
{
struct tm tmpptr;
if (strptime(source,source_fmt,&tmpptr) == NULL)
{
strcpy(dest,"");
return -1;
}
... | Update
The original answer (below) presumed that the "%y%j" format was used on the output (strftime) not the input (strptime). The mktime function will compute yday from valid info, but it doesn't work the other way.
If you want to decode something like that you need to do it manually. Some example code follows. I... |
3,393,438 | 3,393,464 | c++ programs developed and compiled with visual studio | I have Visual c++ 2010 express installed. I develop some apps with it (mainly console based for now).
I usually compile via the cl.exe command line option. Does these apps that I compiled with Visual C++ require .net framework to run?
Also what exactly is the object code file?
Lastly, I know that mono has Windows Form... | In order:
No, your apps will not require the .NET Framework as long as you stuck with pure C++ (i.e., avoided C++/CLI). If you linked to the C runtime library dynamically (/MD), however, your apps will require the "Microsoft Visual C++ 2010 Redistributable" to be installed.
Object code is an intermediate representatio... |
3,393,668 | 3,393,683 | QT Creator compile C++ file? Very simple question | #include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
This code works, but it run then close windows immediately. Need a fix :)
| add this getch() or getchar() before return and the consolw window will stay till you enter something
|
3,393,757 | 3,393,825 | How not to wait for other threads in OpenMP? | I am considering using OpenMP for multithreading in C++. But I wonder if there is a way tell a thread not to wait for other concurrent thread and continue with my program? (Maybe I can cancel/kill other threads?)
I am aware of the existence of "nowait" clause, but I want the decision of "wait" or "not to wait" to be do... | I'd would do it something along the lines of
if(conditon)
{
taskA_with_Barriers();
}
else
{
taskA_without_Barrier();
}
The condtion needs to be the same constant through out all threads.
If you need to be canceling Threads you might be using the wrong technolgy. Might also want to take a look at pthreads ... |
3,393,824 | 3,393,836 | How do I specify default argument values for a C++ constructor? | I have a constructor declaration as:
MyConstuctor(int inDenominator, int inNumerator);
and definition as
MyConstuctor::MyConstuctor(int inDenominator,
int inNumerator, int inWholeNumber = 0)
{
mNum = inNumerator;
mDen = inDenominator;
mWhole = inWholeNumber;
}
but i want to have an option of passing w... | What you need is:
//declaration:
MyConstuctor(int inDenominator, int inNumerator, int inWholeNumber = 0);
//definition:
MyConstuctor::MyConstuctor(int inDenominator,int inNumerator,int inWholeNumber)
{
mNum = inNumerator;
mDen = inDenominator;
mWhole = inWholeNumber;
}
This way you will be a... |
3,394,232 | 3,394,300 | Segmentation fault in equating a char pointer value to some char |
Possible Duplicate:
Why is this C code causing a segmentation fault?
char* string = "abcd";
now when i try to change some character of this string i get segmentation fault
*string = 'p';
or
string[0] = 'p';
string[0] = 52;
Can someone please explain me the reason that why is it happening.
Thanks
Alok.Kr.
| If you write char* string = "abcd"; the string "abcd" is stocked into the static data part of your memory and you can't modify it.
And if ou write char* string = 'p';, that's just wrong. First, you try to declare a variable with the same name (string) and, worse, you try to assign a char value to a char pointer variabl... |
3,394,259 | 3,394,302 | Weird behavior of right shift operator (1 >> 32) | I recently faced a strange behavior using the right-shift operator.
The following program:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdint.h>
int foo(int a, int b)
{
return a >> b;
}
int bar(uint64_t a, int b)
{
return a >> b;
}
int main(int argc, char** argv)
{
std::cout << "foo(... | It's likely the CPU is actually computing
a >> (b % 32)
in foo; meanwhile, the 1 >> 32 is a constant expression, so the compiler will fold the constant at compile-time, which somehow gives 0.
Since the standard (C++98 §5.8/1) states that
The behavior is undefined if the right operand is negative, or greater than or e... |
3,394,479 | 3,394,544 | Export function in c++ static library | My app links to a third party static library which without source code and I find that a function implemented in this library is exported in my exe using dumpbin.exe, just like a export function in a DLL.
I have tried to modify the header file provided by the library, got rid of all the __declspec(dllexport) stuffs, a... | No. You will have to recompile the library itself, changing the header will not affect the library binary code. What problems is the exported function causing you?
|
3,394,797 | 3,394,858 | Is it possible to pass an "unnamed" variable to a function? | Let's say there is the following function:
void SetTheSize(const SIZE *size) { ... }
Is there any way to call that function without specifying the SIZE variable? e.g.,
SetTheSize((const SIZE*)&{10, 10});
edit:
I should had mentioned that the SIZE is a struct, without SIZE(int, int) constructor.
| No, only thing nearest in C++ is to do like this:
void SetTheSize(const SIZE& size); //Change the pointer to const reference
And call it using an unnamed temporary variable: SetTheSize(SIZE(10,10));
|
3,395,023 | 3,397,763 | Throw (or correspondingly) on NULL function argument versus letting it all blow up? | In previous large-scale applications requiring high robustness and long up-times, I've always been for validating a pointer function argument when it was documented as "must never be NULL". I'd then throw an std::invalid_argument exception, or similar, if the argument actually was NULL in C++ and return an error code i... | It's an easy call. Getting a NULL pointer when none is expected is a clear sign of a bug in the program or a severely compromised program state. Either of which is going to require the programmer to do something about it. Throwing an exception will only ever work out well if it isn't caught. If it is caught you los... |
3,395,064 | 3,395,092 | Function that returns iterator from a map | I have a class with a map<K,V> variable which gets its value in the c'tor like so:
class Foo {
map<K,V> m;
Foo (map<K,V>& newM) : m(newM) {}
map<K,V>::iterator bar () { ... }
}
the function bar iterates through the map m, and return some an iterator to some element. I'm calling the function like this:
std:... | It will point to the new map, as you copied the map into variable m in the ctor of the class. The statement m(newM) in the initialization list invokes the copy constructor of the std::map class and copies individual elements of the passed map into the destintation map m. Hence when you invoke bar method, it will return... |
3,395,180 | 3,396,082 | What is an iterator's default value? | For any STL container that I'm using, if I declare an iterator (of this particular container type) using the iterator's default constructor, what will the iterator be initialised to?
For example, I have:
std::list<void*> address_list;
std::list<void*>::iterator iter;
What will iter be initialised to?
| By convention a "NULL iterator" for containers, which is used to indicate no result, compares equal to the result of container.end().
std::vector<X>::iterator iter = std::find(my_vec.begin(), my_vec.end(), x);
if (iter == my_vec.end()) {
//no result found; iter points to "nothing"
}
However, since a default-c... |
3,395,468 | 3,395,800 | Overloading operator<< to accept a template function | I'm trying to be able to write an extensible grammar using functions, but can't seem to find the right syntax for accepting a template function. I'm using Visual C++ 2008. It will accept a variable of the same type as the template function, or a similar non-template function, but not the template function itself.
Err... | Your code looks OK to me, and g++ is fine with that too. This seems to be weird overload resolution bug in Visual Studio. VS2005 seems to have the same problem. A possible workaround is (tested with VS2005):
template<class T>
T id(T t) {return t; }
int main ()
{
ExpressionParticle<int> (*p)();
p = Expression<... |
3,396,077 | 3,396,154 | Can I map lists in Qt? | This is already fairly concise, but it would be awesome if I could map the list a la Ruby. Say I have a QStringList myStringList which contains things like "12.3", "-213.0", "9.24". I want to simply map the whole thing using toDouble without having to iterate. Does Qt have a method for this?
// i.e. I would love a one-... | As far as I can tell, QT's containers have an interface compatible with the Standard containers, so you should be able to use Standard algorithms on them. In this case, something like
std::transform(myStringList.begin(),
myStringList.end(),
std::back_inserter(myDoubleList),
... |
3,396,216 | 3,396,272 | How to retrieve the HD vendor/serial using Windows API | I'm talking about the physical disk drive, not volume/partition/logical drive. So that usually-suggested GetVolumeInformation function is not applicable in my case.
To be exact: I'm working directly with the disk which has not been partitioned yet.
I open a handle to it via CreateFile function:
hDisk = CreateFile(
... | Take a look at DiskId32. Source code is there also. The idea is to use DFP_RECEIVE_DRIVE_DATA with DeviceIoControl.
|
3,396,330 | 3,981,641 | Where to put BOOST_CLASS_EXPORT for boost::serialization? | I'm trying to serialize a pointer to a polymorphic class Shape. So I need to use the BOOST_CLASS_EXPORT macro to define a GUID for each subclass. The problem: where to put it?
Let me show a minimal test case first:
shapes.hpp
#include <boost/serialization/access.hpp>
#include <boost/serialization/base_object.hpp>
#incl... | I ended up putting all the serialization code in a header s11n.h that is included from the CPP file that invokes the serialization. Essentially, the EXPORT_IN_MAIN scenario I sketched above, but with the BOOST_CLASS_EXPORT macro invocations in a different file.
This only works as long as only one compilation unit inclu... |
3,396,393 | 3,396,462 | C++ - basic container question | How should the following cases be handled:
I have some geometrical storage, which is a template from vertex type.
template <typename T> struct Geometry {
std::vector<T>& GetVertices() { ... }
const void* RawVertices() const { ... }
}
This works fine, unless I want to store different types of geometries (for instanc... | Since a container is tied to one type of data it can contain, you could create a class GeometryBase from which all Geometry<T> are derived and then store GeometryBase pointers in your container.
struct GeometryBase
{
// Non-template methods might go here.
// Don't forget to declare the base class destructor vir... |
3,396,610 | 3,396,865 | Memory corruption when using boost::shared_ptr in a multithreaded environment | * glibc detected * malloc(): memory corruption (fast): ***
This is the error I get when, in a multithreaded environment, I execute this portion of code:
/// Some declarations
typedef boost::shared_ptr<Object> ObjectPtr;
ObjectPtr getObject()
{
return ObjectPtr(new Object);
}
/// What is actually executed in a thr... | I don't know if this helps your specific problem, but it is sometimes desirable to use make_shared and avoid the new.
so:
return boost::make_shared<Object>(/* any arguments to constructor here */);
Additionally, you could try std::shared_ptr instead of boost::shared_ptr. They're probably exactly the same, but maybe no... |
3,396,758 | 4,247,661 | Tasks on Thread Building Blocks | Here is the example code:
#include <iostream>
#include <list>
#include <tbb/task.h>
#include <tbb/task_group.h>
#include <stdlib.h>
#include <boost/thread.hpp>
using namespace tbb;
long fib(long a)
{
if (a < 2) return 1;
return fib(a - 1) + fib(a - 2);
}
class PrintTask
{
public:
void operator()()
{
... | Yes, this is the expected behavior.
TBB is a library designed to parallelize code for PERFORMANCE. It is not designed for asynchronous tasks - the official documentation states that you should use another library, eg pthreads, for such tasks (or boost::thread, in your case).
For maximum performance, it does not make an... |
3,396,876 | 3,397,682 | Missing mingwm10.dll | I am coding a c++ project with Qt Creator. Everything is working fine (debug, release), but when I run the compiled .exe directly (go to exe file and run it) it says mingwm10.dll is missing.
What can I do about this problem?
| Here is what you could do:
as chalup said, place you MINGW bin directory to you local/global PATH variable like that: My Computer|System Properties|Advenced|Environment Variables|System variables - select PATH string and press Edit button. After dialog appeared, add something like that - C:\MinGW\bin
Build you app wit... |
3,396,921 | 3,403,178 | Why am I not getting events for a checkbox click in a treeview control? | In my MFC dialog, i have a tree view control with checkboxes. Clicking the checkbox does not raise the NM_CLICK nor the TVN_SELCHANGED events, which I had hoped it would do.
How do I correctly determine when a checkbox is checked/unchecked in a tree view control?
| Handle mouse click normally and in the handler identify the current item and then use TreeView_GetCheckState to get its checked state.
|
3,396,939 | 3,396,996 | Replacing existing raw pointers with smart pointers | Note: This may sound dumb.
I have an application which uses raw pointers and there are lots of memory leaks in the application.
Now my question is how easy would it be to replace the existing raw pointers with the smart pointers.
And would just replacing them help is reducing memory leaks caused by not freeing dynamic... | Using smart pointers would certainly be a good start to cleaning up your application, but they're not a cure-all. Lots of memory leaks could just be carelessness in an otherwise well designed program, but more likely you have significant design issues and the memory leaks are a symptom of that. When you switch to sma... |
3,396,958 | 3,397,410 | How to speed up g++ compile time (when using a lot of templates) | This question is perhaps somehow odd, but how can I speed up g++ compile time? My C++ code heavily uses boost and templates. I already moved as much as possible out of the headers files and use the -j option, but still it takes quite a while to compile (and link).
Are there any tools out there which analyse my code and... | What has been most useful for me:
Build on a RAM filesystem. This is trivial on Linux. You may want to keep a copy of common header files (precompiled or the actual .h files) on the RAM filesystem as well.
Precompiled headers. I have one per (major) library (e.g. Boost, Qt, stdlib).
Declare instead of include class... |
3,396,966 | 3,413,250 | Dynamic linking and Python SWIG (C++) works in C++ fails in python | I have a library for which I have created a python wrapper using SWIG. The library itself accepts user provided functions which are in an .so file that is dynamically linked. At the moment I'm dealing with one that I have created myself and have managed to get the dynamic linking working... in C++. When I attempt to ru... | A solution is to make sure that python is preloading the C++ main library in the global scope.
This is not a very elegant solution, and I don't want to do it, but it makes it work for the moment.
After a little poking around here and recognising the LD_LIBRARY_PATH environment variable that I have to set every time I s... |
3,397,002 | 3,397,520 | Question about abstract factories and injection | This is similar to one of my other questions, but different enough I think to warrant a new question.
Basically I am writing a user interface, and my user interface has nodes that can be selected. When a node is selected, the user interface ends up with an abstract node base class "INode". From this I get a factory b... | How about
class FactoryBase { /* interface */ }
template <typename NodeType> class Factory : public FactoryBase {
// Default implementation.
}
// Add appropriate specializations for all relevant nodetypes, if needed.
template <typename NodeType> inline Factory<NodeType> getFactory(NodeType*) {
return Factory<NodeT... |
3,397,098 | 3,397,137 | Pointer array and sizeof confusion | Why does the following code output 4?
char** pointer = new char*[1];
std::cout << sizeof(pointer) << "\n";
I have an array of pointers, but it should have length 1, shouldn't it?
| pointer is a pointer. It is the size of a pointer, which is 4 bytes on your system.
*pointer is also a pointer. sizeof(*pointer) will also be 4.
**pointer is a char. sizeof(**pointer) will be 1. Note that **pointer is a char because it is defined as char**. The size of the array new`ed nevers enters into this.
Not... |
3,397,513 | 3,397,854 | How do I access return value of a Java method returning java.lang.String from C++ in JNI? | I am trying to pass back a string from a Java method called from C++. I am not able to find out what JNI function should I call to access the method and be returned a jstring value.
My code follows:
C++ part
main() {
jclass cls;
jmethodID mid;
jstring rv;
/** ... omitted code ... */
cls = env->FindCl... | You should have
cls = env->FindClass("ClassifierWrapper");
Then you need to invoke the constructor to get a new object:
jmethodID classifierConstructor = env->GetMethodID(cls,"<init>", "()V");
if (classifierConstructor == NULL) {
return NULL; /* exception thrown */
}
jobject classifierObj = env->NewObject( cls, ... |
3,397,723 | 3,397,795 | C++ Function Pointer Syntax | I am trying to create a function in VC++ that takes a function pointer but I keep getting syntax errors.
The declaration in my header file looks like this:
void ApplyFuncToCellsInSelection(void(*func)(CPoint, *CSpreadWnd));
Here is the definition:
void CSpreadWnd::ApplyFuncToCellsInSelection(void(*func)(CPoint, *CSpr... | It's usually a good idea to define a typedef for your function pointer type. It helps using it in further declarations, and avoids having to change it twice when you write an error. Here, you put the asterisk on the wrong side of CSpreadWnd.
typedef void (*MyFuncPtr)(CPoint, CSpreadWnd*);
void ApplyFuncToCellsInSelecti... |
3,397,765 | 3,397,786 | Copy constructor problem | I tried to use copy constructor using statement:
X y = X();
But copy constructor is not being called. I am using g++ 4.1.0. I set both X(const X&) and X(x&) constructor in the class.
Is this supposed to work or I am doing some very basic problem in the code?
My code for the class is
class A
{
public:
int i;
A(i... | The compiler is permitted to elide the call to the copy constructor in certain situations. Initializing an object from a temporary is one of them. In this case, the temporary is simply constructed in-place instead of constructing a temporary and then copying it into the named object.
You can call the copy constructor... |
3,398,105 | 30,137,474 | Calling CoCreateInstance during service startup | I have a windows service, that makes several COM+ calls during initialization. On some systems this windows service causes a deadlock during startup.
At least one service or driver failed during system startup
The problem with calling CoCreateInstance during service startup is that it might require other services to ... | The easy solution is to configure your COM-application-service to have service-startup set to "Automatic (Delayed Start)" (DelayedAutoStart). Then it will not be part of the "essential" services required for Windows to run. It was introduced with Windows 2008.
|
3,398,285 | 3,398,323 | C++ variable declaration and initialization rules | Consider the following ways of declaring and initializing a variable of type C:
C c1;
C c2;
c2 = C();
C c3(C());
C c4 = C();
Are all of these completely equivalent to each other, or can some of these differ depending on the exact definition of C? (assuming it has public default and copy constructors).
| These mean:
C c1; // default constructor
C c2; // default constructor
c2 = C(); // default constructor followed by assignment
C c3(C()); // default constructor possibly followed by copy constructor
C c4 = C(); // default constructor possibly followed by copy constructor
Note the compiler can elide copy const... |
3,398,304 | 3,398,595 | Converting QString/QChar to be accepted with Crypto++ | I want to make program that encrypts (later decrypts) user inputted string.
Here is beginning for encryption:
QString getData = ui->text->toPlainText(); //Data to process
std::string output; //Result will be Base32 encoded string, so std::string is fine.
Now, I have to convert QString to char* or std::string so it can... | I think you're losing data when converting from QString to QByteArray. Try this:
QByteArray data = getData.toUtf8();
...
getData = QString::fromUtf8( output.c_str() );
|
3,398,819 | 5,184,182 | Sort by proxy (or: sort one container by the contents of another) in C++ | I have a set of data which is split into two arrays (let's call them data and keys). That is, for any given item with an index i, I can access the data for that item with data[i] and the key for that item with keys[i]. I cannot change this structure (eg, to interleave keys and data into a single array), because I need ... | It turns out that Boost contains an iterator which does pretty much what the paired_iterator from my other answer does:
Boost.Iterator Zip Iterator
This seems like the best option.
|
3,398,825 | 3,398,832 | How do I call "operator->()" directly? | For some strange reason, I need to call the operator->() method directly. For example:
class A {
public:
void foo() { printf("Foo"); }
};
class ARef {
public:
A* operator->() { return a; }
protected:
A* a;
};
If I have an ARef object, I can call foo() by writing:
aref->foo();
How... | aref.operator->(); // Returns A*
Note that this syntax works for all other operators as well:
// Assuming A overloads these operators
A* aref1 = // ...
A* aref2 = // ...
aref1.operator*();
aref1.operator==(aref2);
// ...
For a cleaner syntax, you can a implement a Get() function or overload the * operator to allow fo... |
3,398,837 | 5,237,142 | ExTAPI: lineRegister returns before line is registered | I am using the extended TAPI function lineRegister to register a GPRS radio on the network after powering the radio on using lineSetEquipmentState. The lineRegister function is returning successfully before the network is actually registered.
The asynchronous lineRegister function first returns a positive number ind... | The quality of the TAPI implementation is very OEM dependent. You may find another device where it works the way you expect. But, if this is the one that you expect your application will be used on, then you will probably have to poll.
-PaulH
|
3,398,937 | 3,398,971 | Simple recursion question | Let's say we have a simple recursion like.
int x(int a){
if(a<10)
x(a+1);
else
!STOP!
b++;
return b;
}
Globaly:
int b=0;
In main we could have something like this:
int p=x(1);
Is there any way to stop the recursion so that the p will be 0, this means that "b++" will never be executed.
I'll ... | Why wouldn't you do this?
int x(int a){
if(a<10) {
x(a+1);
b++;
}
return b;
}
The thing is, though, you're modifying a global in a recursive routine, which is not especially threadsafe and pretty sloppy. You're returning a value that is always ignored except by the top level caller. You're also ... |
3,399,217 | 3,399,248 | C++ Pass by Reference Program | IBM explains C++ pass by reference in the example below (source included).
If I changed void swapnum... to void swapnum(int i, int j), would it become pass by value?
// pass by reference example
// author - ibm
#include <stdio.h>
void swapnum(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}
int main(void) {... | Any swapping performed if you pass by value are only affected or seen within the function they are passed into and not the calling code. In addition, once you return back to main you will see that a and b did not swap. That is why when swapping numbers you want to pass by ref.
If you are just asking if that is what i... |
3,399,574 | 3,399,838 | What are the differences between the various boost ublas sparse vectors? | In boost::numeric::ublas, there are three sparse vector types.
I can see that the mapped_vector is essentially an stl::map from index to value, which considers all not-found values to be 0 (or whatever is the common value).
But the documentation is sparse (ha ha) on information about compressed_vector and coordinate_ve... | replace matrix with vector and you have the answers
http://www.guwi17.de/ublas/matrix_sparse_usage.html
|
3,399,646 | 3,399,887 | Should I randomly shuffle before inserting into STL set? | I need to insert 10-million strings into a C++ STL set. The strings are sorted. Will I have a pathological problem if I insert the strings in sorted order? Should I randomize first? Or will the G++ STL implementation automatically rebalance for me?
| The only question I have: do you really need a set ?
If the data is already sorted and you don't need to insert / delete elements after the creation, a deque would be better:
you'll have the same big-O complexity using a binary search for retrieval
you'll get less memory overhead... and better cache locality
On binar... |
3,399,711 | 3,399,813 | Starting vg dev, which language? | Hey, I know someone who is looking into developing simple video games on his pc, and then eventually, hopefully port or develop some on the XBOX 360 indie center, using XNA studio.
So, I have heard about C#? How easy it for a beginner?
C++ is pretty good isn't it? But I've heard it's QUITE deep, broad, and sounds pre... | To put it simply:
For a beginner looking toward PC and XBOX, then the answer is XNA studio, using the C# language.
Microsoft provides a free version of Visual Studio developer environment:
http://www.microsoft.com/express/Downloads/#2010-Visual-CS
C# is a very nice modern language, and a very good first-time language, ... |
3,399,821 | 3,399,852 | gcc -O4 optimization flag | What's the meaning of the -O4 optimization flag in gcc (3.2.3)? What's the difference to O3? When would you use one vs. the other?
The man pages only mention O, O0-3, Os, no word of the mysterious O4. Thanks!
| There is no -O4 in 3.2.3.
Everything above -O3 results in -O3 being chosen.
|
3,400,015 | 3,400,103 | undefined reference with member implelementation of a templated class | This is wholy mysterious to me. I'm using g++ on ubuntu, and this is some of my code (with class names change, but nothing else because I'm still using stubs everywhere):
Bob.hpp
template <class A>
class Bob : public Jack<Chris, A>
{
public:
Bob(int x1, int x2, float x3 = 1.0, float x4 = 2.0, float x5 = 3... | You need to move the code from Bob.cpp into Bob.hpp. When the compiler sees the definitions of Bob::Bob and Bob::~Bob in Bob.cpp, it does not know what types of Bob are actually going to be instantiated (i.e. Bob<int> vs Bob<SomeClass> and the code for them isn't generated.
Alternatively, you can still place the cod... |
3,400,025 | 3,608,307 | msvcp90d.dll is missing msvcr90d.dll | I had a DLL project on one machine, and copied it to another with freshly installed VS2008. The project builds, but I cannot debug it. Dependecy Walker shows that my DLL sees msvcr90d.dll, but msvcp90d.dll does not see the same DLL. But if I open msvcp90d.dll in separate window then msvcr90d.dll is visible to msvcp90d.... | I copied the latest project to the computer that exibited the problem, and it turns out that there is no issue after all. Dependancy Walker still shows the same yellow icons as before, but the latest project can be debugged just fine. The problem was obviously in my code, possibly function signature mismatch between C#... |
3,400,086 | 3,400,107 | C++ Runtime Error caused by adding new function (which isn't ever used beyond it's definition) | This has been stumping me for a bit. I have a Class written in C++.
Everything works fine.
Next, I add function void A(); to the header file and run, It still works fine.
However as soon as I add a new function definition to the CPP file, I get a runtime error every single time. (specifically: Process terminated with ... | Usually such an error is the result of memory corruption somewhere in the program.
|
3,400,130 | 3,400,549 | Help with DLL to Lib | I have converted a dll to lib. I gave it the lib and dll file and told it to remove the unnecessary stuff. I #included the .h file it created, and called GLU_DLLMAIN() in InitInstance just like I saw in the samples, but it still crahes on start up when it tries to initialize my static GLU object. What am I doing wrong?... | The binary soft tool cannot so far as I can see work in all cases, so perhaps you have one of these fringe cases. On the other hand the .lib must be build with the same compiler settings as the executable to which is was linked, including assumptions about versions of standard libraries used.
Perhaps your issues are ge... |
3,400,200 | 3,400,265 | Convert ASCII string into Decimal and Hexadecimal Representations | I need to convert an ASCII string like... "hello2" into it's decimal and or hexadecimal representation (a numeric form, the specific kind is irrelevant). So, "hello" would be : 68 65 6c 6c 6f 32 in HEX. How do I do this in C++ without just using a giant if statement?
EDIT: Okay so this is the solution I went with:
in... | You can use printf() to write the result to stdout or you could use sprintf / snprintf to write the result to a string. The key here is the %X in the format string.
#include <cstdio>
#include <cstring>
int main(int argc, char **argv)
{
char *string = "hello2";
int i;
for (i = 0; i < strlen(string); i++)
... |
3,400,277 | 3,400,533 | How do I set GNU G++ compiler in Visual studio 2008 | How do I set my Visual studio 2008 compiler to GNU GCC. Can I also make it specific to projects? I didn't find any conclusive answer.
Thank you.
| You can't use the compiler directly.
You can, however, invoke a makefile instead of using the built-in build system.
Example of configuration:
Install MinGW (I guess this step is already done), including mingw32-make
Create a makefile for mingw32-make called MinGWMakefile , with 3 targets: clean, build, and rebuild.... |
3,400,287 | 3,402,002 | Partial specialization of existing metafunction using mpl | Maybe I'm not all there today, but I'm wondering how to get this to work.
I'd like to partially specialize range_mutable_iterator and range_const_iterator from the boost library but only for specific types that I'd rather avoid mentioning explicitly, instead only letting the partial specialization be chosen if the enab... | In order to partially specialize a template the compiler must match the actual template arguments to the existing specializations, with the aim to select the best match. This is just not possible if the template argument in the specialization is used just as the (template) parameter to a dependent type. So, the compile... |
3,400,309 | 3,400,364 | find c++ execution time | I am curious if there is a build-in function in C++ for measuring the execution time?
I am using Windows at the moment. In Linux it's pretty easy...
| The best way on Windows, as far as I know, is to use QueryPerformanceCounter and QueryPerformanceFrequency.
QueryPerformanceCounter(LARGE_INTEGER*) places the performance counter's value into the LARGE_INTEGER passed.
QueryPerformanceFrequency(LARGE_INTEGER*) places the frequency the performance counter is incremented ... |
3,400,453 | 3,400,603 | How has C++ changed in the past decade? | I've barely/rarely used C++ in the past decade, and now it looks like I'll be doing something in it again. I'm looking forward to it, but have to wonder how it's changed since I last used it.
Are there any good / brief web pages, blog posts, or even books on how C++ has changed in the past decade?
Please note this que... | While the official standard hasn't changed much over the past decade or so, there are several things of importance that have happened:
while it's not an official standard yet, an upcoming new standard (commonly called C++0x) is 'around the corner'. GCC and MSVC 2010 have incorporated significant parts of that new sta... |
3,400,484 | 3,414,397 | Windows C++ Should I use WinHttp library or XmlHttp from MSXML? | A rather simple question. Should I use the WinHttp library to make a web service request in my C++ programs or should I use the IXmlHttpRequest interface in the msxml library to send web service requests? Obviously the WinHttp library provides a lot more fine control compared to the IXmlHttpRequest library. But the Xml... | It depends whether you are accessing the service on secure channel i.e. HTTPS or simple one i.e. HTTP.
As per MSDN (http://msdn.microsoft.com/en-us/library/ms891732.aspx), IXMLHttpRequest supports only HTTP.
Note IXMLHTTPRequest does not support secure website access. To access a secure website, use the WinINet ... |
3,400,675 | 3,401,068 | DuplicateHandle: need to OpenProcess, but the access is denied | Using windows hooks I send messages to my application, which is notified about Windows events by every application on the system.
To execute marshal of the message parameters, I use shared memories. The external process calls DuplicateHandle, but for sharing the handle with my application instance, it shall call OpenPr... | I don't understand why you don't use named shared memory. If your shared memory objects have a name, then this objects can be opened without the usage of DuplicateHandle.
If you do have to use DuplicateHandle and need be able to use OpenProcess(PROCESS_DUP_HANDLE, FALSE, pId) inside of any process I find that you shoul... |
3,400,823 | 3,400,912 | Searching for a QObject | I'm working on a multi-threaded Qt application and would like to connect a signal in a thread with slot in another thread. My problem is that I only have the string used to set the QObject:objectName in the signaling thread that is defined in a project wide constants file.
My overall goal is to avoid having to pass po... | Trees of objects must all belong to the same thread. The detailed description of QObject states:
Use the moveToThread() function to change the thread affinity for an object and its children (the object cannot be moved if it has a parent).
I have seen an interesting solution to the problem of finding objects implement... |
3,400,851 | 3,400,896 | Execution time limit for a Lua script called from the C API | luaL_loadfile(mState, path.c_str());
lua_pcall(mState, 0, 0, 0);
Is there a way to put an execution time limit (say 10-20 seconds) for those two C++ statements, that load and then execute a lua file?
Since the Lua file is untrusted I don't want a malicious user to hang the program indefinitely with an infinite loop in... | There's lua_sethook which can be used to tell the interpreter to call a hook after every 'count' instructions executed. This way you can monitor the user script and terminate it if it eats up its quota:
int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);
This can also be used from Lua:
debug.sethook(func... |
3,401,032 | 3,430,580 | shared_from_this called from constructor | I have to register an object in a container upon its creation.
Without smart pointers I'd use something like this:
a_class::a_class()
{
register_somewhere(this);
}
With smart pointers I should use shared_from_this but I can't use that in the constructor.
Is there a clean way to solve this problem? What would you d... |
a_class is responsible for creating and destroying b_class instances
...
a_class instance "survives" b_class instances.
Given these two facts, there should be no danger that a b_class instance can attempt to access an a_class instance after the a_class instance has been destroyed as the a_class instance is responsi... |
3,401,099 | 3,401,132 | C++ binding question | Is there any way to make boost::bind work with std::fill?
I tried the following, but it didn't work:
boost::bind(std::fill, x.begin(), x.end(), 1);
| The problem is that std::fill is a template function. Template functions don't really exist, so to say, until they're instantiated. You can't take the address of std::fill because it doesn't really exist; it's just a template for similar functions that use different types. If you provide the template parameters, it wil... |
3,401,101 | 3,401,141 | Best way to parse a large floating point file stored in ASCII? | What is the best way to parse a large floating point file stored in ASCII?
What would be the fastest way to do it? I remember someone telling me using ifstream was bad, because it worked on a small number of bytes, and it would be better to just read the file into memory first. Is that true?
Edit: I am running on Wind... | I think your first concern should be how large the floating point numbers are. Are they float or can there be double data too? The traditional (C) way would be to use fscanf with the format specifier for a float and afaik it is rather fast. The iostreams do add a small overhead in terms of parsing the data, but that is... |
3,401,341 | 3,401,430 | binary file encryption problem | i'm having a problem while encrypting some data in the file. i'm using simple xor for that.
lets say i have this struct:
struct MyFile{
char fileName[128];
int account;
float balance;};
saving this as a binary file is working properly but when i use xor to encrypt the filename in the struct and save the struct to hd t... | Note that you need to open the files in binary mode ("rb"/"wb" instead of "r"/"w" for fopen). Windows C implementations in particular have problems regarding \n<->\r\n conversion.
It is also a good idea to use unsigned chars for arithmetic and bitwise operations; anything but 8-bit two's complement signed chars might c... |
3,401,385 | 3,401,398 | std::sort on std::vector<std::string> | I have a std::vector<std::string> which would contain numbers and characters (single char). I would want to have numbers sorted first followed by the characters...so I have a jumbled up vector of strings as an input and after sort I want it like 1,2,3,5,7,9,10,A,B,C,D.
But I guess sort also compares the sizes of the in... | Write a non-lexicographical comparison routine and pass it along with the iterators to std::sort.
|
3,401,653 | 3,401,686 | Stl methods with cmath functions | I was trying to write an STL method to take the log of a vector:
for_each(vec.begin(),vec.end(),log);
But I get
no matching function for call to ‘for_each(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<dou... | Yes. You can cast the function to the appropriate type:
for_each(vec.begin(),vec.end(),(double(*)(double))log);
Another possibility would be creating your functor that would accept any type:
struct log_f
{
template <class T> T operator()(const T& t) const { return log(t); }
};
for_each(vec.begin(),vec.end(), log_f(... |
3,401,722 | 3,401,755 | Conversion from unsigned int to float | warning C4244: '=' : conversion from 'unsigned int' to 'float', possible loss of data
Shouldn't a float be able to handle any value from an int?
unsigned int: 0 to 4,294,967,295
float 3.4E +/- 38 (7 digits)
Wiki:
The advantage of floating-point representation over fixed-point (and
integer) representation i... | 'unsigned int' and 'float' both use 32 bits to store values. Since a float has a larger range, it necessarily sacrifices some precision. This means that there are some unsigned int values that cannot be accurately represented in a float. MSDN provides some more details.
|
3,401,878 | 3,401,891 | why didn't the positive terms get displayed in this asbolute program | Let's start with this demo
#include <iostream>
using namespace std;
template <class T>
void abs(T number)
{
if (number < 0)
number = -number;
cout << "The absolute value of the number is " << number << endl;
return;
}
int main()
{
int num1 = 1;
int num2 = 2;
double num3 = -2.1333;
float n... | There is an abs function built-in to the standard library:
int abs ( int n );
long abs ( long n );
The compiler is going to use these versions in preference to your templated function since non-templated functions are more specific than templated functions, and thus take precedence in function overload resolution.
I r... |
3,401,881 | 3,401,896 | how to show the device keyboard using C++ MFC for Windows CE device? | How to show the device keyboard using C++ MFC for Windows CE/Windows Mobile device to type in?
thanks
| The API you probably want is SipShowIM().
|
3,401,894 | 3,401,906 | Cleaning Up After OpenGL on iPhone | Right now, I'm playing with OpenGL ES on the iPhone using Oolong Engine. This might be a silly question, but how necessary is it to clean up after OpenGL when the app exits? My problem is that I have a static vector that manages loading models, and loosely ensures that models aren't loaded twice. Because of this, all t... | When the actual app exits, all resources get cleaned up with it, including all GL stuff. Don't worry, the OS wouldn't let your rogue app accidentally leak a bunch of GPU resources.
Managing resources in Open GL in general is something you should do of course during the course of your app's life, but it sounds like you ... |
3,401,950 | 3,409,775 | Configuring a CMake C++/Java Project to work with Eclipse | I'm currently trying to set up a VTK project that has pre written Cmake makefiles to work with Eclipse. The code that I need to use is in both C++ and Java, but my main concern right now is actually to be able to translate the existing project into something that Eclipse can understand with all the dependencies etc.
Pl... | First of all you need the Eclipse CDT package.
Then you need to generate the Eclipse CDT project: cmake -G "Eclipse CDT4 - Unix Makefiles" /path/to/source/dir.
The last step you need to do is import the project in the current workspace: File -> Import... -> Existing Projects Into Workspace.
|
3,401,983 | 3,401,987 | Can I implement multiple callback interfaces in C++? | Can I implement multiple callback interfaces in C++ for Java?
| The answer is no. You can only implement one callback interface in C++ and there are some very good reasons for it. The callback mechanism relies on the fact that there is a Java type that implements the callback interface. This Java type has all the knowledge to delegate callback invocations to a C++ object that is ma... |
3,402,178 | 3,402,194 | Omitting return statement in C++ | I just had some weird behavior from a version of g++ for Windows that I got with Strawberry Perl. It allowed me to omit a return statement.
I have a member function that returns a structure consisting of two pointers, called a boundTag:
struct boundTag Box::getBound(int side) {
struct boundTag retBoundTag;
retB... | Omitting the return statement in a non-void function [Except main()] and using the returned value in your code invokes Undefined Behaviour.
ISO C++-98[Section 6.6.3/2]
A return statement with an expression can be used
only in functions returning a value; the value of the expression is
returned to the c... |
3,402,195 | 3,402,250 | how to pass a member function as a function pointer? | I want add a logger function to a worker class,
how to pass a member function as a function pointer?
use mem_fun?
here is the code sample:
class Work{
public:
void (*logger) (const string &s);
void do_sth(){if (logger) logger("on log")};
};
classs P{
public:
void log(const string &s)(cout << s);
};
int ma... | You can accomplish this using std::function and std::bind:
#include <functional>
#include <iostream>
#include <string>
class Work {
public:
std::function<void(const std::string&)> logger;
void do_sth() { logger("on log"); }
};
class P {
public:
void log(const std::string& s) { std::cout << s; }
};
int ma... |
3,402,248 | 3,402,258 | Differentiation between const and non-const versions of methods in C++ | I have a few questions regarding differentiation between const and non-const versions of methods in C++.
Example:
MyObject* MyClass::objectReference()
const MyObject* MyClass::objectReference() const
My questions are:
Is there any way at all to differentiate between which version of the method is called manuall... | I don't know about doxygen; though here is what I know.
If there's only a non-const version, it simply can't be called on a const object.
If there's only a const version, it can be called on both const and non-const objects.
If there's both, the non-const version will be called on non-const objects, and the const vers... |
3,402,318 | 3,402,328 | const_cast vs static_cast | To add const to a non-const object, which is the prefered method? const_cast<T> or static_cast<T>. In a recent question, someone mentioned that they prefer to use static_cast, but I would have thought that const_cast would make the intention of the code more clear. So what is the argument for using static_cast to make ... | Don't use either. Initialize a const reference that refers to the object:
T x;
const T& xref(x);
x.f(); // calls non-const overload
xref.f(); // calls const overload
Or, use an implicit_cast function template, like the one provided in Boost:
T x;
x.f(); // calls non-const overload
imp... |
3,402,338 | 3,402,372 | template function specialization default argument | template <typename T> void function(T arg1,
T min = std::numeric_limits<T>::min(),
T max = std::numeric_limits<T>::max())
{
}
template <> void function<int>(int arg1, int min,int max)
{
}
int main(int argc,char* argv[])
{
function<int>(1);
}
it give syntax error C2689 and C2059 on function default argum... | There is nothing wrong with the code; Comeau Online, Intel C++ 11.1, and g++ 4.1.2 compile it successfully.
I would guess that it is a bug in the compiler. I recently submitted a related, but slightly different bug report against the Visual C++ 2010 compiler.
As a workaround, you can wrap the calls:
template <typenam... |
3,402,460 | 3,402,469 | Best Data structure in C++ to find a string in a dictionary | I am a beginner to C++. Can some one tell me a best data structure in C++ to store all words in a dictionary and find if a word is present in the dictionary. I know hash tables are the best but I dont know which data structure uses them ?
Thank you very much in advance.
| Your C++ implementation's standard library may have unordered_set or hash_set. They are essentially the same thing; the former is part of the forthcoming C++0x standard and is supported by some of the latest compilers, the latter is from the original SGI STL and is included in many standard library implementations.
|
3,402,554 | 3,402,665 | Are there any problems with this overload of operator new? | I was thinking about some memory pool/allocation stuff I might write so I came up with this operator new overload that I want to use to facilitate reuse of memory. I'm wondering if there are any problems you guys can think of with my implementation (or any other possible ones).
#include <cstddef>
namespace ns {
st... | SHOULD be good, as long as you don't try something crazy and try to renew a subclass. Since you said this is for a pool, it should be fine.
That said, my only question is - what is more legible? This is a question of taste, but imagine that somebody else might need to look at the code. You're basically just contracting... |
3,403,008 | 3,403,035 | how to send the searched string completely to google search (Qt)? | I send the url to find the page what I need. Hovewer there is a misunderstanding with google.
QString baseurl("http://blogsearch.google.com/blogsearch?hl=tr&ie=UTF-8&q=C++");
I send searched string q=C++; but google search the string only C, it does not search C++.
What to do for change the searching key C to C++ ?
| Try passing at least the query part of the url to QUrl::toPercentEncoding.
Even better, try:
QUrl url("http://blogsearch.google.com/blogsearch");
url.addQueryItem("hl", "tr");
url.addQueryItem("ie", "UTF-8");
url.addQueryItem("q", "c++");
QByteArray baseurl = url.toEncoded();
|
3,403,031 | 3,403,061 | What is the macro definition of isupper in C? | I want to know how the "isupper" macro is defined in C/C++. Could you please provide me the same or point me to available resources. I tried looking at ctype.h but couldnt figure it out.
| It's implementation defined -- every vendor can, and usually does, do it differently.
The most common usually involves a "traits" table - an array with one element for each character, the value of that element being a collection of flags indicates details about the character. An example would be:
traits[(int) 'C'] = ... |
3,403,088 | 3,403,124 | calling C++ methods from C | So it's been a while since I've used straight C. And I'm on a project where I'm working on an API in C++. Most of these methods are just C anyway, and all of the return values are C structures. Except one. One method I need to return a vector<string>. Now here's my question. Is C++ methods/libraries/whatever callable f... | No, C cannot use C++ features that are not also available in C. However, C code can make use of C++ code indirectly. For example, you can implement a C function using C++, and you can use opaque types in the interface so that the signature uses void*, but the implementation uses a C++ class.
The equivalent of vector<st... |
3,403,280 | 3,403,362 | Memory allocation to functions in C++ | I am still a C++ newbie. Just came to read that the static member function of a class is not object specific - there is a single copy of the member functions for all the objects.
Now two questions arise in my mind :
What is the difference between an ordinary function and a static function "in terms of memory allocatio... |
What is the difference between an
ordinary function and a static
function "in terms of memory
allocation only" ?
Nothing. A static function is just like a global function except for the scope.
Even for non-static member functions, there's no extra memory required. The member function int C::f(int arg1, int arg2) is... |
3,403,421 | 3,403,495 | How to apply overlay transparency to RGBA image | Here's my dilemma: I have to RGBA RAW images: a master image (the first) and a subtitle track (the second), and I want to overlay them in a way based on the alpha channel of the second image: If it's zero, then take the pixels from the second image, if it's 0xFF take the pixels from the first image, otherwise create an... | An equation for doing alpha blending is more complex than just a bitwise or. Supposing a linear response model for RGB a quite common implementation is:
dst_R = (src_R*src_A + dst_R*(255 - src_A)) / 255;
dst_G = (src_G*src_A + dst_G*(255 - src_A)) / 255;
dst_B = (src_B*src_A + dst_B*(255 - src_A)) / 255;
dst_A = min(sr... |
3,403,479 | 3,403,903 | Lookup tables in C++ | I have to implement small multimage graphic control, which in essence is an array of 9 images, shown one by one. The final goal is to act as minislider.
Now, this graphic control is going to receive various integer ranges: from 5 to 25 or from 0 to 7 or from -9 to 9.
If I am going to use proportion - "rule of three" ... | I'm not sure look up tables are required. You can get from your input value to an image index between 0 and 9 proportionally:
int ConvertToImageArrayIndex(int inputValue)
{
int maxInputFromOtherModule = 25;
int minInputFromOtherModule = 5;
// +1 required so include both min and max input values in possibl... |
3,403,632 | 3,403,663 | check if user input a float to a int var? | I have a int var; and using cin, but how to check if user input a float or give me a solution for this problem?
| There is no easy way of doing this. Input via the >> operator is really not intended for interaction with humans who may enter the wrong thing. You will have to read the input as a string and then check it using a function like strtol, or your own hand-rolled code.
Here's an outline of an approach using strtol:
#inc... |
3,403,844 | 3,403,868 | tolower function for C++ strings | Is there an inbuilt function to convert C++ string from upper case letters to lowercase letters ? If not converting it to cstring and using tolower on each char is the only option ?
Thank you very much in advance.
| If boost is an option:
#include <boost/algorithm/string.hpp>
std::string str = "wHatEver";
boost::to_lower(str);
Otherwise, you may use std::transform:
std::string str = "wHatEver";
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
You can also use another function if you have some custom locale-aw... |
3,404,117 | 3,404,213 | How to write graphical programs | I have learned C++ and Qt4. I wrote one graphical program with 3000 rows and I found out that there is really complicated to keep code simple, transparent and well-structured. I like design patterns etc. because they are really effective and helps to keep code simpler and more transparent. Now I am going to write anoth... | I would highly recommend the book, Code Complete; http://www.cc2e.com/
|
3,404,312 | 3,406,838 | precompiled .libs for boost on 64 bit VC++ 2010 | Are there precompiled .libs for boost on 64 bit VC++ 2010?
| I've found complete set of them at http://boost.teeks99.com/. Starting with Boost 1.43, they include VS2010.
By complete, he means complete. VS2003, VS2005, VS2008, VS2010. 32/64 bit + all standard build options. Do the full install, then delete the versions you don't need.
Very painless install. All thanks to w... |
3,404,364 | 4,693,569 | Windows Mobile Hopper Test Tool, FocusApp | Hi recently I finished my WM6 Pro.6.1 application and happily learned that to put it into marketplace, it has to pass some tests.
-Application Verifier
-Microsoft Hopper Test Tool for Windows Mobile 6.0, 6.1, and 6.5
I use VS 2008 and windows mobile 6.1 and I couldnt run none of these tests, Hopeer tool has a FocusApp ... | There are a number of tips for this process in this blog post:
http://windowsteamblog.com/windows_phone/b/wmdev/archive/2010/02/18/windows-marketplace-for-mobile-certification-testing-hopper-and-multiple-screen-support.aspx
Try these first. If they don't work post more information on what specific problems you're havin... |
3,404,393 | 3,405,595 | Date/Time parsing in C++ (Any format string to Epoch) | I am writing a C++ app that has to parse a date/time string and give out epoch time.
But the format of the date/time string can be more than one (actually say 25 formats) like
"EEE, dd MMM yyyy HH:mm:ss '('ZZZ')'",
"EEE, dd MMM yyyy HH:mm:ss '\"'ZZZ'\"'",
"EEE, dd MMM yyyy hh:mm:ss z",
"EEE, dd MMM yyy... | I suppose you could attempt to convert your string into ptime using each of these formats and pick the ones that do not result in a not_a_date_time.:
The boost format flags are slightly different from yours, I'll do just the last five for this example:
#include <iostream>
#include <boost/date_time/posix_time/posix_time... |
3,404,491 | 3,405,349 | loop QHash by insert order | Is it possible to loop a QHash by the insert order? The method below seem to loop the hash by some other factor:
QHashIterator<QString, QString> i(hash);
while (i.hasNext()) {
i.next();
qDebug() << i.key() << ": " << i.value();
}
EDIT:
I figured it was impossible with QHash but what should I use instead?
| From QHash documentation,
QHash is unordered, so an iterator's
sequence cannot be assumed to be
predictable. If ordering by key is
required, use a QMap
So it is not possible.
If you want ordering based on the keys, use QMap instead..
Hope it helps..
Edit:
If you don't need Key and Value Logical mapping and ju... |
3,404,974 | 3,410,877 | How do I inherit from and extend QCalendarWidget using C++ | At present the QCalendarWidget only supports SingleSelection or NoSelection. I'd like to be able to write a widget that inherits from QCalendarWidget in Qt 4.6.2 and adds the ability for the user to select any day in a week and have that custom week selected.
e.g. Click on Thu 5 August 2010 and all days from Saturday ... | After reading the QCalendarWidget source code, it seems to me this might be the case for inheritance, but there will be issues.
First, classes that derive from QObject, widgets included, shouldn’t have copy constructors. The explanation for this is here. The QObject destructor is virtual, so no matter how you declare y... |
3,404,982 | 3,405,078 | How to map an ftp share folder to a local drive using C++? | How to map an ftp share folder to a local drive using C++ ?
Any code snippet...
| See if this does what you need: http://dokan-dev.net/en/docs/dokan-readme/
|
3,405,177 | 3,405,239 | Python modules for visualization of C++ code | I'm looking for python modules that can help with grepping C++ code. I have a large code base that I would like to do some analysis on. Ultimately I would like to come up with a graphical map of the software. There is lots of message passing going on amongst apps so I would like to be able to capture that informatio... | Your best tool for the job is Graphviz. If you look at their gallery you'll find the sort of thing that you're interested in along with links to projects.
Under the language bindings section here there are a few python entries. Personally I don't use them as the dot language format is simple enough that you can build u... |
3,405,278 | 3,405,387 | Do very long methods always need refactoring? | I face a situation where we have many very long methods, 1000 lines or more.
To give you some more detail, we have a list of incoming high level commands, and each generates results in a longer (sometime huge) list of lower level commands. There's a factory creating an instance of a class for each incoming command. Eac... | I understand exactly where you're coming from, and can see exactly why you've structured your code the way it is, but it needs to change.
The uncertainty you feel when you attempt to refactor can be ameliorated by writing unit tests. If you've tests specific to each spec, then the code for each spec can be refactored u... |
3,405,331 | 4,450,467 | Windows: File rename and directory iteration clash | I'm using boost::filesystem to rename a file like this:
boost::filesystem::rename(tmpFileName, targetFile);
tmpFileName / targetFile are of type boost::filsystem::path.
While doing this, I iterate over the directory using this code in another thread:
directory_iterator end_itr;
for (directory_iterator itr(dirInfoPath... | code you provided doesn't contain any file open operations, so it cannot lock the file. you iterate over directory and renaming file, right? so it's possible this file is really used by another application like file viewer or something else, it's quite typical error. or you have it opened in your app somewhere else
|
3,405,511 | 3,405,554 | which is the best way to generate choices out of a given set of numbers? | for example if it is given to make all the choices between 1 to 5 and the answer goes like this..
1,2,3,4,5,
1-2,1-3,1-4,1-5,2-3,2-4,2-5,3-4,3-5,4-5,
1-2-3,1-2-4,1-2-5,1-3-4,
.....,
1-2-3-4-5.
can anyone suggest a fast algorithm?
| Just generate all the integers from one (or zero if you want to include the empty set) to 2^N - 1. Your sets are indicated by the set bits in the number. For example if you had 5 elements {A,B,C,D,E} the number 6 = 00110 would represent the subset {C,D}.
|
3,405,690 | 3,405,835 | Registry and file system change identification | Is there a Coding way in C++ to find out the changes happened in Registry and file system. I need to find the changes happened to file system and registry after a software installion.
There is filesystemwatcher in c# to identify filesystem changes. However, I need that to implement in C++ for both registry and files.... | For monitoring registry keys you can use RegNotifyChangeKeyValue(), see here. For files you'd use ReadDirectoryChangesW(), see here.
|
3,405,851 | 3,406,515 | C++ Class design - easily init / build objects | Using C++ I built a Class that has many setter functions, as well as various functions that may be called in a row during runtime.
So I end up with code that looks like:
A* a = new A();
a->setA();
a->setB();
a->setC();
...
a->doA();
a->doB();
Not, that this is bad, but I don't like typing "a->" over and over again. ... | One note unrelated to your question, the statement A a = A(); probably isn't doing what you expect. In C++, objects aren't reference types that default to null, so this statement is almost never correct. You probably want just A a;
A a creates a new instance of A, but the = A() part invokes A's copy constructor with a ... |
3,406,004 | 3,406,131 | Define a specific case for a templated function (C++) | So in my .h file I have
template <class T>
void getValue(T *val, int element, int index);
and then in my .cc file I have a function:
template <class T>
void RParser::getValue(T *val, int element, int index)
{
I also have it explicitly instantiated:
template void RParser::getValue<char>(char *val, int element, st... | If you want to specialise the template, then the syntax is:
template<>
void RParser::getValue<std::string>(std::string* val, int element, int index) {}
But as Neil's answer says, you don't need to specialise this function template; an overload will do the job:
void RParser::getValue(std::string* val, int element, int... |
3,406,031 | 3,406,083 | Constructor with reference arguments in g++ compiler | Have a look at the following piece of code
Header File:
class CxUser
{
public:
CxUser(string& guid) {}
};
I have a c++ file that instantiates the class using CxUser(string("xxx-xxx-x-xxxx")). But this statement fails to compile in g++ with error "no matching function for call to CxUser::CxUser(std::string)" wher... | You need:
class CxUser{ public: CxUser(const string& guid) {} }
When you say:
CxUser c( "foobar" ); // or whatever
a temporary string object is created from the characterv array. In C++ you cannot bind non-const references to temporaries.
|
3,406,395 | 3,406,449 | C++ inline methods with same if statements | i'm writting handler for OpenGL texture and i'm thinking about safety and performance. Which level of optimization should remove marked if statements?
struct Texture2D {
GLuint ID;
inline Texture2D(): ID(0) {};
inline explicit Texture2D(GLuint id): ID(id) {};
~Texture2D();
void GenTexture(bool re... | None.
Sad story, but C++ assumes that if you call a function, then this function might produce all kinds of side effects, including changing the value of binded.ID (which the function somehow knows to do)
Except
If you make sure that the functions you invoke have absolutely no legal way to know about your bindend.ID, e... |
3,406,407 | 3,406,431 | Can functions be in a struct? | Can we describe functions in a struct? For example, is this code valid?
struct function {
int func() { return 5; }
};
| Yes, the only differences between a struct and class in C++ are:
In C++, a structure is a class defined with the struct keyword. Its members and base classes are public by default. A class defined with the class keyword has private members and base classes by default. This is the only difference between structs and cl... |
3,406,482 | 3,406,541 | C++: inheriting overloaded non-virtual method and virtual method both with the same name causes problem | I am trying to inherit two equally named methods with different parameter lists to a derived class. One of them is virtual and overridden in the derived class, the other one is non-virtual. Doing so, i get a compile error while trying to access the non-virtual method of the base class from an derived class object.
Here... | In Deriv, add this:
using Base::f;
In addition to the link given by @DumbCoder, you can find more details in my answer to a similar question: Overriding a Base's Overloaded Function in C++
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.