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 |
|---|---|---|---|---|
2,928,834 | 2,929,183 | PhysX: Joint friction/"stiff" joints | I'm working with physx (trying to add ik to ragdoll) at the moment. For some reason, all ragdoll joints are frictionless, and as a result, ragdoll tend to "wobble", especially when it is hung in the air and is connected to several moving kinematic actors.
I would like to add friction to the joints and make them "stiff"... | I've asked a question on the nvidia forums recently which might be related to this: link
Unfortunately I didn't get a real answer to my questions but managed to do what I want to do, using a spring in the joint might help you here if you only add a damping constant without a spring constant. This works in my case but I... |
2,928,863 | 2,928,948 | Difference between static const char* and const char* | Could someone please explain the difference in how the 2 snippets of code are handled below? They definitely compile to different assembly code, but I'm trying to understand how the code might act differently. I understand that string literals are thrown into read only memory and are effectively static, but how does th... | With your static version there will be only one variable which will be stored somewhere and whenever the function is executed the exact same variable will be used. Even for recursive calls.
The non-static version will be stored on the stack for every function call, and destroyed after each.
Now your example is a bit co... |
2,929,267 | 2,929,458 | Virtual functions and templates in C++ - can they be replaced with other (existing in C++) operations? | For example concept of Templates in C++ are for comfort as compiler generates some additional code, for your class or for your function, isn't it? So we could live without template by doing some additional (manual work).
What about virtual functions???
Are there any situations where both of them are irreplaceable?
| Yes, we can live without templates by doing more manual work (write the code that the compiler writes, or use void* to remove type specifics).
Yes, we can live without polymorphism by doing more manual work (using switch statements, or storing your own vtable struct).
Are there instances where they're irreplaceable?
... |
2,929,301 | 3,015,899 | Objective-C++ pre-compiled headers | I'm using a C++ library (it happens to be in an iPad application, but I'm not sure that should make any difference) and would really like to have the headers pre-compiled to speed up the builds, but xCode seems to run the pre-compiled header file through the C compiler rather than the C++ one.
Is there a way to get it ... | According to the Xcode docs, a compiled header is generated for each language variant. So if you bracket your #include with guard macros, it should work i.e.
#if defined __cplusplus
#include "mycplusplusheader.h"
#endif
|
2,929,446 | 2,929,652 | Boost shared_ptr use_count function | My application problem is the following -
I have a large structure foo. Because these are large and for memory management reasons, we do not wish to delete them when processing on the data is complete.
We are storing them in std::vector<boost::shared_ptr<foo>>.
My question is related to knowing when all processing i... | My immediate reaction (and I'll admit, it's no more than that) is that it sounds like you're trying to get the effect of a pool allocator of some sort. You might be better off overloading operator new and operator delete to get the effect you want a bit more directly. With something like that, you can probably just use... |
2,929,543 | 2,936,457 | Instance where embedded C++ compilers don't support multiple inheritance? | I read a bit about a previous attempt to make a C++ standard for embedded platforms where they specifically said multiple inheritance was bad and thus not supported. From what I understand, this was never implemented as a mainstream thing and most embedded C++ compilers support most standard C++ constructs.
Are ther... | Many of the restrictions imposed in the EC++ subset were made to allow wide compiler support for small 16 and 32 bit targets at a time when not all C++ compilers supported all emerging features (for example GCC did not support namespaces until version 3.x, and EC++ omits namespace support). This was before ISO C++ sta... |
2,929,586 | 2,929,930 | Design for fastest page download | I have a file with millions of URLs/IPs and have to write a program to download the pages really fast. The connection rate should be at least 6000/s and file download speed at least 2000 with avg. 15kb file size. The network bandwidth is 1 Gbps.
My approach so far has been: Creating 600 socket threads with each having... | First and foremost you need to figure out what is limiting your application. Are you CPU-bound, IO-bound, memory-bound, network-bound, ...? Is there locking contention between your threads? etc...
Its impossible to say from your description. You will need to run your app in a profiler to get an idea where the bottlenec... |
2,929,598 | 2,929,691 | OpenGL GL_LINE_STRIP gives error 1281 (Invalid value) after glEnd | I have no idea what is wrong with the simple code. The function is for use with python and ctypes.
extern "C" void add_lines(bool antialias,GLdouble coordinates[][2],int array_size,GLdouble w,GLdouble r,GLdouble g, GLdouble b,GLdouble a){
glDisable(GL_TEXTURE_2D);
if (antialias){
glEnable(GL_LINE_SMOOTH... | glGetError() is sticky: once the error gets set by some function, it will stay at that error value until you call glGetError(). So, the error is likely being caused elsewhere. Check the value of glGetError() on function entry, and then after each function call to find out where it's being set.
|
2,929,840 | 2,929,896 | Simple inheritance in C++ | I was going over some sample questions for an upcoming test, and this question is totally confusing me.
Consider the following code:
class GraduateStudent : public Student
{
...
};
If the word "public" is omitted, GraduateStudent uses private inheritance, which means which of the following?
GraduateStudent objects... | Although this is a bare homework-ish question, I'm going to answer it because it is a terrible question. I would almost consider it a trick question, and it doesn't really make for a good test of knowledge.
The answer is 2. GraduateStudent does not have access to private objects of Student., except that this has nothin... |
2,929,868 | 2,929,887 | Good C++11 information, other than Wikipedia? | Does anyone know a good website where I can find information on C++11, other than Wikipedia?
| The best I know is ISO/IEC JTC1/SC22/WG21 - The C++ Standards Committee where the n3092.pdf document is available.
|
2,929,925 | 2,929,964 | Fast comparison of char arrays? | I'm currently working in a codebase where IPv4 addresses are represented as pointers to u_int8. The equality operator is implemented like this:
bool Ipv4Address::operator==(const u_int8 * inAddress) const
{
return (*(u_int32*) this->myBytes == *(u_int32*) inAddress);
}
This is probably the fasted solution, but it ... | I would go for memcmp()
It is more portable
I usually try not to be smarter than my compiler/language. You are trying to compare memory contents and (depending on compiler options too) the implementation of memcmp() should be the most efficient way to do that.
Also think that if your compiler does not inline memcmp()... |
2,929,970 | 2,930,168 | How to debug ctypes call of c++ dll? | in my python project I call a c++ dll using ctypes library.
That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll.
Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it?
How can I attach the c++ debugger to this situation?
Thanks in advanc... | I don't know about your direct question, but maybe you could get around it by using comtypes to go straight from COM to Python instead sticking C++ in between.
Then all you have to do is:
>>> from comtypes import client, COMError
>>> myclassinst = client.CreateObject('MyCOMClass.MyCOMClass')
>>> try:
... myclassins... |
2,930,111 | 2,930,568 | Wireshark Plugin: Is There a non-ntoh Version of tvb_get_ntoh64? | I am writing a Wireshark dissector plugin for a protocol that does not hton it's data, and I need to extract a 64-bit data value without doing any endian conversions.
Is there a version of tvb_get_ntoh64 included in the Wireshark libraries that does not do the ntoh?
| I found the answer to my own question. The wireshark document \wireshark\doc\README.developer addresses this:
Don't fetch a little-endian value
using "tvb_get_ntohs() or
"tvb_get_ntohl()" and then using
"g_ntohs()", "g_htons()", "g_ntohl()",
or "g_htonl()" on the resulting value
- the g_ routines in questio... |
2,930,444 | 2,930,518 | What to name an array of flags? | I have a project where lots of the objects hold state by maintaining simple boolean flags. There are lots of these, so I maintain them within a uint32_t and use bit masking. There are now so many flags to keep track of, I've created an abstraction for them (just a class wrapping the uint32_t) with set(), clear(), etc... | FlagBank would be fairly descriptive.
But I have one suggestion. Instead of using uint32_t and bit masking, it might be less C-like to use an STL vector instead. It uses a template specialization for the boolean case where only one bit per element is used for the storage. Very efficient and MUCH more object oriented... |
2,930,613 | 2,930,649 | c++ STL vector is not acccepting the copy constructor | I wrote a code ( c++,visual studio 2010) which is having a vector, even I though copy const is declared, but is still showing that copy const is not declared
Here the code
#include<iostream>
#include<vector>
using namespace std;
class A
{
public:
A() { cout << "Default A is acting" << endl ; }
A(A &a) { cout ... | Copy constructor should take the object as a const reference, so it should be:
A(const A &a){ cout << "Copy Constructor of A is acting" << endl; }
|
2,931,288 | 2,931,887 | Edit characters in a String in C# | What's the cleanest way of editing the characters in a string in C#?
What's the C# equivalent of this in C++:
std::string myString = "boom";
myString[0] = "d";
| Decided to time what I felt where the two most canonical approaches, plus one I threw in as unrepresented; here's what I found (Release build):
ReplaceAtChars: 86ms
ReplaceAtSubstring: 258ms
ReplaceAtStringBuilder: 161ms
Clearly the Char array approach is by far best optimized by the runtime. Which actually suggests th... |
2,931,345 | 2,931,359 | Trouble with dependent types in templates | I'm having trouble with templates and dependent types:
namespace Utils
{
void PrintLine(const string& line, int tabLevel = 0);
string getTabs(int tabLevel);
template<class result_t, class Predicate>
set<result_t> findAll_if(typename set<result_t>::iterator begin, set<result_t>::iterator end, Predicate ... | Well, the warning says:
dependent name is not a type. prefix with 'typename' to indicate a type
The dependent name (that is, the iterator in std::set<result_t>::iterator) is not a type. You need to prefix it with typename to indicate a type:
typename std::set<result_t>::iterator
So, your declaration should be:
temp... |
2,931,423 | 2,931,438 | Problem overridding virtual function | Okay, I'm writing a game that has a vector of a pairent class (enemy) that s going to be filled with children classes (goomba, koopa, boss1) and I need to make it so when I call update it calls the childclasses respective update. I have managed to create a example of my problem.
#include <stdio.h>
class A{
public:
... | Polymorphism only works on pointers and references. If you assign a B to an A, it becomes an A and you lose all B-specific information, including method overrides. This is called "slicing"; the B parts are "sliced" off the object when it is assigned to an object of a parent class.
On the other hand, if you assign a B* ... |
2,931,477 | 2,931,545 | C++ ambiguous template instantiation | the following gives me ambiguous template instantiation with nvcc (combination of EDG front-end and g++).
Is it really ambiguous, or is compiler wrong? I also post workaround à la boost::enable_if
template<typename T> struct disable_if_serial { typedef void type; };
template<> struct disable_if_serial<serial_tag> { };... | AFAIK, the problem is that you have the nontype arguments inconsistently typed (that is, M and N are int here, but size_t there). This means not all template variable assignments from one can be used in the other, which means there is no partial ordering, hence the error message.
Unite the template nontype argument typ... |
2,931,551 | 2,936,281 | How to give properties to c++ classes (interfaces) | I have built several classes (A, B, C...) which perform operations on the same BaseClass. Example:
struct BaseClass {
int method1();
int method2();
int method3();
}
struct A { int methodA(BaseClass& bc) { return bc.method1(); } }
struct B { int methodB(BaseClass& bc) { return bc.method2()+bc.method1(); } }
... | use pattern Adapter
struct InterfaceA { virtual int method1() = 0; }
struct A { int methodA(InterfaceA& bc) { return bc.method1(); } }
struct BaseClassAdapterForA: public InterfaceA
{
BaseClassAdapterForA(BaseClass& _bc) : bc(_bc) {}
virtual int method1()
{
//note that the name of BaseClass method... |
2,931,566 | 2,931,762 | C++: Trouble with templates (C2064) | I'm having compiler errors, and I'm not sure why. What am I doing wrong here:
Hangman.cpp:
set<char> Hangman::incorrectGuesses()
{
// Hangman line 103
return Utils::findAll_if<char>(guesses.begin(), guesses.end(), &Hangman::isIncorrectGuess);
}
bool Hangman::isIncorrectGuess(char c)
{
return correctAnswer... | Use the following to use a bound member function as a predicate:
return Utils::findAll_if<char>(
guesses.begin(), guesses.end(),
std::bind1st(std::mem_fun(&Hangman::isIncorrectGuess), this)));
Member functions expect an implicit this parameter and can't be used directly with STL ... |
2,931,613 | 2,931,641 | after XOR operation find C (and XOR reversability) | Assume:
unsigned char A = 10;
unsigned char B = 11;
unsigned char C = 12;
unsigned char Diff1 = A ^ B;
unsigned char Diff2 = B ^ C;
//find any of A or B or C using Diff1 and Diff2
Question is: There were 3 values initially for which we found 2 differences. Is there any way we can find any of A or B or C using 2 di... | You don't have enough information to find any of A, B or C from just knowing the values of Diff1 and Diff2.
There are 256 ** 3 different possible inputs and only 256 ** 2 possible outputs so for each output there are 256 different possible inputs that could have given that output - where A, B and C could be any value. ... |
2,931,704 | 2,931,750 | How to compare string with const char*? | #include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string cmd;
while(strcmp(cmd.c_str(),"exit")==0 && strcmp(cmd.c_str(),"\exit")==0)
{
cin>>cmd;
cout<<cmd;
}
return 0;
}
I am stuck.
| After fixing a couple of small bugs, this works on my machine:
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
int main()
{
std::string cmd;
while( std::strcmp(cmd.c_str(),"exit")!=0
&& std::strcmp(cmd.c_str(),"\\exit")!=0)
{
... |
2,931,854 | 2,931,961 | Can I use a static library compiled with gcc 3.4.2 with gcc 4.2.2 | I have a static library that is compiled with gcc 3.4.2. I am building a shared library that relies on this static lib. I will be building this shared library (.so) with gcc 4.2.2. I was wondering what are the potential pitfalls of using the 3.4.2 static library in a gcc 4.2.2 shared library?
| If your static library is c++ based then I thought due to ABI changes it probably would not be compatible but according to this other stackoverflow question, gcc is forward compatible starting with gcc 3.4.0. So you could be ok. I had to rebuild all of my libraries going from gcc 3.0/3.2 to gcc 3.4.6 but I have not d... |
2,931,925 | 2,932,366 | gluNewQuadric() before opengl's initialization | I'm working on a c++ code that uses SDL/opengl.
Is this possible to create a pointer to a quadric with gluNewQuadric() before having initialized opengl with SDL_SetVideoMode?
The idea is to create a class with a (pointer to a) quadric class member that has to be instantiate before the SDL_SetVideoMode call. This poin... | I'm not seeing anything in the source code that would require an active GL context.
|
2,932,189 | 3,052,780 | OpenGL code to render ribbon diagrams for protein | I am looking to render ribbon diagrams of proteins using OpenGL and C++. Does anyone know if any open source code for this already exists, or if there are good guides to do this? If not, I'd prefer to figure it out myself ;) but I didn't want to reinvent the wheel, especially if the wheel was free.
EDIT: thanks for t... | Take a look at http://molvis.sdsc.edu/visres/molvisfw/titles.jsp for an amazing number of projects devoted to molecular visualization, most of them open source.
|
2,932,204 | 2,959,902 | Timing related crash when unloading a DLL? | I know I'm reaching for straws here, but this one is a mystery... any pointers or help would be most welcome, so I'm appealing to those more intelligent than I:
We have a crash exhibited in our release binaries only. The crash takes place as the binary is bringing itself down and terminating sub-libraries upon which it... | The problem was a conflicting setting of the pernicious _SECURE_SCL flag under Visual Studio, causing silent ABI incompatibilities between the DLL and one of its dependencies.
|
2,932,300 | 2,932,348 | conflicting declaration when filling a static std::map class member variable | I have a class with a static std::map member variable that maps chars to a custom type Terrain. I'm attempting to fill this map in the class's implementation file, but I get several errors. Here's my header file:
#ifndef LEVEL_HPP
#define LEVEL_HPP
#include <bitset>
#include <list>
#include <map>
#include <string>
#... | You can initialize static members outside of functions, but you can't perform arbitrary operations.
You could use a function to initialize the members:
namespace {
std::map<char, Terrain> initTerrainTypes() {
std::map<char, Terrain> m;
m['.'] = Terrain("00001");
// ...
return m;
... |
2,932,423 | 2,932,490 | Changing type of object in a conditional | I'm having a bit of trouble with dynamic_casting. I need to determine at runtime the type of an object. Here is a demo:
#include <iostream>
#include <string>
class PersonClass
{
public:
std::string Name;
virtual void test(){}; //it is annoying that this has to be here...
};
class LawyerClass : public PersonClas... | Dynamic casting to a subclass and then assigning the result to a pointer to superclass is of no use - you practically are back where you started. You do need a pointer to a subclass to store the result of the dynamic cast. Also, if the concrete type of your object is PersonClass, you can't downcast it to a subclass. Dy... |
2,932,644 | 2,932,662 | CoGetClassObject gives many First-chance exceptions in ATL project. Should I worry? | I have written a COM object that in turn uses a thrid party ActiveX control. In my FinalConstruct() for my COM object, I instantiate the ActiveX control with the follow code:
HRESULT hRes;
LPCLASSFACTORY2 pClassFactory;
hRes = CoInitializeEx(NULL,COINIT_APARTMENTTHREADED);
bool bTest = SUCCEEDED(hRes);
if (!... | It's usually nothing to worry about.
When an exception is thrown, the debugger is notified and depending on the debugger configuration, it may stop the application or let the application resume normally. This is a "first-chance" exception. If the application resumes, then it may catch the exception, and do whatever is ... |
2,932,753 | 2,932,800 | Multidimensional Array Initialization: Any benefit from Threading? | say I have the following code:
char[5][5] array;
for(int i =0; i < 5; ++i)
{
for(int j = 0; j < 5; ++i)
{
array[i][j] = //random char;
}
}
Would there be a benefit for initializing each row in this array in a separate thread?
Imagine instead of a 5 by 5 array, we have a 10 by 10?
n x n?
Also, this ... | You're joking, right?
If not: The answer is certainly no!!!
You'd incur a lot of overhead for putting together enough synchronization to dispatch the work via a message queue, plus knowing all the threads had finished their rows and the arrays were ready. That would far outstrip the time it takes one CPU core to fill ... |
2,932,822 | 2,932,853 | Is it safe to catch an access violation in this scenario? | I've read a lot, including here on SO that suggests this is a very bad idea in general and that the only thing you can do safely is exit the program. I'm not sure that this is true.
This is for a pooling memory allocator that hands off large allocations to malloc. During pool_free() a pointer needs to be checked it it ... | There is no need to implement a reactive mechanism. You can get in front of the problem by aligning heap allocations to a 1 MB boundary:
Windows: _aligned_malloc(size, 1<<20)
Unix: memalign(1<<20, size)
Using this approach, rounding down to 1 MB is guaranteed to point into an allocated block of memory, and you simply... |
2,932,909 | 2,932,963 | Overriding vs Virtual | What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as void draw(){}.
class Parent {
public:
void say() {
std::cout << "1";
}
};
class Child : public Parent {
public:
void say()
... | This is the classic question of how polymorphism works I think. The main idea is that you want to abstract the specific type for each object. In other words: You want to be able to call the Child instances without knowing it's a child!
Here is an example:
Assuming you have class "Child" and class "Child2" and "Child3" ... |
2,932,954 | 2,932,959 | c++: at what point should I start using "new char[N]" vs a static buffer "char[Nmax]" | My question is with regard to C++
Suppose I write a function to return a list of items to the caller. Each item has 2 logical fields: 1) an int ID, and 2) some data whose size may vary, let's say from 4 bytes up to 16Kbytes. So my question is whether to use a data structure like:
struct item {
int field1;
char fi... | You should instead use one of the standard library containers, like std::string or std::vector<char>; then you don't have to worry about managing the memory yourself.
|
2,933,124 | 2,933,139 | Buffer size: N*sizeof(type) or sizeof(var)? C++ | I am just starting with cpp and I've been following different examples to learn from them, and I see that buffer size is set in different ways, for example:
char buffer[255];
StringCchPrintf(buffer, sizeof(buffer), TEXT("%s"), X);
VS
char buffer[255];
StringCchPrintf(buffer, 255*sizeof(char), TEXT("%s"), X);
Which on... | Neither is correct.
You are using StringCchPrintf(), which operates on the count of characters, not bytes. sizeof(buffer) returns the size of buffer in bytes, as does 255*sizeof(char). 255*sizeof(char) also has the disadvantage that you are duplicating the size of the array in two places - if you change the size of b... |
2,933,295 | 2,933,357 | Embed Text File in a Resource in a native Windows Application | I have a C++ Windows program. I have a text file that has some data. Currently, the text file is a separate file, and it is loaded at runtime and parsed. How is it possible to embed this into the binary as a resource?
| Since you're working on a native Windows application, what you want to do is to create a user-defined resource to embed the contents of the text file into the compiled resource.
The format of a user-defined resource is documented on MSDN, as are the functions for loading it.
You embed your text file in a resource file ... |
2,933,504 | 2,933,525 | Where in the standard is forwarding to a base class required in these situations? | Maybe even better is: Why does the standard require forwarding to a base class in these situations? (yeah yeah yeah - Why? - Because.)
class B1 {
public:
virtual void f()=0;
};
class B2 {
public:
virtual void f(){}
};
class D : public B1,public B2{
};
class D2 : public B1,public B2{
public:
using B2::f;
... | The C++ standard says in §10.3/2:
The rules for member lookup (10.2) are used to determine the final overrider for a virtual function in the scope of a derived class but ignoring names introduced by using-declarations.
So, even though you use using B2::f; to bring B2::f() into the derived class, it is not considered ... |
2,933,554 | 2,933,571 | How can I change the value or a static char* from a function? C++ | I am trying to change the value of a "static char *" I define at startup, I do it from inside a function, and when this function returns the var I am trying to re-set the value doesn't retain it.
Example:
static char *X = "test_1";
void testFunc()
{
char buf[256];
// fill buf with stuff...
X = buf;
}
How ... | As James said, use std::string... except be aware that global construction and destruction order is undefined between translation units.
So, if you still want to use char*, use strcpy (see man strcpy) and make sure buf gets NUL-terminated. strcpy will copy the buf into the destination X.
char buf[256];
// ...
strcpy(X,... |
2,933,758 | 2,935,995 | priority queue with limited space: looking for a good algorithm | This is not a homework.
I'm using a small "priority queue" (implemented as array at the moment) for storing last N items with smallest value. This is a bit slow - O(N) item insertion time. Current implementation keeps track of largest item in array and discards any items that wouldn't fit into array, but I still would ... | Array based heaps seem ideal for your purpose. I am not sure why you rejected them.
You use a max-heap.
Say you have an N element heap (implemented as an array) which contains the N smallest elements seen so far.
When an element comes in you check against the max (O(1) time), and reject if it is greater.
If the value c... |
2,933,774 | 2,933,800 | C++ Windows function call that get local hostname and IP address | Is there built-in windows C++ function call that can get hostname and IP address? Thanks.
| To get the hostname you can use: gethostname or the async method WSAAsyncGetHostByName
To get the address info, you can use: getaddrinfo or the unicode version GetAddrInfoW
You can get more information about the computer name like the domain by using the Win32 API: GetComputerNameEx.
|
2,934,021 | 2,934,046 | STL map containing references does not compile | The following:
std::map<int, ClassA &> test;
gives:
error C2101: '&' on constant
While the following
std::map<ClassA &, int> test;
gives
error C2528: '_First' : pointer to reference is illegal
The latter seems like map cannot contain a reference for the key value, since it needs to instantiate the class sometimes a... | It is illegal to store references in an stl container, because types must be copy constructible and assignable. References can not be assigned.
Exactly what operation causes the first error is implementation dependent, but I image that it is related to creating a reference and not assigning it immediately. The second... |
2,934,042 | 2,934,922 | Partial template specialization: matching on properties of specialized template parameter | template <typename X, typename Y> class A {
// Use Y::Q, a useful property, not used for specialization.
};
enum Property {P1,P2};
template <Property P> class B {};
class C {};
Is there any way to define a partial specialization of A such that A<C, B<P1> > would be A's normal template, but A<C, B<P2> > would be th... | I've no idea what you mean. Template template parameters seem the solution, although you somehow say they won't work. Why not do this?
template <typename X, typename Y>
class A {
};
template <typename X, template<typename> class Y, typename P>
class A< X, Y<P> > {
/* property is P */
};
For your SFINAE question, ... |
2,934,216 | 2,934,671 | Did I implement clock drift properly? | I couldn't find any clock drift RNG code for Windows anywhere so I attempted to implement it myself. I haven't run the numbers through ent or DIEHARD yet, and I'm just wondering if this is even remotely correct...
void QueryRDTSC(__int64* tick) {
__asm {
xor eax, eax
cpuid
rdtsc
mov edi, dword ptr tick
mov d... | The Sleep function is limited by the resolution of the system clock, so Sleep (1) may not be doing what you want.
|
2,934,240 | 2,934,260 | Calling a method at a specific interval rate in C++ | This is really annoying me as I have done it before, about a year ago and I cannot for the life of me remember what library it was.
Basically, the problem is that I want to be able to call a method a certain number of times or for a certain period of time at a specified interval.
One example would be I would like to ca... | A combination of boost::this_thread::sleep and time duration found in boost::datetime?
|
2,934,314 | 2,934,329 | How to escape a semicolon in C++ string | std:string str("text1\; text2\;");
How come VS2005 says ; unrecognized character escape sequence.
Please advise, thanks.
| Because this is wrong:
std:string str("text1\; text2\;");
This is correct:
std::string str("text1; text2;");
TWO colons after std.
|
2,934,648 | 2,934,660 | C++: Platform independent game lib? | I want to write a serious 2D game, and it would be nice if I have a version for Linux and one for Windows (and eventually OSX). Java is fantastic because it is platform independent. But Java is too slow to write a serious game. So, I thought to write it in C++. But C++ isn't very cross-platform friendly. I can find gam... | Try SDL (in association with c/c++), it's great for 2D games (and supports 3D through opengGL), and it works on windows, os x and linux.
|
2,934,672 | 2,934,725 | link .a and .o files in GCC | I have two precompiled library: X.a and Y.a and a test.cpp (without main function) source code use these two libraries.
I compiled the C++ using:
g++ -c test.cpp
and I got 'test.o'.
Now how can I link these three together to generate a .a file because test.cpp use some function in X.a and Y.a and other GCC libraries?
... |
Now how can I link these three
together to generate a .a file because
test.cpp use some function in X.a and
Y.a and other GCC libraries?
.a is nothing more then ar archive containg all object files (.o files)
Can I rename this .a file to .lib and
use this .lib in VC?
Yes, but it requires little trick to wor... |
2,934,692 | 2,934,710 | how to see contents of a.out file? | The executable file of c++ will contain linkers, modules and others, i would like to look into its contents,
i'm using linux, how can i view contents of a.out?
which command should use to browse a.out, text editors wont show the contents......
| You can use nm to see the internal symbols and objdump to get the disassemble. By example:
objdump -D a.out | less
Note however that during the final linking of the object files into the executable a lot of symbols and internal data get eliminated, therefore you won't be able to understand the structure as you would b... |
2,934,746 | 4,645,606 | How to remove one folder from C:\Windows\winsxs? | I've installed:
Microsoft Visual C++ 2008 SP1 Redistributable Package (x86)
and got the following folders:
x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91
x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4926_none_508ed732bcbc0e5a
I allready uninstalled the redistribute package but they conti... | Modifying the registry or filesystem directly is a bit dangerous, since there's a lot of extra configuration data associated with installed assemblies.
The fact that those files are still present doesn't do great harm (WinSxS is a cache), what's important is whether the system treats them as installed or not. I've blog... |
2,934,764 | 2,934,775 | Receiving integers, but also want to test for char | Say I am looking to receive a series of numeric values and read them into an int, but I also want to test if the user hit key 'x'.
I am sure I am missing something obvious, and have tried a few things but seem to be stuck.
This is what I have so far...
cout << endl << "Enter key (or 'x' to exit): ";
cin >>... | You need to read into a string and then convert that to an integer. In outline:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
string s;
cout << endl << "Enter key (or 'x' to exit): ";
getline( cin, s );
if ( s == "x" ) {
// do exit stuff
}
else {
istrin... |
2,934,904 | 2,934,909 | Order of evaluation in C++ function parameters | If we have three functions (foo, bar, and baz) that are composed like so...
foo(bar(), baz())
Is there any guarantee by the C++ standard that bar will be evaluated before baz?
| No, there's no such guarantee. It's unspecified according to the C++ standard.
Bjarne Stroustrup also says it explicitly in "The C++ Programming Language" 3rd edition section 6.2.2, with some reasoning:
Better code can be generated in the
absence of restrictions on expression
evaluation order
Although technically... |
2,935,017 | 2,935,050 | Input system reference trouble | I'm using SFML for input system in my application.
size_t WindowHandle;
WindowHandle = ...; // Here I get the handler
sf::Window InputWindow(WindowHandle);
const sf::Input *InputHandle = &InputWindow.GetInput(); // [x] Error
At the last lines I have to get reference for the input system.
Here is declaration of GetI... | Is there a special reason why you want to have a pointer rather than a reference?
If not, you could try this:
const sf::Input & InputHandle = InputWindow.GetInput();
This will return you a reference to your Input handle.
Btw, this worked for me:
const int& test(int& i)
{
return i;
}
int main()
{
int i = 4;
... |
2,935,038 | 2,935,044 | Why can't I add pointers? | I have code very similiar to this:
LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const
{
return (this + &right);//IN THIS PLACE I'M GETTING AN ERROR
}
LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator-(const Iterator& right)const
{//substracts one iterator f... | Pointer addition is forbidden in C++, you can only subtract two pointers.
The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or do... |
2,935,109 | 2,935,146 | Window Wrapper Class C++ (G++) | I am attempting to learn about creating windows in c++, I have looked at an article about creating a wrapper class but I don't really understand it. So far I know that you can't have a class method WndProc (I dont know why) but honestly, that is all. Can somebody give an explanation, also explaining the reinterpret_cas... | The MsgRouter() procedure acts as a proxy between the Windows message handling system to the Window instance associated with a HWND. It routes Windows messages to C++ objects.
A pointer to the Window instance is passed to the MsgRouter() procedure via the last parameter of the CreateWindow() function. When you first cr... |
2,935,166 | 2,935,262 | What good programming practices will change with C++11? | For example, "Don't return objects by value if they are expensive to copy" (RVO can't always be used). This advice might change because of rvalue references.
The same might be said about storing collections of pointers to objects, because copying them by value into the collection was too expensive; this reason might no... | I expect that C++ written in a functional-like style will become more prevalent because:
Lambda expressions make using the standard library algorithms much easier
Move semantics make returning standard library or other RAII container objects significantly cheaper
|
2,935,173 | 2,935,191 | Init var without copy constructor | I have some class(Window) without copy constructor (it's private). I can't understand how to init var of this class in my own class:
class MyClass
{
Window obj; // Hasn't copy constructor
public:
void init()
{
obj = Window(/* constructor params */); // [error]
obj(/* constructor para... | Your MyClass needs a constructor to initialize the obj member.
class MyClass
{
private:
Window obj;
public:
MyClass() : obj(/* constructor params */) // This is an initializer list
{}
};
If you need the init() function, and the Window object provides its own
init() function of some sort, you can do this... |
2,935,201 | 2,935,230 | Will C++0x support __stdcall or extern "C" capture-nothing lambdas? | Yesterday I was thinking about whether it would be possible to use the convenience of C++0x lambda functions to write callbacks for Windows API functions.
For example, what if I wanted to use a lambda as an EnumChildProc with EnumChildWindows? Something like:
EnumChildWindows(hTrayWnd, CALLBACK [](HWND hWnd, LPARAM lPa... | Lambdas without a capture are implicitly convertible to a pointer to function (by a non-explicit conversion function defined by the closure type).
The FCD does not seem to specify what language linkage the function type of that function pointer type has, so if you need to pass this function pointer to C functions, the... |
2,935,239 | 2,935,274 | C++ Inheritance and Constructors | trying to work out how to use constructors with an inherited class. I know this is very much wrong, I've been writing C++ for about three days now, but here's my code anyway:
clientData.h, two classes, ClientData extends Entity :
#pragma once
class Entity
{
public:
int x, y, width, height, leftX, rightX, topY, bottom... | Currently the constructor for the Client data class wont work. You will need to make a constructor for Client data like:
ClientData(int x, int y, int width, int height): Entity(x, y, width, height)
if you want to call
new ClientData(32,32,32,16);
|
2,935,366 | 2,935,379 | In C++, what happens when you return a variable? | What happens, step by step, when a variable is returned. I know that if it's a built-in and fits, it's thrown into rax/eax/ax. What happens when it doesn't fit, and/or isn't built-in? More importantly, is there a guaranteed copy constructor call?
edit: What about the destructor? Is that called "sometimes", "always", or... | Where the return value is stored depends entirely on the calling convention and is very architecture- and system-specific.
The compiler is permitted to elide the call to the copy constructor (i.e., it does not have to call the copy constructor). Note that returning a value from a function might also invoke an assignme... |
2,935,513 | 2,935,564 | Draw OpenGL on the windows desktop without a window | I've seen things like this and I was wondering if this was possible, say I run my application
and it will show the render on whatever is below it.
So basically, rendering on the screen without a window.
Possible or a lie?
Note: Want to do this on windows and in c++.
| It is possible to use your application to draw on other application's windows. Once you have found the window you want, you have it's HWND, you can then use it just like it was your own window for the purposes of drawing. But since that window doesn't know you have done this, it will probably mess up whatever you hav... |
2,935,532 | 2,935,580 | Portable way to hide console window in GLUT application? | Hey, I'm creating a little GLUT application and need help with hiding/removing the console window.
I am developing on windows and I already know of the various methods to hide the console window on a windows system, however is there no portable method of hiding it?
Thanks...
| You don't really want to "hide" the console window. What you want is to configure your compiler to generate a "Windows application" instead of a "Console application". That will tell windows to never create a console for your application. You'll need to consult your compiler's documentation to figure out how to do t... |
2,935,587 | 2,939,249 | Handle complex options with Boost's program_options | I have a program that generates graphs using different multi-level models. Each multi-level model consists of a generation of a smaller seed graph (say, 50 nodes) which can be created from several models (for example - for each possible edge, choose to include it with probability p).
After the seed graph generation, th... | By using a custom validator and boost::program_options::value::multitoken, you can achieve the desired result:
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <boost/program_options.hpp>
// Holds parameters for seed/expansion model
struct Model
{
std::string type;
b... |
2,935,604 | 2,935,614 | Qt cross thread call | I have a Qt/C++ application, with the usual GUI thread, and a network thread. The network thread is using an external library, which has its own select() based event loop... so the network thread isn't using Qt's event system.
At the moment, the network thread just emit()s signals when various events occur, such as a s... | Using signals to send messages between threads is fine, if you don't like using the Condition Variable, then you can send signals in both directions in a more-or-less asynchronous manner: this might be a better option if you want to continue processing network stuff while you wait for a reply from the GUI.
|
2,935,760 | 2,935,786 | Getline and 16h (26d) character | in VC++ environment Im using (string) getline function to read separate lines in opened file. Problem is that getline takes character 1Ah as end of file and if it is present on the line, whole reading ends prematurely. Is there any solution for this?
Code snippet:
fstream LogFile (Source,fstream::in);
string Line
whil... | Replace getline with a hand-rolled function that reads in character by character until end of line or eof, as defined by you.
|
2,935,984 | 2,936,092 | C++ meta-splat function | Is there an existing function (in boost mpl or fusion) to splat meta-vector to variadic template arguments? For example:
splat<vector<T1, T2, ...>, function>::type
// that would be the same as
function<T1, T2, ...>
My search have not found one, and I do not want to reinvent one if it already exists.
Alternatively, is... | You need unpack_args and quoteN, where N is the number of template arguments your template takes. Alternatively if you implement function as a metafunction class, you don't need to quoteN. Example of a metafunction class yielding the first of two given types:
struct function1st {
template<typename T1, typename T2>
... |
2,935,997 | 2,936,057 | How to use environment variable in #import c++ command? | nowadays I have this piece of code:
#import "C:\Users\Public\SoundLog\DLLs\ForPython\SoundLogDLL.tlb" named_guids
but I want to substitute the C:\Users\Public part by the %PUBLIC% environment variable.
How can I do this ?
| It would be wise to store your projects in a common folder so that you can use relative paths. The #import directive also searches files in the same folders where it looks for #include files. In the IDE, you can add them with Project + Properties, C/C++, General, Additional Include Directories.
|
2,936,001 | 2,936,017 | Doing extra initialisations on a MFC Dialog in Visual Studio C++ 2008 Pro | How do I make extra initializations on a modal dialog before calling DoModal(); ?
The whole application is created using VS wizards.
I have a main Dialog (the one that is created automatically when I select new MFC Application in Visual Studio 2008 Professional). When I click a button on this dialog I want to open anot... | Add an OnInitDialog (WM_INITDIALOG) handler to your CDialog-derived class and have it initialise itself.
|
2,936,044 | 2,936,082 | Loop invariants (Specifically Ch.3 of "Accelerated C++") | I'm currently working my way through "Accelerated C++" and just came across this in chapter 3:
// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades
while (cin >> x) {
++count;
sum += x;
}
The authors follow this by explaining that the invariant needs special att... | From your description it sounds like the author is talking nonsense. Yes, the invariant becomes untrue temporarily between instructions, but that is going to happen whenever you have non-atomic operations like this. As long as there aren't any clear break points that could lead to the invariant being incorrect and the ... |
2,936,052 | 2,936,064 | Clang doesn't support the Lock Prefix. How shall I workaround? | Assume this code:
static inline void inc(int64_t* atomic)
{
__asm__ __volatile__
(
"lock incq %0\n"
: "=m" (*atomic)
: "m" (*atomic)
);
}
The Clang compiler doesn't support the lock prefix (yet?). What shall I do now?
| Why not use the built-ins...?
static inlint void inc(int64_t* atomic) {
__sync_add_and_fetch_8(atomic, 1);
}
|
2,936,078 | 2,936,081 | How do I reset my pointer to a specific array location? | I am a brand new programming student, so please forgive my ignorance. My assignment states:
Write a program that declares an array of 10 integers. Write a loop that accepts 10 values from the keyboard and write another loop that displays the 10 values. Do not use any subscripts within the two loops; use pointers only.
... | You can do exactly as you did first when you assigned p:
p = &values[0];
Besides, arrays are very much like pointers (that you can't change) to statically allocated memory. Therefore, the expression &values[0] evaluates to the same thing that just values does. Consequently,
p = &values[0];
is the same as
p = values;
... |
2,936,111 | 19,524,080 | Emacs hide/show support for C++ triple-slash Doxygen markup? | I use Doxygen's triple-slash syntax to markup my C++ code. There are
two important cases which arise:
1) block markup comments which are the sole element on the line and may
or may not begin flush left; e.g.
class foo
/// A one sentence brief description of foo. The elaboration can
/// continue on for many lines.
... | Maybe, as a partial answer the following snippet of code would do the trick.
Press M-s M-s in C++-mode and it hides all comments of the kind you described. Again pressing M-s M-s reveals the comments again. I know that the short code has its limitations:
It would be nice if one could hide/show each special comment sep... |
2,936,165 | 2,936,183 | C++ - 3 possible values in Variable? | I need to store a 30 letter combination, but each letter can only be "0", "1" or "2". When I use sizeof(myString), it returns 32.
I want to use this 30 letter combination to access a row of an array, so I'm wondering if it is possible to use a 3 value bool of some sort to store 1 of 3 values in.
| 3^30 = 205891132094649 (~2E14), which is less than the maximum value of a 64-bit integer (~2E19), so you could map the strings to 64-bit ints in a 1:1 fashion.
An obvious way to do this would be to treat your string as a base-3 number, which would be quite slow to convert. Much faster would be to treat it as base 4, th... |
2,936,279 | 2,937,871 | Disable script debugging in IWebBrowser2 OLE control? C++ | I have a IWebBrowser2 I use to visit some webpages with .Navigate()
When the page has a js error I got a warning box for "Syntax error", so I used .put_Silent(TRUE). And now I get a warning for "VS Just-In-Time Debugger: Unhandled exception" instead
How can I disable all the script error warnings (including JIT debugge... | You can disable script debugging by overriding the registry settings that control it. The correct way to do this is to implement the IDocHostUIHandler interface, and specifically the IDocHostUIHandler::GetOptionKeyPath or IDocHostUIHandler::GetOverrideKeyPath methods. Use GetOptionKeyPath to ignore all the user's IE se... |
2,936,472 | 2,936,705 | SetMatrix() does not copy all values to HLSL | I want to use the contents of a vector of D3DXMatrices to my shader.
m_pLightMatrices->SetMatrixArray(¤tLightMatrices[0].m[0][0],0,numLights);
As we know the internals of a vector this poses no problems (as it is just a dynamic array).
Now when I access this matrix in hlsl to fill up a struct I get this strange ... | I managed to fix the issue. I do need some clarification on why it works now.
I just put the SetMatrixArray() function before the Input layout is set and suddenly it works perfectly.
Previously it was inside an update function together with all other variables (like world matrices, etc ..) and those work fine.
|
2,936,481 | 2,936,486 | Visual C++ 2010 atomic types support? | Does VC++ 2010 have support for C++11's portable atomic type template?
| No; none of the C++11 atomic operations or thread support features are supported by Visual C++ 2010.
Both of these sets of features are supported by Visual C++ 2012.
|
2,936,757 | 2,936,759 | What C++11 features does Visual Studio 2010 support? | There is a list for GCC; is there a similar list for Visual Studio 2010?
| There is also a list for Visual C++ 2010 (that article describes the core language features that have been implemented; the PDF linked from the article describes the library features that have been implemented).
Edit: I've just come across an awesome list: the Apache C++ Standard Library wiki has a table listing the C... |
2,936,805 | 2,937,119 | How do C++ compilers actually pass reference parameters? | This question came about as a result of some mixed-language programming. I had a Fortran routine I wanted to call from C++ code. Fortran passes all its parameters by reference (unless you tell it otherwise).
So I thought I'd be clever (bad start right there) in my C++ code and define the Fortran routine something like ... | Just to chime in, I believe you are right. I use references for passing parameters to Fortran functions all the time. In my experience, using references or pointers at the Fortran-C++ interface is equivalent. I have tried this using GCC/Gfortran, and Visual Studio/Intel Visual Fortran. It may be compiler dependent, but... |
2,936,844 | 2,936,850 | C++: Create abstract class with abstract method and override the method in a subclass | How to create in C++ an abstract class with some abstract methods that I want to override in a subclass? How should the .h file look? Is there a .cpp, if so how should it look?
In Java it would look like this:
abstract class GameObject
{
public abstract void update();
public abstract void paint(Graphics g);
}
... | In Java, all methods are virtual by default, unless you declare them final. In C++ it's the other way around: you need to explicitly declare your methods virtual. And to make them pure virtual, you need to "initialize" them to 0 :-) If you have a pure virtual method in your class, it automatically becomes abstract - th... |
2,936,910 | 2,936,917 | Static variable inside a constructor, are there any drawbacks or side effects? | What I want to do: run some prerequisite code whenever instance of the class is going to be used inside a program. This code will check for requiremts etc. and should be run only once.
I found that this can be achieved using another object as static variable inside a constructor. Here's an example for a better picture:... | This isn't thread-safe, since if two threads try to construct C for the first time at the same time, Prerequisites will probably be initialized twice.
If you're okay with that, you can probably do this, though gaming the scoped constructor system has zero discoverability (i.e. once you forget the 'trick' or others try... |
2,936,993 | 2,937,030 | What is the rationale for difference between -> and . in c/c++? |
Possible Duplicates:
C++: ptr->hello(); /* VERSUS */ (*ptr).hello();
Why does C have a distinction between -> and . ?
I know the difference between the member operator (.) and the member by pointer operator (->).
Why did the C designers create a different operator for this access? Why can't the compiler figure it ou... | When you have a language that is, at its core, intended to be a "portable assembler" you don't try to hide implementation details from the user. Of course the compiler can figure out that in the expression a.b the a in question is a pointer. Can you? Reliably? All the time? In hairy, complicated code? And can you... |
2,937,273 | 2,937,401 | questions about name mangling in C++ | I am trying to learn and understand name mangling in C++. Here are some questions:
(1) From devx
When a global function is overloaded, the generated mangled name for each overloaded version is unique. Name mangling is also applied to variables. Thus, a local variable and a global variable with the same user-given name... | C does not do name mangling, though it does pre-pend an underscore to function names, so the printf(3) is actually _printf in the libc object.
In C++ the story is different. The history of it is that originally Stroustrup created "C with classes" or cfront, a compiler that would translate early C++ to C. Then rest of t... |
2,937,331 | 2,937,424 | win32 console - form example! | I'm trying to build a simple form in a c++ win32 console application.
instead of using cin and keep prompting the user to enter the details, i would like to display the form labels then using the tab key, allow the user to tab through.
What is the simplest way of doing this, without having to use ncurses?
all I need is... |
What is the simplest way of doing
this, without having to use ncurses?
Using ncurses (or an equivalent library) is the simple way to do this, by far.
You seem to forget that tab is just another character when reading by lines (as in cin>>name;). To emulate ncurses, your program would need to handle multiple classe... |
2,937,351 | 2,937,447 | How to use autoconf with C++0x features | What are the best practices for using autoconf in conjunction
with shared_ptr and other TR1/BOOST C++0x templates so as to maximize
portability and maintainability?
With autoconf I can determine whether shared_ptr is
available as std::tr1::shared_ptr and/or boost::shared_ptr. Given
that the same feature has two diffe... | One improvement to your example code, and an answer to your first question, is to use the "template typedef" idiom:
#if HAVE_STD_TR1_SHARED_PTR
template <class T>
struct SharedPtr {
typedef std::tr1::shared_ptr<T> Type;
};
#elif HAVE_BOOST_SHARED_PTR
template <class T>
struct SharedPtr {
... |
2,937,425 | 2,937,522 | boost::enable_if class template method | I got class with template methods that looks at this:
struct undefined {};
template<typename T> struct is_undefined : mpl::false_ {};
template<> struct is_undefined<undefined> : mpl::true_ {};
template<class C>
struct foo {
template<class F, class V>
typename boost::disable_if<is_undefined<C> >::type... | Your C does not participate in deduction for apply. See this answer for a deeper explanation of why your code fails.
You can resolve it like this:
template<class C>
struct foo {
template<class F, class V>
void apply(const F &f, const V &variables) {
apply<F, V, C>(f, variables);
... |
2,937,511 | 2,937,521 | C++ struct containing unsigned char and int bug | Ok i have a struct in my C++ program that is like this:
struct thestruct
{
unsigned char var1;
unsigned char var2;
unsigned char var3[2];
unsigned char var4;
unsigned char var5[8];
int var6;
unsigned char var7[4];
};
When i use this struct, 3 random bytes get added before the "var6", if i delete "var5" it's sti... | The compiler is probably using its default alignment option, where members of size x are aligned on a memory boundary evenly divisible by x.
Depending on your compiler, you can affect this behaviour using a #pragma directive, for example:
#pragma pack(1)
will turn off the default alignment in Visual C++:
Specifies th... |
2,937,822 | 2,938,475 | Is it possible to use Boehm garbage collector only for the part of the program? | I've read article in LinuxJournal about Boehm-Demers-Weiser garbage collector library. I'm interesting to use it in my library instead of my own reference counting implementation.
I have only one question: is it possible to use gc only for my shared library and still use malloc/free in the main application? I'm not qu... | The example in the manual states:
It is usually best not to mix garbage-collected allocation with the system malloc-free. If you do, you need to be careful not to store pointers to the garbage-collected heap in memory allocated with the system malloc.
And more specifically for C++:
In the case of C++, you need to be... |
2,937,971 | 2,937,977 | How are open source projects in C/C++ carried out exactly without .sln/.project files? | Seems most open source projects in C/C++ only provide the source code,i.e. nginx
Is this a convention that anyone interested in joining the developing team should figure out the .sln/.project files himself to qualify??
| most open source projects are coming from the linux side of computing. thus, they are mainly using unix style build tools, as well as open source compilers.
the main build tool is make, which uses a makefile to know how to build a project. on Windows, the main open source compiler is MinGW which is a win32 port of gcc.... |
2,938,160 | 2,940,486 | SWIG interface file questions | I am writing a C/C++ extension module for other languages and I am using SWIG to generate the bindings.
I have two questions
Can I include more than 1 header file in the declaration part of the interface file e.g.:
/* Declarations exposed to wrapper: */
> %{
> #define SWIG_FILE_WITH_INIT
> #include "a.h"
> #include "b... |
Yes ( see http://www.swig.org/Doc1.1/HTML/Library.html )
No ( see http://www.swig.org/tutorial.html ; look for SWIG for the truly lazy )
|
2,938,313 | 2,938,367 | C++/Win32 : XP Visual Styles - no controls are showing up? | Okay, so i'm pretty new to C++ & the Windows API and i'm just writing a small application. I wanted my application to make use of visual styles in both XP, Vista and Windows 7 so I added this line to the top of my code:
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' ... | Do you call InitCommonControlsEx? Details are here.
|
2,938,389 | 2,938,397 | A cross between std::multimap and std::vector? | I'm looking for a STL container that works like std::multimap, but has constant access time to random n-th element. I need this because I have such structure in memory that is std::multimap for many reasons, but items stored in it have to be presented to the user in a listbox. Since amount of data is huge, I'm using li... | What you need is:
Boost Multi-Index
|
2,938,414 | 2,938,429 | How to cast correctly a struct in C++ | Consider a code excerpt below:
typedef struct tagTHREADNAME_INFO {
DWORD dwType;
LPCTSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} THREADNAME_INFO;
const THREADNAME_INFO info = { 0x1000, threadName, CurrentId(), 0};
::RaiseException(kVCThreadNameException, 0,
sizeof(info) / sizeof(ULONG_PTR),
... | I guess it would be const_cast<ULONG_PTR*>(reinterpret_cast<const ULONG_PTR*>(&info)).
From Effective C++, 3rd. Ed., Item 27:
const_cast is typically used to cast away the constness of objects. It is the only C++-style cast that can do this.
reinterpret_cast is intended for low-level casts that yield implementation-d... |
2,938,435 | 2,938,448 | COM(C++) programming tutorials? | Are there any good sites for learning C++/COM from the ground up? I'm looking for something like a crash course with perhaps two weeks' worth of content.
The course can assume knowledge in standard C/C++, or at least not a complete dummy.
| Since you're asking for websites, you can try this introduction to COM on The Code Project, and how to handle COM in plain C and in C++ on the same site. And of course, you have MSDN.
|
2,938,467 | 2,938,472 | Instantiating a class within a class | I'm trying to instantiate a class within a class, so that the outer class contains the inner class.
This is my code:
#include <iostream>
#include <string>
class Inner {
private:
std::string message;
public:
Inner(std::string m);
void print() const;
};
Inner::Inner(std::string m) {
... | You need to use initialization lists to initialize class members:
Inner::Inner(const std::string& m)
: message(m)
{
}
Outer::Outer(const std::string& m)
: in(m)
{
}
(Note that I passed the strings per const reference, which is better than passing them by value. See this answer for how to pass function arguments.... |
2,938,545 | 2,938,630 | Why can operator-> be overloaded manually? | Wouldn't it make sense if p->m was just syntactic sugar for (*p).m? Essentially, every operator-> that I have ever written could have been implemented as follows:
Foo::Foo* operator->()
{
return &**this;
}
Is there any case where I would want p->m to mean something else than (*p).m?
| operator->() has the bizarre distinction of implicitly being invoked repeatedly while the return type allows it. The clearest way to show this is with code:
struct X {
int foo;
};
struct Y {
X x;
X* operator->() { return &x; }
};
struct Z {
Y y;
Y& operator->() { return y; }
};
Z z;
z->foo = 42;... |
2,938,571 | 2,938,589 | How to declare a function that accepts a lambda? | I read on the internet many tutorials that explained how to use lambdas with the standard library (such as std::find), and they all were very interesting, but I couldn't find any that explained how I can use a lambda for my own functions.
For example:
int main()
{
int test = 5;
LambdaTest([&](int a) { test += a... | Given that you probably also want to accept function pointers and function objects in addition to lambdas, you'll probably want to use templates to accept any argument with an operator(). This is what the std-functions like find do. It would look like this:
template<typename Func>
void LambdaTest(Func f) {
f(10);
}... |
2,938,592 | 2,938,696 | C++ Primer Plus: 2D Arrays | I've just started working through C++ Primer Plus and I have hit a little stump.
const int MONTHS = 12;
const int YEARS = 3;
int sales[YEARS][MONTHS] = {0};
const string months[MONTHS] = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "No... | #include <iostream>
#include <string>
using namespace std;
int main (void)
{
const int MONTHS = 12;
const int YEARS = 3;
int sales[YEARS][MONTHS] = {0};
const string months[MONTHS] = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "Novemb... |
2,938,689 | 2,939,310 | Azure and native code | It looks like you can host native code on Azure: http://msdn.microsoft.com/en-us/library/dd573362.aspx. Is it possible to run a socket server (listening tcp/udp) here? And even hosting a CLR on top?
| It's easy to run a socket server on a worker role, but only tcp, not udp. You can start your own process from the worker role's OnStart() method You can do it from the Run() method too but once you hit the run state, your role is seen by the load balancer and outside world, so you might get tcp traffic before your sock... |
2,938,744 | 2,938,910 | can't increment Glib::ustring::iterator (getting "invalid lvalue in increment" compiler error) | in the following code:
int utf8len(char* s, int len)
{
Glib::ustring::iterator p( string::iterator(s) );
Glib::ustring::iterator e ( string::iterator(s+len) );
int i=0;
for (; p != e; p++) // ERROR HERE!
i++;
return i;
}
I get the compiler error on the for line, which is sometimes "invalid lvalue in incremen... | Your declaration declares this function:
Glib::ustring::iterator p(string::iterator s);
The parentheses in your code around s are ignored. They are like the parentheses around n in the following example
int(n);
n = 0; /* n is actually an int variable! */
They are for grouping modifiers like pointer (*) or references ... |
2,938,755 | 2,938,759 | A public struct inside a class | I am new to C++, and let's say I have two classes: Creature and Human:
/* creature.h */
class Creature {
private:
public:
struct emotion {
/* All emotions are percentages */
char joy;
char trust;
char fear;
char surprise;
char sadness;
char disgust;
ch... | There is no variable of the type emotion. If you add a emotion emo; in your class definition you will be able to access foo.emo.fear as you want to.
|
2,938,939 | 2,938,996 | Generic transparent Qt widget that can catch clicks? | I've figured out how to use QPainter to draw rectangles. Now I want to have a drawing area where if the user clicks, a 1x1 rectangle is drawn where the mouse pointer is. To accomplish this, I assume I need a transparent Qt widget that supports the clicked() signal.
How do I make such a transparent widget? Or is there s... | You don't really need a transparent widget?
All you have to do is implement
protected:
void mousePressEvent(QMouseEvent *event);
for your widget and draw your rectangle.
Take a look at scribble example that comes with Qt.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.