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,069,375 | 3,069,403 | setting value of string& to string | I have a string& parameter, and i want to assign it to string parameter.
How can it be done.
| void f(string ¶m);
string myString = "something";
f(myString)
Is that what you need?
|
3,069,545 | 3,069,570 | Handles and pointer to object | I have a python Interpreter written in C++, the PyRun_String function from the Python API is said to return a handle, however in my code I have it assigned to pointer to a PyObject?
PyObject* presult = PyRun_String(code, parse_mode, dict, dict);
Is this actually correct? Can you implicitly cast this handle to this object pointer?
Should it not be a HANDLE instead?
| The word "handle" in API documentation usually does not refer specifically to the HANDLE type, but rather to any type intended to be opaque to the user.
PyRun_String in particular returns a PyObject*, there is no cast going on.
|
3,069,613 | 3,069,724 | Why doesn't g++ pay attention to __attribute__((pure)) for virtual functions? | According to the GCC documentation, __attribute__((pure)) tells the compiler that a function has no side-effects, and so it can be subject to common subexpression elimination.
This attribute appears to work for non-virtual functions, but not for virtual functions. For example, consider the following code:
extern void f( int );
class C {
public:
int a1();
int a2() __attribute__((pure));
virtual int b1();
virtual int b2() __attribute__((pure));
};
void test_a1( C *c ) {
if( c->a1() ) {
f( c->a1() );
}
}
void test_a2( C *c ) {
if( c->a2() ) {
f( c->a2() );
}
}
void test_b1( C *c ) {
if( c->b1() ) {
f( c->b1() );
}
}
void test_b2( C *c ) {
if( c->b2() ) {
f( c->b2() );
}
}
When compiled with optimization enabled (either -O2 or -Os), test_a2() only calls C::a2() once, but test_b2() calls b2() twice.
Is there a reason for this? Is it because, even though the implementation in class C is pure, g++ can't assume that the implementation in every subclass will also be pure? If so, is there a way to tell g++ that this virtual function and every subclass's implementation will be pure?
| Without looking into g++'s internals, I suspect it's because g++ can't assume that every subclass's implementation will be pure (like you said).
Can you turn b2 into a non-virtual pure wrapper around a virtual non-pure method?
|
3,069,801 | 3,069,814 | Where can I define the body for a private function? | I have a header like this (header guards not shown):
class GameSystem
{
public:
GameSystem(Game *pcGame);
virtual ~GameSystem();
void Setup();
private:
void InitGame();
void RunGame();
void ExitGame();
Game *m_pcGame;
/* Properties */
int m_nWidth;
int m_nHeight;
int m_nFps;
bool m_bFullscreen;
};
Where can I define the body for InitGame(), RunGame() and ExitGame()? Can I define it in my .cpp file? If so, how? Or am I obliged to make their body in my .h file?
I'm using Eclipse and I began typing: void GameSystem:: and then it doesn't suggest the private functions.
| Yes, you can define then in a .cpp file. Just put #include "MyHeader.h" at the beginning of the file. You'll also need to start each function like so
void GameSystem::Init(){
//stuff
}
|
3,069,862 | 3,069,960 | Help with Arduino and Analog Min Max settings | Hey there, I have the following code:
sVal = analogRead(potPin); // read the value from the sensor
valMin = min(sVal, 1);
valMax = max(sVal, 128);
constrain(sVal,valMin,valMax);
itoa(sVal, res, 10);
println(res);
println(" ");
delay(150);
clearScreen();
Now for some reason, the output on the gLCD screen is almost constantly 1023.
I would like the minimum for the potentiometer to be 1 and the maximum to be 128.
| Your code indicates a lack of understanding of the min, max and constrain functions. I suggest you read the documentation more carefully.
In the meantime, here is what I think you're after:
sVal = analogRead(potPin);
sVal = sVal / 8 + 1; //scale value [0.. 1023] to [1.. 128]
itoa(sVal, res, 10);
println(res);
println(" ");
delay(150);
clearScreen();
|
3,069,945 | 3,070,112 | Open source soft modem that runs on Linux? | Can anyone recommend an open source soft modem (a software only emulation of a modem card), that runs on Linux?
Preferably, this will be implemented in C/C++
| take a look at iaxmodem
|
3,069,950 | 3,070,012 | Changing number precision | How would you change the precision of a number for example: float n = 1.2345 and store it back to the variable 'n' with changing it to 1.23 ?
| float n = 1.2345;
int scaled = n * 100
n = static_cast<float>(scaled)/100.0;
or in one line:
n = static_cast<float>( static_cast<int>(n*100) ) / 100;
|
3,070,187 | 3,070,203 | C++ / Java: Toggle boolean statement? | Is there a short way to toggle a boolean?
With integers we can do operations like this:
int i = 4;
i *= 4; // equals 16
/* Which is equivalent to */
i = i * 4;
So is there also something for booleans (like the *= operator for ints)?
In C++:
bool booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?
In Java:
boolean booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?
| There is no such operator, but this is a little bit shorter: booleanWithAVeryLongName ^= true;
|
3,070,290 | 3,070,806 | C++ vtable resolving with virtual inheritance | I was curious about C++ and virtual inheritance - in particular, the way that vtable conflicts are resolved between bass and child classes. I won't pretend to understand the specifics on how they work, but what I've gleamed so far is that their is a small delay caused by using virtual functions due to that resolution. My question then is if the base class is blank - ie, its virtual functions are defined as:
virtual void doStuff() = 0;
Does this mean that the resolution is not necessary, because there's only one set of functions to pick from?
Forgive me if this is an stupid question - as I said, I don't understand how vtables work so I don't really know any better.
EDIT
So if I have an abstract class with two seperate child classes:
A
/ \
/ \
B C
There is no performance hit when calling functions from the child classes compared to say, just a single inheritance free class?
| There is no hit for calling nonvirtual functions in the child class. If you're calling an overridden version of your pure virtual function as in your example, then the virtual penalty may still exist. In general it's difficult for compilers to optimize away the use of the virtual table except under very specific circumstances, where it knows the exact by-value type of the object in question (from context).
But seriously don't worry about the overhead. It's going to be so little that in practice you will almost certainly never encounter a situation where it's the part of code causing performance bottlenecks. Use virtual functions where they make sense for your design and don't worry about the (tiny) performance penalty.
|
3,070,317 | 3,070,710 | question on arrays in c++ | int java declaration of array like this
int a[][]=new int[3][3] works but in c++ not why? please help me i have not used c++ a long time so please help me
| I once had this same problem and ended up creating a class for it. Basically it's stored as a pointer of single dimension array and the pointers are manipulated a bit so that it acts just like a 2D array (matrix). Here's the code I used:
#include <utility>
#include <memory.h>
template <typename T>
class Matrix
{
protected:
T** m;
int x,y;
__forceinline void setMatrix()
{
assert(x > 0);
assert(y > 0);
m = new T*[y];
m[0] = new T[x*y];
for (int i = 1; i < y; ++i)
{
m[i] = m[i-1] + x;
}
}
public:
Matrix():m(0),x(0),y(0){}
Matrix(int rows, int cols):x(cols),y(rows),m(0)
{
setMatrix();
}
Matrix(const Matrix<T>& mat):m(0),x(mat.x),y(mat.y)
{
setMatrix();
memcpy_s(m[0], x*y, mat.m[0], x*y);
}
~Matrix()
{
if (m)
{
delete[] m[0];
delete[] m;
}
}
void fill(const T& val)
{
if (m)
{
for (int j = 0; j < y; ++j)
for (int i = 0; i < x; ++i)
m[j][i] = val;
}
}
T& at(int row, int col)
{
assert(row >= 0 && row < y);
assert(col >= 0 && col < x);
return m[row][col];
}
const T& at(int row, int col) const
{
assert(row >= 0 && row < y);
assert(col >= 0 && col < x);
return m[row][col];
}
T* operator[](int row)
{
assert(row >= 0 && row < y);
return m[row];
}
const T* operator[](int row) const
{
assert(row >= 0 && row < y);
m[row];
}
T& operator ()(int row, int col)
{
assert(row >= 0 && row < y);
assert(col >= 0 && col < x);
return m[row][col];
}
const T& operator ()(int row, int col) const
{
assert(row >= 0 && row < y);
assert(col >= 0 && col < x);
return m[row][col];
}
void swap(Matrix<T>& mat)
{
std::swap(m, mat.m);
std::swap(x, mat.x);
std::swap(y, mat.y);
}
const Matrix& operator = (const Matrix<T>& rhs)
{
Matrix temp(rhs);
swap(temp);
return *this;
}
//
int getRows() const
{
return y;
}
int getColumns() const
{
return x;
}
};
Usage would be like:
typedef Matrix<int> IntMatrix;
IntMatrix mat(2,3); // Creates a 2x3 matrix to store integers.
mat.fill(0); // Fill it with zeroes.
int val02 = mat[0][2]; // Unsafe way to retrieve values
int val12 = mat(1,2); // Safe way to retrieve values;
mat(0,1) = 10; // Assign values directly to the matrix.
You can also extend this class so that it has other matrix related function in it.
|
3,070,417 | 3,070,760 | ITASK API for Windows Scheduler | Does anybody know what permissions are needed to create ITASK?
This is the error I am getting in C++:
Error creating ITask. Error: -2147024891
| That error is 0x80070005 in hex. Facility 7 = Windows, error code 5 = Access Denied. The user account used to run this code doesn't have sufficient rights. Creating scheduled tasks is a privileged operation. Talk to the server admin about getting the rights to do this.
|
3,070,425 | 3,070,566 | Best way to write a recursive function in C++? | Question
I wish to know if this is a viable way to implement variable depth recursion so that I can run a function at each step and any better/other solutions to the description problem.
Description
Suppose I wish to have a function that fills an array either in pattern
x,y,x,y,x,ywhere x and y are variables defined by some algorithm
and x,y,z,x,y,z where x, y and z are variables defined by the same algorithm.
This should continue for all number of variables. Is this a viable way to implement it.
void recurse_n(int n)
{
while(n > 0)
{
--n;
recurse_n(n);
n = 0;
// Use algorithm here
}
}
EDIT: Removed the incorrect return type previously referred to. Brainfart.
| So, based on your comment you want to know the best way to set up a recursive function. What you have done will work, but it is convoluted and slightly confusing. What I would do to simplify it is:
void recurse_n(int n) {
if (n <= 0) {
// Break-out condition
return;
}
--n;
recurse_n(n);
// Your algorithm stuff here.
}
That will make it easier to see what is going on. One thing I would add though is that you might want to do the algorithm stuff before the call to recurse_n, but that all depends on what your algorithm is doing.
If you think about it, the way I have written it, it will recurse until n is less than or equal to 0 before doing any of the algorithm work. It might be that you want to do the algorithm work then recurse.
|
3,070,461 | 3,070,859 | Unexpected termination when pushing a shared_ptr into a list | I have some function:
void addNormalLine(int id, LineNumber number, Rate smsRate, Rate callRate) {
list<Account>::iterator iAccounts;
findAccount(iAccounts, id);
if(iAccounts == listOfAccounts.end()){
throw "AccountDoesNotExist";
}
if(lineExists(number)){
throw "LineExists";
} else{
iAccounts->increaseNumLines();
shared_ptr<Line> currentLine(new Line(id, number, smsRate, callRate)); //here I have some problems
listOfLines.push_back(currentLine); //without these two rows it works, but didn't add lines to my list
}
}
Account, Rate, LineNumber - some classes
but It always add only one or two numbers, if I add 3 it always terminates and and I recieve terminated, exit value: 3, I tried google it, but didn't find, what is than supposed to mean, thanks in advance
| It's a bad practice to use strings as exception values. Use classes for exceptions, at least something like std::runtime_error() or better create a new class derived from it.
Make sure you catch exceptions you're throwing in this method.
What's the definition of findAccount?
|
3,070,625 | 3,070,658 | Is there an open source netflow collector C++ library set? | I am looking for a C++ library set to develop my own C++ daemon in Linux for collecting NetFlow information. Does anyone know of an open source one or a library set that is available?
Many thanks
| Have you tried Googling? There are plenty of daemons for NetFlow available, for Linux and BSD flavors:
http://www.mindrot.org/projects/softflowd/
http://fprobe.sourceforge.net/
http://lionet.info/ipcad/
|
3,070,730 | 3,078,106 | Video display with openGL | I want to display very high resolution video directly with OpenGL.
The image data is going to be processed on the GPU and I want to avoid a round-trip back to the PC to show the video in a standard bitmap based window.
Cross platform is nice, Windows only would be OK (so would nvidia only)
Anyone have any links to ways doing this?
There is a poor NeHe tutorial and a few examples for embedded openGL widgets in Qt but I need much better performance and much larger images.
| Assuming OpenGL 2.1, use a buffer object of type GL_PIXEL_UNPACK_BUFFER to stream pixel data to a texture. It's faster than uploading data every frame as the implementation might use DMA for copying when you use glMapBuffer, glMapBufferRange (OpenGL 3.2) or call glBufferData directly. You can also copy several frames in each batch to get a tradeoff between copy-overhead and mapping overhead. Last, create a shader to convert YUV or YCbCr to RGB and display the texture with a triangle strip.
|
3,070,786 | 3,070,829 | C++ Generate and store the co-ordinates of an n-cube | I want to write a function to generate and store the co-ordinates of an n-cube and I have no idea how to start. Specifically, I wish to generate the co-ordinates for an evenly or randomly distributed cloud of points for this n-cube and store them. What would be a good way to start with this or if possible, a quick solution?
| I don't want to give C++ source code for this problem, however, here's the thought how you could generate it.
A hypercube contains all bit-strings of length n. Thus there are 2^n possibilities for coordinates in total.
Now how you can do it recursively:
if you want to generate coordinates for n=1, just return 0 and 1
if you want to generate coordinates for n>1, take 0 and concatenate it to all possible coordinates for n'=n-1, then take 1 and concatenate it to all possible coordinates for n'=n-1
|
3,070,805 | 3,070,815 | How to design a utility class? | But I don't know if I should go for static methods, just a header, a class, or something else?
What would be best practice? But, I don't want to have an instance of a utility class.
I want to add functions like:
Uint32 MapRGB (int r, int g, int b);
const char* CopyString(const char* char);
// etc. You know: utility methods...
| Don't put them in a class; just make them non-member functions at namespace scope.
There's no rule that says every function has to be a member function of some class.
|
3,070,841 | 3,071,740 | Is stack address shared by Heap addresses? | I read On most operating systems, the addresses in memory starts from highest to lowest. So I am wondering if the heap, stack, and global memory all fall under the same ordering..?
If I created...
pointerType* pointer = new pointerType //creates memory address 0xffffff
And then created a local varible on the stack
localObject object
would localObjects address be 0xfffffe
Or is heap and stack ordering completely different.
|
the addresses in memory starts from highest to lowest
Are the addresses of the houses on your street ordered from highest to lowest, or from lowest to highest? Well, that depends on which way you're driving.
Just like postal addresses, memory addresses aren't really ordered at all. Each address simply identifies a unique location in memory (At least conceptually. We'll ignore, for a moment, segmented or virtual memory).
But when your mail carrier delivers the daily mail, he most likely does work in either highest-to-lowest or lowest-to-highest order (probably both, down one side of the street, and up the other side). This is more efficient, of course, than jumping from house to house at random. In addition, it makes the carrier's job much simpler. If he were to jump from house to house in a random order, it would be difficult to keep track of which houses he had already visited, and which ones still needed delivery. If he simply goes in order, then the position of his truck is all he needs to keep track of.
A stack is similar to this. It doesn't occupy arbitrary positions in memory, but instead has a first position, and subsequent positions follow in logical order from there. In this way, a stack pointer (often "SP") is all that is needed to keep track of which stack locations are occupied and which are free.
A heap is necessarily different, though. While a stack inherently has a first-in-last-out ordering, a heap is inherently unordered. Heap memory can be allocated and deallocated at any time. Earlier allocations can outlive later allocations. A heap, therefore, must be able to allocate arbitrary address ranges, and has to keep track of them all.
Because of the different ways in which the stack and heap operate, they should occupy different areas of memory. In your example, a second stack allocation would overwrite memory occupied by your heap allocation. Obviously, this would be a bad thing, and is what is referred to as a stack overflow.
Most modern CPUs have all the features necessary to keep stack memory and heap memory completely separate. This is where memory segments and virtual memory come into play. On some platforms, the stack and the heap may be identified by the same address range, while still occupying different areas of physical memory or even secondary storage. A discussion of how this works it outside the scope of this post.
Most modern operating systems don't actually do this, though. More commonly, a "flat" address space is used, where all addresses, whether stack, heap, code, or whatever, refer to the same address space. This makes it easier for the application developer, by obviating the need to juggle segment identifiers for every address.
In a flat address space, the same scheme of separating stack and heap is used that was used in ancient CPUs that had no memory segmentation or virtualization: the stack grows down from the "top" of memory (higher addresses), and the heap grows up from the bottom of memory (lower addresses). A certain point between the two may be picked to be the limit of both, and when one reaches the point, an error condition occurs—either stack overflow or out of memory.
Of course, this description is a huge simplification, but hopefully it gives a better basic understanding.
|
3,070,904 | 3,070,999 | C++ compiler error on template specialization | I would like to specialize a template method for a class C that is itself
templated by an int parameter.
How do I do this?
template <int D=1>
class C {
static std::string foo () { stringstream ss; ss << D << endl; return ss.str();}
};
template <class X>
void test() { cout << "This is a test" << endl;}
template <>
template <int D>
void test<C<D> > () {cout << C<D>::foo() << endl;}
The specialization for test() fails with "Too many template parameter lists in declaration of void test()".
| Function template partial specialization is not allowed. Do
template <int D>
void test () {cout << C<D>::foo() << endl;}
|
3,070,928 | 3,070,984 | C++ map to track when the end of map is reached | Currently I have a map that prints out the following
map<string, map<int,int> > mapper;
map<int,int>::iterator inner;
map<string, map<int,int> >::iterator outer;
for(outer = mapper.begin(); outer != mapper.end(); outer++){
cout<<outer->first<<": ";
for(inner = outer->second.begin(); inner != outer->second.end(); inner++){
cout<<inner->first<<","<<inner->second<<",";
}
}
As of now this prints out the following
stringone: 1,2,3,4,6,7,8,
stringtwo: 3,5,6,7,
stringthree: 2,3,4,5,
What i want it to print out is
stringone: 1,2,3,4,6,7,8
stringtwo: 3,5,6,7
stringthree: 2,3,4,5
how can i check for the end of the map inside my inner map?
Any help would be appreciated Thank you
| Change your output line to print the comma first and only if it is not the first element:
if (inner != outer->second.begin())
std::cout << ",";
std::cout << inner->first << "," << inner->second;
|
3,071,020 | 3,071,108 | IF Statement has strange behavior | I've developed a 'custom' cout, so that I can display text to console and also print it to a log file. This cout class is passed a different integer on initialization, with the integer representing the verbosity level of the message. If the current verbosity level is greater then or equal to the verbosity level of the message, the message should print.
The problem is, I have messages printing even when the current verbosity level is too low. I went ahead and debugged it, expecting to find the problem. Instead, I found multiple scenarios where my if statements are not working as expected.
The statement if(ilralevel_passed <= ilralevel_set) will sometimes proceed even if ilralevel_set is LESS then ilralevel_passed. You can see this behavior in the following picture (my apologizes for using Twitpic) http://twitpic.com/1xtx4g/full. Notice how ilralevel_set is equal to zero, and ilralevel_passed is equal to one. Yet, the if statement has returned true and is now moving forward to pass the line to cout.
I've never seen this type of behavior before and I'm not exactly sure how to proceed debugging it. I'm not able to isolate the behavior either -- it only occurs in certain parts of my program. Any suggestions are appreciated as always.
// Here is an example use of the function:
// ilra_status << setfill('0') << setw(2) << dispatchtime.tm_sec << endl;
// ilra_warning << "Dispatch time (seconds): " << mktime(&dispatchtime) << endl;
// Here is the 'custom' cout function:
#ifndef ILRA_H_
#define ILRA_H_
// System libraries
#include <iostream>
#include <ostream>
#include <sstream>
#include <iomanip>
// Definitions
#define ilra_talk ilra(__FUNCTION__,0)
#define ilra_update ilra(__FUNCTION__,0)
#define ilra_error ilra(__FUNCTION__,1)
#define ilra_warning ilra(__FUNCTION__,2)
#define ilra_status ilra(__FUNCTION__,3)
// Statics
static int ilralevel_set = 0;
static int ilralevel_passed;
// Classes
class ilra
{
public:
// constructor / destructor
ilra(const std::string &funcName, int toset)
{
ilralevel_passed = toset;
}
~ilra(){};
// enable / disable irla functions
static void ilra_verbose_level(int toset){
ilralevel_set = toset;
}
// output
template <class T>
ilra &operator<<(const T &v)
{
if(ilralevel_passed <= ilralevel_set)
std::cout << v;
return *this;
}
ilra &operator<<(std::ostream&(*f)(std::ostream&))
{
if(ilralevel_passed <= ilralevel_set)
std::cout << *f;
return *this;
}
}; // end of the class
#endif /* ILRA_H_ */
| When you define a static variable outside a class, you're defining a separate variable for each source file into which you include the header -- changing the value in one doesn't affect the value of the variable with the same name in another file.
What you almost certainly want is to have
int ilralevel_set = 0;
int ilralevel_passed;
In one file where you're defining your object, and:
extern int ilralevel_set;
extern int ilralevel_passed;
in the header. Alternatively, it looks like you could move it all inside the class:
class ilra {
int passed_level;
int set_level;
public:
ilra(int toset) : passed_level(toset), set_level(0) {}
verbose_level(int toset) { set_level = toset; }
// ...
};
|
3,071,475 | 3,071,686 | String method crashes program | Alright so i have two identical string methods...
string CreateCust() {
string nameArray[] ={"Tom","Timo","Sally","Kelly","Bob","Thomas","Samantha","Maria"};
int d = rand() % (8 - 1 + 1) + 1;
string e = nameArray[d];
return e;
}
string CreateFood() {
string nameArray[] = {"spagetti", "ChickenSoup", "Menudo"};
int d = rand() % (3 - 1 + 1) + 1;
string f = nameArray[d];
return f;
}
however no matter what i do it the guts of CreateFood it will always crash. i created a test chassis for it and it always fails at the cMeal = CreateFood();
Customer Cnow;
cout << "test1" << endl;
cMeal = Cnow.CreateFood();
cout << "test1" << endl;
cCustomer = Cnow.CreateCust();
cout << "test1" << endl;
i even switched CreateCust with CreateFood and it still fails at the CreateFood Function...
NOTE: if i make createFood a int method it does work...
Also guys even if i changed CreateFood to just COUT a message and nothing more it still crashed...
| The crash is happening because you are accessing an invalid index. This is because array indexes start from 0 and not 1, so you don't want to add a 1 to the rvalue of the modulus operator.
Here is a neat trick that you can use to make your code a little more maintainable:
template <class T>
T getRandElem( const T[] arr )
{
return arr[ rand() % ( sizeof(arr) / sizeof((arr)[0]) ) ];
}
string CreateCust(){
static string nameArray[] = {"Tom","Timo","Sally","Kelly","Bob","Thomas","Samantha","Maria"};
return getRandElem<string>( nameArray );
}
string CreateFood(){
static string nameArray[] = {"spagetti", "ChickenSoup", "Menudo"};
return getRandElem<string>( nameArray );
}
|
3,071,652 | 3,071,707 | CPU Process time using GetProcessTimes and FileTimeToSystemTime do not work in 64 bit win | I am trying to measure CPU time.
It works great on Win 32, but on 64 bit, it says:
error LNK2019: unresolved external symbol __imp_GetProcessTimes referenced in function "unsigned int __cdecl getWINTime(void)" (?getWIN32Time@@YAIXZ)
It has similar error for FileTimeToSystemTime
error LNK2019: unresolved external symbol __imp_FileTimeToSystemTime referenced in function "unsigned int __cdecl getWINTime(void)" (?getWIN32Time@@YAIXZ)
Function itself is not that important there is no issue with it.
Are this calls legit in 64 bit architecture or what?
This is not the only issue it seems like its not linking correctly to libraries on 64 bit windows.
Is there a setting I should set for it to link properly?
| Do you're build settings for the two environments have the same import libraries listed. Both of those functions are in kernel32.dll.
|
3,071,665 | 3,071,729 | Getting a directory name from a filename | I have a filename (C:\folder\foo.txt) and I need to retrieve the folder name (C:\folder) in C++. In C# I would do something like this:
string folder = new FileInfo("C:\folder\foo.txt").DirectoryName;
Is there a function that can be used in C++ to extract the path from the filename?
| There is a standard Windows function for this, PathRemoveFileSpec. If you only support Windows 8 and later, it is highly recommended to use PathCchRemoveFileSpec instead. Among other improvements, it is no longer limited to MAX_PATH (260) characters.
|
3,071,710 | 3,072,061 | What is the fastest design to download and convert a large binary file? | I have a 1GB binary file on another system.
Requirement: ftp/download and convert binary to CSV on main system.
The converted file will be magnitudes larger ~ 8GB
What is the most common way of doing something similar to this?
Should this be a two step independent process, download - then convert?
Should I download small chunks at a time and convert while downloading?
I don't know the most efficient way to do this...also what should I be cautions of with files this size?
Any advice is appreciated.
Thank You.
(Visual Studio C++)
| I would write a program that converts the binary format and outputs to CSV format. This program would read from stdin and write to stdout.
Then I would call
wget URL_of_remote_binary_file --output-document=- | my_converter_program > output_file.csv
That way you can start converting immediately (without downloading the entire files) and your program doesn't deal with networking. You can also run the program on the remote side, assuming it's portable enough.
|
3,071,785 | 3,072,002 | does sfinae instantiates a function body? | I want to detect existence of a specific member function for a class, using the usual SFINAE trick.
template<typename T>
struct has_alloc
{
template<typename U,U x>
struct dummy;
template<typename U>
static char test(dummy<void* (U::*)(std::size_t),&U::allocate>*);
template<typename U>
static char (&test(...))[2];
static bool const value = sizeof(test<T>(0)) ==1;
};
It should be noted that this detects a different kind of allocator which has void* allocate(std::size_t) as member function which are non standard (probably some raw memory allocator).
Next, I have an incomplete type and an std::allocator for that incomplete type.
struct test;
typedef std::allocator<test> test_alloc;
And I am checking whether the test_alloc is the one I am looking for.
struct kind_of_alloc
{
const static bool value = has_alloc<test_alloc>::value;
};
Surely struct test will be complete when I will "use" test_alloc such as
#include "test_def.hpp"//contains the code posted above
struct test{};
void use()
{
test_alloc a;
}
in another compilation unit. However when the has_alloc test happens,the compiler tries to instantiate the allocate function for std::allocator and finds that sizeof an incomplete type is used inside function body, and causes a hard error.
It seems that the error doesn't occur if the implementation of allocate separated and included separately at the point of use such as
template<typename T>
T* alloc<T>::allocate(std::size_t n)
{
return (T*)operator new(sizeof(T)*n);
}
void use()
{
test_alloc a;
a.allocate(2);
}
And test_def.hpp contains
template<typename T>
struct alloc
{
T* allocate(std::size_t n);
};
However while I can do this for alloc<T> , it is not possible for std::allocator as separating out the implementation is not possible.
What I am looking for is it possible to test whether a function with void* allocate(size_t) exists in test_alloc. If not, it will test negative, and if yes ,i.e. if the function signature matches, even if it can not be instantiated there, test positive.
| No, SFINAE is only in effect during overload resolution. Once a resolution has been made and the compiler begins instantiating the function SFINAE is over.
Edit: and taking the address of a function instantiates it.
|
3,071,806 | 3,071,899 | C++ Union, Struct, Member type | If I have a class:
class Odp
{
int i;
int b;
union
{
long f;
struct
{
WCHAR* pwszFoo;
HRESULT hr;
};
};
}
Union means that, of all values listed, it can only take on one of those values at a time? How does that work in terms of accessing these variables? How would I access hr directly? If I set hr, what happens if I try to access f?
| This is a very fraught area in the C++ standard - basically a union instance, per the standard can only be treated at any one time as if it contained one "active" member - the last one written to it. So:
union U {
int a;
char c;
};
then:
U u;
u.a = 1;
int n = u.a;
u.c = 2;
char c = u.c;
is OK, but:
U u;
u.a = 1;
char c = u.c;
is not. However, there are vast volumes of existing code that say that both are OK. and in neither, or any, case will an exception be thrown for an "invalid" access. The C++ language uses exceptions exceptionally (!) sparingly.
Basically, if you find yourself using unions in your C++ code to deal with anything but C libraries, something is wrong.
|
3,072,050 | 3,072,194 | Can I reconstruct C++ source code from debug binaries? | I have a C++ application compiled in debug (using MinGW and Qt) but I've lost some major changes because someone in my team forgot to commit his changes in the source control manager and overwrote the source code with other changes.
When I run the program in debug (in Qt Creator) I can set a break point in main and then see the source code.
Is there a way to reconstruct all the source file lost using only the debug binaries? Either manually or automatically.
Thanks!
|
When I run the program in debug (in Qt Creator) I can set a break point in main and then see the source code.
Really? Find out where your debugger is getting the source code from, and copy it from there.
It's more likely that your debugger is just grabbing a file on your system with the same name/path as the original filename (perhaps a more recent version, or an old version, etc) and things just happen to line up.
You can not truly regenerate the original source form a compiled binary, because the transformation from C++ source to a compiled binary is not a 1 to 1 relationship. There are many (infinitely...) different source files which will compile to the same binary. There is no way to know from looking at a binary what the original source looked like.
There are tools which can generate something which resembles a C++ source file, but more than likely it'll look nothing like your original source.
|
3,072,074 | 3,072,089 | sizeof(Structure) Confusion | In the following piece of code,
#include<stdio.h>
typedef struct {
int bit1:1;
int bit3:4;
int bit4:4;
} node;
int main(){
node n,n1,n2,ff[10];
printf("%d\n",sizeof(node));
return 0;
}
How do I predict the size of the structure?
| You cannot predict it without knowing the compiler and the target platform it compiles to.
|
3,072,248 | 3,072,399 | Why aren't template specializations allowed to be in different namespaces? | Please, see what I am trying to do:
#include <iostream>
namespace first
{
template <class T>
class myclass
{
T t;
public:
void who_are_you() const
{ std::cout << "first::myclass"; }
};
}
namespace second
{
using first::myclass;
template <>
class myclass <int>
{
int i, j;
public:
void who_are_you() const
{ std::cout << "second::myclass"; }
};
}
This isn't allowed. Could you please, clarify why can't specializations be in different namespaces, and what are the available solutions? Also, is it something fixed in C++0x?
This would allow me for example, to specialize std::max, std::swap, std::numeric_limits, etc.. without resorting to undefined behavior by adding something to ::std::?
@AndreyT Here is how I though I would use it:
// my_integer is a class
std::numeric_limits<my_integer>::max(); // specialized std::numeric_limits for my_integer
Can this be done?
| C++ 2003, §17.4.3.1/1: "A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library template results in undefined behavior unless the declaration depends on a user-defined name of external linkage and unless the specialization meets the standard library requirements for the original template."
As such, you're allowed to specialize a library template, and put your specialization in namespace std, as long as it depends on a user defined type and meets the requirements of the original template.
The code you have in your edited question seems to be a specialization for a user-defined name that (presumably) has external linkage, so you shouldn't have any problem with that part of things.
That leaves only the requirement that your specialization meet the requirements of the original template. For your type, most of this will probably border on trivial. The only part I can see that might not be obvious is that you do seem to have to provide a specialization for the whole template, not just numeric_limits::max(). I.e., you'll have to do something like (example should be in the ballpark for a 128-bit unsigned integer type):
namespace std {
template <>
class numeric_limits<my_integer> {
public:
static const bool is_specialized = true;
static T min() throw() { return 0;
static T max() throw() { return /* 2^128-1 */; } // ***
static const int digits = 128;
static const int digits10 = 38;
static const bool is_signed = false;
static const bool is_integer = true;
static const bool is_exact = true;
static const int radix = 2;
static T epsilon() throw() { return 0; }
static T round_error() throw() { return 0; }
static const int min_exponent = 0;
static const int min_exponent10 = 0;
static const int max_exponent = 0;
static const int max_exponent10 = 0;
static const bool has_infinity = false;
static const bool has_quiet_NaN = false;
static const bool has_signaling_NaN = false;
static const float_denorm_style has_denorm = denorm_absent;
static const bool has_denorm_loss = false;
static T infinity() throw() { return 0; }
static T quiet_NaN() throw() { return 0; }
static T signaling_NaN() throw() { return 0; }
static T denorm_min() throw() { return 0; }
static const bool is_iec559 = false;
static const bool is_bounded = true;
static const bool is_modulo = true;
static const bool traps = false;
static const bool tinyness_before = false;
static const float_round_style round_style = round_toward_zero;
};
}
Quite a few of those are really for FP types, and aren't required to be meaningful for an integer type; I believe they still need to be implemented.
|
3,072,421 | 3,072,448 | Difference between (++i) and (i++) | In C++ I understand that (++i) should return a reference to i because the need of concatenation of operators, but what I can't figure out is:
Why (i++) should return i by value?
Can anyone please clarify.
| ++i can be written as
prefix_inc (this) {
increase this by 1
return this
}
Since the real i is returned, we can take reference of it. However, i++ looks like
postfix_inc (this) {
set old_this = copy of this
increase this by 1
return old_this
}
as old_this is just a local variable, the reference of it is pointless after i++ is completed. So logically it should return an rvalue.
|
3,072,444 | 3,072,551 | Long long int on 32 bit machines | very simple question, I read that GCC supports long long int type. But how can make math operations with it, when CPU is 32 bit wide only?
| The compiler will synthesize math operations (or use function calls) that use more than one CPU instruction to perform the operation. For example, an add operation will add the low order components (the low words) of the long long values and will then take the carry out of that operation and feed it into an add operation on the high order words of the long long.
So the following C code:
long long a;
long long b;
long long c;
// ...
c = a + b;
might be represented by an instruction sequence that looks something like:
mov eax, [a.low] ; add the low order words
add eax, [b.low]
mov edx, [a.high] ; add the high order words,
adc edx, [b.high] ; including the carry
mov [c.low], eax
mov [c.high], edx
And if you consider for a moment, compilers for 8 and 16 bits systems had to do this type of thing for 16 and/or 32-bit values long before long long came into being.
|
3,072,464 | 3,072,604 | Displaying Unicode/ASCII Characters on console or window | I couldn't display a 'bullet' of character code DEC 149 which can be found on ASCII Chart.
cout << char(149) << endl;
it comes out as ò on console window. I know a few characters from charmap that I'd like to use but how would i know their character codes?
| The problem is that ASCII only defines character codes 0 through 127. If you want to use codes above that, then you need to specify an ANSI code page. The chart you referenced is using the Latin-1 code page and your console is apparently using something else.
You need to set your console code page to Latin-1 for your characters to display as desired. There's no standard C++ way to do this. If you're programming on Windows, you can use the SetConsoleOutputCP() function. The code page id for Latin-1 on Windows is 1252.
|
3,072,795 | 3,072,840 | How to count lines of a file in C++? | How can I count lines using the standard classes, fstream and ifstream?
| How about this :-
std::ifstream inFile("file");
std::count(std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>(), '\n');
|
3,072,912 | 3,073,041 | boost::this_thread::sleep() vs. nanosleep()? | I recently came across the need to sleep the current thread for an exact period of time. I know of two methods of doing so on a POSIX platform: using nanosleep() or using boost::this_thread::sleep().
Out of curiosity more than anything else, I was wondering what the differences are between the two approaches. Is there any difference in precision, and is there any reason not to use the Boost approach?
nanosleep() approach:
#include <time.h>
...
struct timespec sleepTime;
struct timespec returnTime;
sleepTime.tv_sec = 0;
sleepTime.tv_nsec = 1000;
nanosleep(&sleepTime, &returnTime);
Boost approach:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
...
boost::this_thread::sleep(boost::posix_time::nanoseconds(1000));
| The few reasons why use boost that I can think of:
boost::this_thread::sleep() is an
interruption point in boost.thread
boost::this_thread::sleep() can be
drop-in replaced by C++0x's
std::this_thread::sleep_until() in
future
For why not -- if you're not using threads at all, or of everything else in your project uses POSIX calls, then nanosleep() makes more sense.
As for precision, on my system both boost and nanosleep() call the same system call, hrtimer_nanosleep(). I imagine boost authors try to get the highest precision possible on each system and for me it happens to be the same thing as what nanosleep() provides.
|
3,073,303 | 3,073,311 | Have to use C# dll to call C++ dll? | Do I have to create a C# DLL to call C++ DLL or I can call it directly from my C# application?
| You can call it directly with PInvoke and the DllImport attribute. Assuming, of course, that it has standard C entry points, not compiler-specific C++ entry points.
Unless you were talking about C++/CLI, in which case you would reference the .NET DLL exactly as you would reference any other .NET DLL.
|
3,073,418 | 3,073,456 | Capture stdin input without echoing characters to screen | I have a very simple code:
char character;
std::cin >> character;
However, I would like it to behave as follow:
Don't echo to console the character I type
std::cin should return (unblock) right away when a character is pressed without having to press the Enter key
Is this possible? I also have access to Qt.
| This is going to be platform dependent, but you can use
getch() which is part of conio.h if you're on windows
or
getch() as part of curses.h if you're on *nix
References
http://opengroup.org/onlinepubs/007908799/xcurses/curses.h.html
http://en.wikipedia.org/wiki/Conio.h
|
3,073,466 | 3,073,494 | Dynamic creating of typedef | I'm creating event system. It's based under boost::signals. To make the work easier I'm using typedef for the function signatures.
Everything is okey until I need creating of some new event trought event's system method. I have to create the typedef dynamically on given type to the template function. The problem is the name of typedef.
Some pseudocode I would have:
template<typename EventType>
void create(const string &signalName)
{
typedef EventType signalName;
// ...
}
Is it possible to make such typedef (their names) with some passed string or data or something else? I don't want to make user care about of this.
UPD: So, I have some typedefs list of function signatures - events. I have some templated function for connecting slots, for example. I don't want to force user to input signature by his hands again every time (user is programmer which will use the event system). So I just use my typedefs from special namespace into template argument.
| typedefs only matter during compilation. As far as I know it's just an alias for a type.
|
3,073,563 | 3,088,126 | Creating an Ctablctrl on a CFrameWnd | I want to create a mfc window that has tabs on top.
I cannot find a good tutorial or example of this.
Can someone give me a link to a good tutorial of example?
please help me.
| Install the Visual C++ Feature Pack. It comes with newer libraries to do this.
|
3,073,642 | 3,073,656 | Official C++ language subsets | I mainly use C++ to do scientific computing, and lately I've been restricting myself to a very C-like subset of C++ features; namely, no classes/inheritance except complex and STL, templates only used for find/replace kinds of substitutions, and a few other things I can't put in words off the top of my head. I am wondering if there are any official or well-documented subsets of the C++ language that I could look at for reference (as well as rationale) when I go about picking and choosing which features to use.
| There is Embedded C++. It sounds mostly similar to what you're looking for.
|
3,073,753 | 3,073,810 | How can I extract the domain from a URL? | I'm currently making a few changes in the rTorrent source. I have the following code:
torrent::Object
apply_to_domain(const torrent::Object& rawArgs) {
const char * url = rawArgs.as_string().c_str();
char buffer[50];
snprintf(buffer, 50, "URL: %s.", url);
return std::string(buffer);
}
I need to extract the domain from url. There's a regex.h included in the source but I'm not sure if I can use that or if I need to use a different regex library.
Link to regex.h
| The only thing that "regex" implementation handles is the wildcard character, *. (BTW, I'm just assuming it's a wildcard, since it's the only character that's recognised and the comments seem to hint as much, but I haven't actually verified it.)
Use a proper regex library like Boost.Regex.
|
3,073,844 | 3,073,879 | Horizontal mouse wheel event? (WinAPI) | Some laptops have a trackpad that can do horizontal scrolling as well as vertical (WM_MOUSEWHEEL), and some desktop mice have ability to tilt their wheels.
How can I handle horizontal scrolling from a trackpad or mouse wheel?
| WM_MOUSEHWHEEL is sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated, and is also useful for horizontal scrolling from a trackpad's horizontal scrolling control
|
3,073,965 | 3,074,042 | Specifying test dependencies in CppUnit? | I would like to specify the order of testing in CppUnit. According to my research, the testing order depends on either the compiler or linker and how they came across the files.
How does one specify dependencies in CppUnit?
For example, let us consider a rectangle class that has four lines. Each line contains two point classes. Assume that each class is in a separate module or translation unit.
struct Point
{
int x;
int y;
};
struct Line
{
Point a;
Point b;
};
struct Rectangle
{
Line top;
Line left;
Line right;
Line bottom;
};
In the above code, the Point class should be tested first, then the Line class and finally the Rectangle class. There is no reason to test the Rectangle class if the Line or Point classes have problems. This is a very simplified example.
For composite classes, the inner classes or member data type classes should be test first.
Let us assume that each class has an associated testing class. Each test class has its own published test methods (which are registered to the CppUnit list), in separate files. The class for testing Lines has no knowledge of the testing class for points; and similar for the rectangle. When these test case classes are compiled, their order is dependent on the compiler and linker.
So, how does one order the test cases?
FYI, I am using CppUnit, wxTestRunner and Visual Studio 2008
| What you're trying to do isn't really unit testing. "Pure" unit testing is intended to test individual units (individual classes), using mocks or fake objects in the place of real dependencies; once you're testing classes' dependencies on each other, that's integration testing, not unit testing.
With that disclaimer out of the way...
It looks like you might be able to use CPPUNIT_TEST_SUITE_NAMED_REGISTRATION to create multiple suites then run each suite in order, only if all previous suites have passed, but you might need to hack up or replace wxTestRunner test runner to do this.
CppUnit's page on Creating TestSuite has other options for registering test suites; CPPUNIT_REGISTRY_ADD, for example, lets you create a hierarchy of suites, which should give you some control over the ordering, but I don't see any way for a failure in one suite to abort subsequent tests.
Finally, just as a suggestion, CppUnit is probably not the best C++ unit testing framework these days. I'm personally a fan of Google Test, but Boost.Test and UnitTest++ are also good. (This answer introduces a personal project called Saru that sounds like it might give you the flexibility you want of ordering tests.)
|
3,074,202 | 3,078,208 | Can read(2) return zero when not at EOF? | According to the man page for read(2), it only returns zero when EOF is reached.
However, It appears this is incorrect and that it may sometimes return zero, perhaps because the file is not ready to be read yet? Should I call select() to see if it is ready before reading a file from disk?
Note that nBytes is: 1,445,888
Some sample code:
fd_set readFdSet;
timeval timeOutTv;
timeOutTv.tv_sec = 0;
timeOutTv.tv_usec = 0;
// Let's see if we'll block on the read.
FD_ZERO(&readFdSet);
FD_SET(fd, &readFdSet);
int selectReturn = ::select(fd + 1, &readFdSet, NULL, NULL, &timeOutTv);
if (selectReturn == 0) {
// There is still more to read.
return false; // But return early.
} else if (selectReturn < 0) {
clog << "Error: select failure: " << strerror(errno) << endl;
abort();
} else {
assert(FD_ISSET(fd, &readFdSet));
try {
const int bufferSizeAvailable = _bufferSize - _availableIn;
if (_availableIn) {
assert(_availableIn <= _bufferSize);
memmove(_buffer, _buffer + bufferSizeAvailable, _availableIn);
}
ssize_t got = ::read(fd, _buffer + _availableIn, bufferSizeAvailable);
clog << " available: " << bufferSizeAvailable << " availableIn: "
<< _availableIn << " bufferSize: " << _bufferSize << " got "
<< got << endl;
return got == 0;
} catch (Err &err) {
err.append("During load from file.");
throw;
}
}
The output reads (when it fails with no data read):
available: 1445888 availableIn: 0 bufferSize: 1445888 got: 0
This is running on centos4 32 bit as a virtual machine using VMware Server 1.0.10. The file system being read is local to the virtual machine. The host machine is windows server 2008 32 bit.
The uname -a says:
Linux q-centos4x32 2.6.9-89.0.25.ELsmp #1 SMP Thu May 6 12:28:03 EDT 2010 i686 i686 i386 GNU/Linux
I notice that the link http://opengroup.org/onlinepubs/007908775/xsh/read.html given below states:
The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal...
If a read() is interrupted by a signal before it reads any data, it will return -1 with errno set to [EINTR].
If a read() is interrupted by a signal after it has successfully read some data, it will return the number of bytes read.
So, perhaps I am getting a signal interrupting the read and thus the value returned is zero because of either a bug or it thinks zero bytes were read?
| Figured it out! I had an Uninitialized Memory Read (UMR) and was incorrectly seeking to the end of the file.
|
3,074,290 | 3,074,319 | How do I get the regex matched value using Boost.Regex? | I'm trying to extract the domain from a URL. Following is an example script.
#include <iostream>
#include <string>
#include <boost/regex.hpp>
int main () {
std::string url = "http://mydomain.com/randompage.php";
boost::regex exp("^https?://([^/]*?)/");
std::cout << regex_search(url,exp);
}
How do I print the matched value?
| You need to use the overload of regex_search that takes a match_results object. In your case:
#include <iostream>
#include <string>
#include <boost/regex.hpp>
int main () {
std::string url = "http://mydomain.com/randompage.php";
boost::regex exp("^https?://([^/]*?)/");
boost::smatch match;
if (boost::regex_search(url, match, exp))
{
std::cout << std::string(match[1].first, match[1].second);
}
}
Edit: Corrected begin, end ==> first, second
|
3,074,376 | 3,076,489 | How to fix file path case? | I have a set of local paths, and some of them are capitalized (C:\SOMEDIR\SOMEFILE.TXT). I need to convert them to their real names (as shown in Explorer). Suggest a way plz.
| Are you looking for that: short names vs. long name?
Note that Explorer applies some tricky conversions to the file names. You easiest shot is to test it all and make your own function for the purpose.
Otherwise, you can try to access via OLE the Explorer's functions to list files in directory. But that is VERY painful and error prone to code. (Why I guess MS has given up in the end and provided the functions I have linked to above in Win2K).
|
3,074,416 | 3,074,421 | Is g++ on cygwin any different from what I get on Linux platform? | Can I start installing boost libraries, ACE framework and use it as my home Linux server?
| The G++ on Cygwin is very similar to that on any other platform. You should be able to use it with Boost if you can't find the Boost libraries you want pre-compiled for Cygwin.
However, Cygwin is not Linux; you won't be able to use it as your 'home Linux server'. Cygwin gives a Linux-like interface to Windows, but it is still running on Windows, not Linux.
|
3,074,456 | 3,074,479 | Collision detection in STL's hash_map | I have to create a lookup table for C function names (as keys) to function pointers (as values). I am thinking of using STL's hash_map container, as the access time of a hash table is O(1). Is there any good hash function for this? Currently I am using (31*H + c) as my hash function.
Also, does STL's hash_map takes care of collisions, or I have to take care of them in my code? Please give some examples if possible.
Sample Code I am currently working upon
#include <iostream>
#include <ext/hash_map>;
using namespace std;
using namespace __gnu_cxx;
namespace __gnu_cxx {
#ifndef __HASH_STRING__
#define __HASH_STRING__
template <>
struct hash<string> {
size_t operator() (const std::string& s) const
{
size_t h = 0;
std::string::const_iterator p, p_end;
for(p = s.begin(), p_end = s.end(); p != p_end; ++p)
{
h = 31 * h + (*p);
}
return h;
}
};
#endif
};
int main()
{
hash_map<string, int> months;
months["january"] = 1;
months["february"] = 2;
months["march"] = 3;
months["april"] = 4;
months["may"] = 5;
months["june"] = 6;
months["july"] = 7;
months["august"] = 8;
months["september"] = 9;
months["october"] = 10;
months["november"] = 11;
months["december"] = 12;
return 0;
}
| Assuming you've got the full STL, it actually includes a hash function, hash<T>, which in its included form is suitable for a few different key types including char* (C strings). I don't know details of its performance, but the STL is generally engineered to have acceptable performance for most applications.
As for collisions, that's for hash_map to deal with, you needn't worry about it.
|
3,074,518 | 3,074,542 | Why am I able to create a copy constructor and overload the assignment operator for a QObject subclass? | I was under the impression that QObject disabled the copy constructor and assignment operator... why am I able to compile this QObject derivative containing both of these?
#ifndef QVERSION_H
#define QVERSION_H
#include "silverlocklib_global.h"
#include <QtCore>
struct SILVERLOCKLIBSHARED_EXPORT QVersion : public QObject
{
Q_OBJECT
Q_PROPERTY(bool valid READ isValid)
Q_PROPERTY(long major READ major)
Q_PROPERTY(long minor READ minor)
Q_PROPERTY(long build READ build)
Q_PROPERTY(long revision READ revision)
public:
QVersion(long major = 0, long minor = 0, long build = -1, long revision = -1, QObject *parent = NULL);
QVersion(const QString &version, QObject *parent = NULL);
QVersion(const QVersion &version);
static QVersion parse(const QString& version, bool *ok = NULL);
bool isValid() const;
long compareTo(const QVersion &other) const;
bool equals(const QVersion &other) const;
QString toString() const;
QString toString(int fieldCount) const;
long major() const;
inline int majorRevision() const { return (qint16)(this->m_revision >> 16); }
long minor() const;
inline int minorRevision() const { return (qint16)(this->m_revision & 65535); }
long build() const;
long revision() const;
QVersion& operator=(const QVersion &version);
friend bool operator==(const QVersion &v1, const QVersion &v2);
friend bool operator!=(const QVersion &v1, const QVersion &v2);
friend bool operator<(const QVersion &v1, const QVersion &v2);
friend bool operator<=(const QVersion &v1, const QVersion &v2);
friend bool operator>(const QVersion &v1, const QVersion &v2);
friend bool operator>=(const QVersion &v1, const QVersion &v2);
private:
inline static void copy(QVersion *const destination, const QVersion &source);
static bool tryParseComponent(const QString &component, long *parsedComponent);
long m_major;
long m_minor;
long m_build;
long m_revision;
};
#endif // QVERSION_H
| A derived class can always declare it's own copy constructor and assignment operator. If the base class disables it by making it private and leaving it undefined the derived class can't call the base class' version in its own implementation of course, but it can still implement them.
|
3,074,643 | 3,074,649 | What is the difference between pointer to function and pointer to WINAPI function? | I came accross a code snippet which detects whether app is running in x32 emulated environment on x64 PC here
Generally I understand that code but there is one thing I don't get:
1) typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
Why does WINAPI have to be there? Why is it so important to know that pointer doesn't point to my-defined function but to WINAPI one? Would these 2 pointers be different? (in way of size, place they are created etc.)
Thanks,
Kra
| WINAPI expands to __stdcall (in most cases -- you shouldn't rely on that calling convention specifically), which is a different calling convention than the default, __cdecl. The difference is that in __stdcall, the function called cleans the stack, while in __cdecl, the caller cleans the stack. __stdcall does not support varadic (Variable argument length) functions like __cdecl does, but __stdcall can be faster and reduce code size in some cases.
|
3,074,646 | 3,074,654 | how to catch unknown exception and print it | I have some program and everytime I run it, it throws exception and I don't know how to check what exactly it throws, so my question is, is it possible to catch exception and print it (I found rows which throws exception) thanks in advance
| If it derives from std::exception you can catch by reference:
try
{
// code that could cause exception
}
catch (const std::exception &exc)
{
// catch anything thrown within try block that derives from std::exception
std::cerr << exc.what();
}
But if the exception is some class that has is not derived from std::exception, you will have to know ahead of time it's type (i.e. should you catch std::string or some_library_exception_base).
You can do a catch all:
try
{
}
catch (...)
{
}
but then you can't do anything with the exception.
|
3,074,738 | 3,074,777 | Algorithms in C++ by Robert Sedgewick experiences | How good is this book for learning algorithm creation, based on experiences ?
| Its a good book but this does not mean it is good for you - maybe you find it at google books so you can have a look in it.
|
3,074,776 | 3,074,785 | how to convert char array to wchar_t array? | char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);
I cannot use cmd in
sei.lpFile = cmad;
so,
how to convert char array to wchar_t array ?
| From MSDN:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
using namespace System;
int main()
{
char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;
// Convert to a wchar_t*
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
}
|
3,074,872 | 3,074,981 | typedef and incomplete type | Recently I am having many problem with typedef and incomplete type when I changed certain containers, allocators in my code.
What I had previously
struct foo;//incomplete type.
typedef std::vector<foo> all_foos;
typedef all_foos::reference foo_ref;
Though not completely not sure whether the above lines are legal, but this worked on every implementation I used. When I thought that I can do the job with std::tr1::array, changed the above two lines with
typedef std::tr1::array<foo,5> all_foos;
typedef all_foos::reference foo_ref;
Here everything breaks, as the compiler tries to instantiate array and fails as foo is incomplete type. What all I needed is a reference to foo, and not much interested on 'other parts' of the array. foo will definitely be completely available when I create such an array.
The same is problem when typedef std::allocator<foo>::pointer foo_ptr got replaced by typedef stack_alloc<foo,10>::pointer foo_ptr. where a stack_alloc implementation is like
template<typename T,unsigned N>
struct stack_alloc
{
typedef T* pointer;
typedef std::tr1::aligned_storage<sizeof(T)*N, std::tr1::alignment_of<T>::value> buffer;
};
Presuming that, value_type, pointer, reference, iterator etc does not depend on the completeness of T, and knowing that the class can not be instantiate without complete type, how such typedef can be made in generic way independent of specific container or allocator?
NOTE:
Just for completeness, in 'real' code I use a small local memory with vector rather than replacing it with std::array, though the problem remains same.
stack_alloc code is far from complete, and only shows the part of the problem.
I know that array, sizeof etc needs complete type available. But I am NOT creating object of type all_foos with incomplete foo.
My assertion is that pointer,reference etc should not depend on completeness of a type. Otherwise construct like struct foo{ foo_ptr p;}; can not be defined. Though probably foo_ref can not be anything other than foo&, but foo_ptr can be. Surprisingly GCC implementation doesn't have nested pointer type for tr1::array.
Know mostly what can not be done, and interested to know what can be done in this situation. So expecting a good design as a solution.
| A type must be complete to be used in a standard container, or the behavior is undefined (§17.4.3.6/2). So the only standard solution is to not make that typedef until the class is defined.
I don't get what the intermediate container is for:
struct foo;//incomplete type.
typedef foo& foo_ref;
In any case, you'll just have to have the complete type defined first, really. To get a typedef defined in a class, that class must be instantiated, which means the entire thing must be able to use T as desired.
For example, stack_alloc must have T be a complete type (for sizeof(T) to work), otherwise the class cannot be instantiated. If the class can't be instantiated, you cannot get the typedef out of it. Ergo, you'll never get the typedef out of it if T is incomplete.
|
3,075,049 | 3,075,077 | Why do compilers allow string literals not to be const? | And where are literals in memory exactly? (see examples below)
I cannot modify a literal, so it would supposedly be a const char*, although the compiler let me use a char* for it, I have no warnings even with most of the compiler flags.
Whereas an implicit cast of a const char* type to a char* type gives me a warning, see below (tested on GCC, but it behaves similarly on VC++2010).
Also, if I modify the value of a const char (with a trick below where GCC would better give me a warning for), it gives no error and I can even modify and display it on GCC (even though I guess it is still an undefined behavior, I wonder why it did not do the same with the literal). That is why I am asking where those literal are stored, and where are more common const supposedly stored?
const char* a = "test";
char* b = a; /* warning: initialization discards qualifiers
from pointer target type (on gcc), error on VC++2k10 */
char *c = "test"; // no compile errors
c[0] = 'p'; /* bus error when execution (we are not supposed to
modify const anyway, so why can I and with no errors? And where is the
literal stored for I have a "bus error"?
I have 'access violation writing' on VC++2010 */
const char d = 'a';
*(char*)&d = 'b'; // no warnings (why not?)
printf("%c", d); /* displays 'b' (why doesn't it do the same
behavior as modifying a literal? It displays 'a' on VC++2010 */
| The C standard does not forbid the modification of string literals. It just says that the behaviour is undefined if the attempt is made. According to the C99 rationale, there were people in the committee who wanted string literals to be modifiable, so the standard does not explicitly forbid it.
Note that the situation is different in C++. In C++, string literals are arrays of const char. However, C++ allows conversions from const char * to char *. That feature has been deprecated, though.
|
3,075,208 | 3,075,214 | Calling base class method from derived constructor | class Base {
public:
Base() {}
void Foo(int x) {...}
};
class Derived : public Base {
public:
Derived(int args) {
/* process args in some way */
Foo(result);
}
};
Is it allowed to call a method of the base class in the constructor of the derived class?
I would imagine this is fine as the Base object should be fully constructed, but I wanted to check just in case.
|
Is it allowed to call a method of the base class in the constructor of the derived class?
Yes. Just watch out for virtual functions. If an class derived from Derived overrides a virtual function, while constructing Derived as a sub-object of that further derived class, the dynamic type always is Derived, so no virtual functions overridden in further derived classes are called. (The same goes for the destructor, BTW.)
I would imagine this is fine as the Base object should be fully constructed, but I wanted to check just in case.
Your reasoning is right.
|
3,075,335 | 3,075,359 | Creating effects in 3D game from scratch, using c++ and DirectX | So the title says it. I couldn't find any info on how actualy build effects into 3D game. I'll maybe stick to some engine later, but for understanding of this whole thing I would need to try it on my own for this time. I found a few about particle systems which may be the right way but any other connection between DirectX and particle systems on google gave results as 3DSmax and etc.
So I would be thankful if you would point me on some tutorials for this, or explaining it...
Last possibilitie would be pointing me on some simple engine focused on this thing (I don't really want to fight through tons of code and understanding how this engine works, I just need to see how they implement this FX stuff).
Thanks
PS: the other possibilitie would be if you know about good book discusing this. It can be more complex but apart from tutorial, books are usually wrote more basicly so this would be also nice way to go
| First of all: particle effects are just one kind of effects, it's better you specify the word particle engine :p.
Secondly: search int he articles of Gamedev, it's really the best resource if you want things like this. You can find lots of articles and even better, tons of links, and useful information on the discussion boards. Two articles I can link to is the NeHe lesson about particles in OpenGL, it's not directx but NeHe tutorials for OpenGL are very good. I also found one for directx8 and VB (so a little bit older).
Keep in mind though that a particle engine is often a huge performance hit if you can't optimize it yourself, so try to look at open source game engines (e.g. OGRE) on how they implement it or even better, specific particle engines.
|
3,075,494 | 3,075,528 | How to ensure class template argument is derived from particular class Foo? |
Possible Duplicate:
C++ class template of specific baseclass
class Base
{
...
};
class Derived1 : public Base
{
...
};
class Derived2 : public Base
{
...
};
class Unrelated
{
...
};
I want to have a class template ClassTemplate that accepts as parameter only classes Derived1 and Derived2 but not Unrelated, so I can do:
ClassTemplate<Derived1> object1;
ClassTemplate<Derived2> object2;
but I shouldn't do:
ClassTemplate<Unrelated> object3;
Is it possible at all?
| Use boost::is_base_of from Boost.TypeTraits:
template<class T> class ClassTemplate {
BOOST_STATIC_ASSERT((boost::is_base_of<Base, T>::value));
};
|
3,075,601 | 3,075,661 | pointers to derived members of the class | if I have for example some class Base and derived from it Derived
Also I have some list of shared pointers:
list<shared_ptr<Base> > list
I create shared pointer:
line 5 shared_ptr<Derived> ptr(new Derived(//some constructor));
my question is, can I do something like this:
list.push_back(ptr);
if Yes, can somebody explain why can I recieve an error (I receive this on the line 5)
no matching function for call to //here It writes me my constructor to Derived
thanks in advance for any help
|
my question is, can I do something like this: list.push_back(ptr);
Yes - your problem has nothing to do with inheritance or smart pointers - you simply don't have the constructor declared you are trying to use.
A simple example that reproduces the error is:
struct X {};
X x(1);
Which gives you:
no matching function for call to 'X::X(int)'
You fix that by either constructing the instance differently or by adding the missing constructor:
struct X { X(int) {} };
|
3,075,697 | 3,859,694 | "non-existent member function specified as friend" -? | I'm trying to compile CSSTidy with Visual Studio.
The problem is that it throws
error C2245: non-existent member function 'umap::erase' specified as friend (member function signature does not match any overload)
pointing to the
friend void umap<keyT,valT>::erase(const typename umap<keyT,valT>::iterator& it);
which is a declaration in iterator class declared in umap class.
Can anybody tell me where should I digg into to figure out what the problem really is? AFAIK the source compiles in MinGW ...
| The fix, forward declare "class iterator;" at the top of class umap, and move the impl of "class iterator" to the bottom of class umap. The reason, MickySoft VS appears to have a deficiency that causes it not recognize umap::erase declared below the impl of umap::iterator.
template <class keyT, class valT>
class umap
{
typedef map<keyT,valT> StoreT;
typedef std::vector<typename StoreT::iterator> FifoT;
private:
FifoT sortv;
StoreT content;
public:
class iterator;
[...snip...]
void erase(const typename umap<keyT,valT>::iterator& it)
{
content.erase(*it.pos);
sortv.erase(it.pos);
}
[...snip...]
// Iterator
class iterator
{
[...snip...]
}};
|
3,076,075 | 3,076,169 | How to compile code generated by a Java or C++ App | I've been learning compiler theory and assembly and have managed to create a compiler that generates x86 assembly code.
How can I take this assembly code and turn it into a .exe? Is there some magical API or tool I have to interact with? Or is it simpler than I think?
I'm not really sure what's in a .exe, or how much abstraction lies between assembly code and the .exe itself.
My 'compiler' was written in Java, but I'd like to know how to do this in C++ as well.
Note that if I take the generated assembly, it compiles to a .exe just fine for example with vc++.
Edit: To be more precise, I already know how to compile assembly code using a compiler. What I'm wanting is to have my program to basically output a .exe.
| It looks like you need to spawn an assembler process and a linker process. On UNIX, it's as simple as invoking the fork() function, which would create a new process, and the exec() function, specifying the assembler and the linker executable names as the function's parameter, with suitable arguments to those executables, which would be the names of your generated assembly and object files. That's all you'd need to do on a UNIX system.
|
3,076,163 | 3,076,722 | STL Priority Queue - deleting an item | I want to implement a timer queuing system using the C++ STL priority_queue container adapter.
My problem is that I want to occasionally cancel a timer, however there are no interfaces that enable me to easily delete an item in the priority_queue that is not the top item.
Any suggestions?.
Thank you for your help.
| I had the exact same scenario once and did the following:
the structure I kept in std::priority_queue contained only the time to sort by and an index to a std::vector<Handler> (in my case Handler was boost::function, but could as well be pointer to interface or function)
when adding a timer, I'd find a free index in the vector of handlers1 and store the handler at that index. Store the index and the time in the priority_queue. Return the index to the client as token to cancel
to cancel a timer, pass the index received when adding it. Clear the handler at that index (for boost::function call clear(), if using pointers, set it to zero)
when it's time to callback a timer, get its handler index from the priority queue and check the handlers vector - if the handler at that position is empty()/NULL, the timer has been canceled. Mark that handler index as free2.
1 To make finding a free index fast, I used a separate std::stack of indices. When adding a timer and that stack is empty, add at the end of vector; otherwise pop the top index and use it.
2 Here's the point when you push the index to the free indices stack
The whole thing is somewhat tricky and error-prone, especially if your timer callbacks need to add or cancel timers. Here's a link to my canceling timer class described above, this code is public domain
|
3,076,206 | 3,077,033 | enable_if and conversion operator? | Any chance to use enable_if with a type conversion operator? Seems tricky, since both return type and parameters list are implicit.
| dixit the documentation:
There does not seem to be a way to specify an enabler for a conversion operator. Converting constructors, however, can have enablers as extra default arguments.
|
3,076,243 | 3,076,261 | problems with dynamic_cast | I have this snippet of the code:
void addLineRelative(LineNumber number, LineNumber relativeNumber) {
list<shared_ptr<Line> >::iterator i;
findLine(i, number);
if(i == listOfLines.end()){
throw "LineDoesNotExist";
}
line 15 if(dynamic_cast<shared_ptr<FamilyLine> >(*i)){
cout << "Family Line";
} else {
throw "Not A Family Line";
}
}
I have class Line and derived from it FamilyLine and RegularLine, so I want find FamilyLine
my program fails on the line 15, I receive an error
cannot dynamic_cast target is not pointer or reference
can somebody please help, thanks in advance
edited
I tried this one:
shared_ptr<FamilyLine> ptr(dynamic_cast<shared_ptr<FamilyLine> >(*i));
if(ptr){
//do stuff
}
the same error
edited
void addLineRelative(LineNumber number, LineNumber relativeNumber) {
list<shared_ptr<Line> >::iterator i;
findLine(i, number);
if(i == listOfLines.end()){
throw "LineDoesNotExist";
}
shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
if (ptr){
cout << "Family Line";
} else {
throw "Not A Family Line";
}
}
receive this error
Multiple markers at this line
- `dynamic_pointer_cast' was not declared in this
scope
- unused variable 'dynamic_pointer_cast'
- expected primary-expression before '>' token
| shared_ptr does not implicitly convert to a pointer - it is a class-type object - and dynamic_cast, static_cast and const_cast all operate on pointers only.
While you could use dynamic_cast on shared_ptr<T>::get(), its better to use dynamic_pointer_cast<FamilyLine>() instead as you might otherwise accidentally introduce double-deletes:
Returns:
* When dynamic_cast<T*>(r.get()) returns a nonzero value, a shared_ptr<T> object that stores a copy of it and shares ownership with r;
* Otherwise, an empty shared_ptr<T> object.
[...]
Notes: the seemingly equivalent expression
shared_ptr<T>(dynamic_cast<T*>(r.get()))
will eventually result in undefined behavior, attempting to delete the same object twice.
E.g.:
shared_ptr<FamilyLine> ptr(dynamic_pointer_cast<FamilyLine>(*i));
if (ptr) {
// ... do stuff with ptr
}
|
3,076,343 | 3,076,392 | Application settings with WinAPI | Is there any standard way to work with application settings in WinAPI? What I'm doing currently is this:
if(!ReadKey(some_setting))
WriteKey(some_setting, some_setting_setting_default_value)
when the settings dialog is initialized. Then I set the widget states to the corresponding values read from the registry. The problem is that if the application is run for the first time, the default settings can't be read following the above code pattern. One more ReadKey() is necessary to read the just written default settings into the settings variable in my program. This looks a bit clumsy to me. So the question basically is:
is there any standard way to work with settings in Win32?
and, most importantly, is there any way to set up default application settings during installation, so that there would be code to set the default settings at all? (which I guess is the preferred method, as then you could modify the default application settings without rebuilding it)
Again, this should be pure Win32, no MFC allowed.
Why is this homework? This is question about whether there is an established practice of doing things, not a request to do my job for me. Now I better remove the "university project" phrase from there.
| You could avoid writing hard-coded default values to the registry, and leave the registry empty except when it contains a non-default value:
string ReadRegistry(
const string& some_setting,
const string& some_setting_default_value
)
{
//try to read user-specified setting from registry
string rc;
if (ReadKey(some_setting, rc))
{
return rc;
}
//else return hard-coded default value, not from registry
return some_setting_default_value;
}
Alternatively you can write all default values to the registry when the program is installed (before the program is run and before you try to read fro the registry).
Is there any standard way to work with settings in Win32?
No.
Is there any way to set up default application settings during installation
Yes, an installation program can write to the registry.
|
3,076,395 | 3,076,408 | does DEFINE Macro work on all platforms? | I am a newb and I am trying to better myself at good practice and design so consider this before reading the following.
I am creating a singleton class, and I have quite a few static members. Instead of calling the members every time like this...
THECLASS::member
I was thinking about using a define macro to make it shorter.
#define(THECLASS::member, shortMember);
So my question is, will that hurt for cross platforms or cross compilers.
| Your define won't work anywhere, actually. It should be:
#define shortMember THECLASS::member
And a good practice would be to not try to save keystrokes – readability is more important, and someone reading your code wants to see THECLASS::member, not shortMember, because then he knows where to look for a definition.
|
3,076,517 | 3,076,530 | Good tutorial to create Win32 toolbar? | I want to add a toolbar and know which tool was clicked. I'd also like to be able to change the toolbar's buttons' bitmap after theyve been created MSDN is fairly breif on all of this. Thanks
| You might want to check out these tutorials.
Grz, Kris.
|
3,076,968 | 3,077,027 | Converting a void* to a std::string | After perusing the web and messing around myself, I can't seem to convert a void*'s target (which is a string) to a std::string. I've tried using sprintf(buffer, "%p", *((int *)point)); as recommended by this page to get to a C string, but to no avail. And sadly, yes, I have to use a void*, as that's what SDL uses in their USEREVENT struct.
The code I'm using to fill the Userevent, for those interested, is:
std::string filename = "ResumeButton.png";
SDL_Event button_press;
button_press.type = BUTTON_PRESS;
button_press.user.data1 = &filename;
SDL_PushEvent(&button_press);
Any ideas?
EDIT: Thanks for all the responses, I just needed to cast the void* to a std::string*. Silly me. Thank you guys so much!
| You just need to dynamically allocate it (because it probably needs to outlive the scope you're using it in), then cast it back and forth:
// Cast a dynamically allocated string to 'void*'.
void *vp = static_cast<void*>(new std::string("it's easy to break stuff like this!"));
// Then, in the function that's using the UserEvent:
// Cast it back to a string pointer.
std::string *sp = static_cast<std::string*>(vp);
// You could use 'sp' directly, or this, which does a copy.
std::string s = *sp;
// Don't forget to destroy the memory that you've allocated.
delete sp;
|
3,076,975 | 3,077,001 | Weird c++ input escaping and space behavior | I'm having an unpleasant problem with my c++ example. Everything works fine until I enter something with a whitespace.
#include <iostream>
using namespace std;
int main (int argc, char * const argv[])
{
int iteration = 0;
while (true) {
char * input = new char[256];
scanf("%s", input);
cout << ++iteration << ": " << input << endl;
cin.get();
}
return 0;
}
So with this code, I can enter anything, but everything after whitespace is somehow like stored in buffer and used in the second iteration.
foo
1: foo
bar
2: bar
foobar
3: foobar
foo bar
4: foo
5: bar
Every single input reading function acts like this and it's driving me crazy. cin >> input, freads(), cin.get() etc. all do this.
It this frequent problem with user input, or am I doing something wrong here?
| First of all, never use scanf. It's difficult to use that function and avoid buffer overflows. Replace input with a std::string, and read from std::cin.
Both scanf("%s", input) and cin >> input will read one word, delimited by whitespace. If you want to read a whole line, then use getline(cin, input).
|
3,077,013 | 3,077,031 | Game Development: Should I program my levels or interpret them from a file? | The game will be written in C++
Programming:
enemies.puch_back(new DefaultEnemy(200, 300, 3, 5));
enemies.puch_back(new DefaultEnemy(500, 400, 4, 5));
enemies.puch_back(new DefaultEnemy(300, 420, 3, 15));
enemies.at(2).createAward(new Key(4), "pling.wav");
Or Interpret them from a file like this:
DefaultEnemy 200 300 3 5
DefaultEnemy 500 400 4 5
DefaultEnemy 300 420 3 15
CreateAward 2 "pling.wav" Key 4
Program it would be more easy and people can't (without speaking of hacking) edit your levels. But it maybe a bit rubbish to program it all? Are there other reasons to choose for programming or interpreting?
How about memory-management (if I should go for interpreting)?
How to delete the (game)objects when the level unloads?
| First variant is equivalent to hardcoding game resources. This is absolutely bad and is suitable only for debugging.
Every games store their resources in external files - xml, archived packages and parse and load them during runtime.
Therefore, modern game engines almost every time have their set of tools which is bundled with it.
Deleting game resources is also a vast question - it depends. Depends on your objects' lifetime management and on that fact if you need to unpack your data into temporal files.
|
3,077,135 | 3,077,138 | Type requirements for std::list | I've got a type that can't be moved or copied (by making the necessary constructors and operators private). But when I tried to compile a std::list of them, the operation failed with a very strange error (class name snipped for brevity).
1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xmemory(202)
: error C2248: 'T::T' : cannot access private member declared in class 'T'
Surely it's not incumbent of a type in a linked list to be movable or copyable.
When these members are made public, the code compiles fine- even though, if the std::list had tried to access them, it would be an unresolved external, since they're only declared private. Makes no sense :(
| As of C++03, elements must be copy constructible and copy assignable. §23.1/3:
The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.
In C++0x, requirements are put on a per-operation basis, but in general it's safe to say elements must be move constructible and move assignable. (Though some operations require copy constructibility and assign-ability, etc.)
A typical solution to your problem is to store pointers to objects, via shared_ptr or some other smart pointer.
|
3,077,184 | 3,077,190 | Derived classes and singleton | If I have two classes "A" and "B", is it OK to derive B from A and then make B a Singleton?.
Thanks for your help.
| Um, sure. Nobody is going to stop you.
If it's okay to make "some class" a singleton*, just imagine B being a new "some class". (It just happens to be derived from A.)
*Though, do you really need a singleton? (No.)
|
3,077,407 | 3,097,910 | Sharing violation on file which really should be closed | I have an application that modifies an XML file by:
(a) opening it,
(b) creating a temporary file and writing a modified version to it,
(c) closing both files, and
(d) replacing the original file with the temporary file.
When I test it on my laptop running Vista, everything works just as it should. On an embedded PC running XP Professional SP2 with a flash drive instead of a hard disk (which may or may not be relevant), it fails at step (d) with an access violation (error code 5).
If I insert code between steps (c) and (d) to verify that the files are closed, it confirms that they are; if I put in code between steps (c) and (d) to try to delete the original file, it fails with a sharing violation (code 32). If I pause the program at this point and try to delete the file from the GUI, it fails with a sharing violation. If I use systinternals "Process Explorer" at this point, it shows the application still has a handle to the file.
Here is some of the code:
// Open the file which is to be updated:
_wfopen_s(&inStream, m_fileName, L"r, ccs=UTF-8");
// Obtain a suitable temporary filename from the operating system:
TCHAR lpTempPathBuffer[MAX_PATH]; // Buffer to hold temporary file path
TCHAR szTempFileName[MAX_PATH]; // Buffer to hold temporary file name
GetTempPath(MAX_PATH, lpTempPathBuffer);
GetTempFileName(lpTempPathBuffer,
TEXT("TMP"),
0,
szTempFileName);
// Now open a temporary file to hold the updates:
errno_t err = _wfopen_s(&outStream, szTempFileName, L"w, ccs=UTF-8");
if (err == 0)
printf ("Temporary file opened successfully\r\n");
else
printf ("Temporary file not opened; error code %d\r\n", err);
Then the gubbins that modifies the file, and then ...
// Finally, we must close both files and copy the temporary file to
// overwrite the original input file:
int closerr = fclose(inStream);
if (closerr == 0)
printf("Original file closed properly\r\n");
else
printf("Original file not closed properly\r\n");
closerr = fclose(outStream);
if (closerr == 0)
printf("Temp file closed properly\r\n");
else
printf("Temp file not closed properly\r\n");
int numclosed = _fcloseall();
printf("Number of files closed = %d\r\n", numclosed);
// Should be zero, as we've already closed everything manually
if (!DeleteFile(m_fileName))
{
int err = GetLastError();
printf ("Delete file failed, error code was %d\r\n", err);
}
else
printf ("Delete file succeeded\r\n");
if (!MoveFileEx(szTempFileName, m_fileName,
MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH))
{
int err = GetLastError();
printf ("Move file failed, error code was %d\r\n", err);
}
else
printf ("Move file succeeded\r\n");
The output log shows:
"Temporary file opened successfully
Original file closed properly
Temp file closed properly
Number of files closed = 0
Delete file failed, error code was 32
Move file failed, error code was 5"
This makes no sense... Why am I getting a sharing violation on a file which the operating system insists is closed? And is there a reason why this works in Vista but not in XP?
Many thanks for any advice,
Stephen.
| It seems to be a problem with file permissions. After trying various other things which didn't work, I decided to try opening the file with read/write permissions (i.e with the "r+" attribute rather than "r"), and then overwriting the original file contents with the contents of the temporary file. This time, the "_wfopen_s" command itself failed with error code 13 ("Permission denied"), indicating that the operating system was clearly not willing to let the program tamper with this file under any circumstances.
So I guess I need to frame the question slightly differently: why, when
(a) my application works perfectly as-is in Vista, and
(b) I can freely edit the file when I am using the GUI in XP, and all the file permissions look to be set correctly, and
(c) the program that is trying to modify the file is running from a session that is 'logged in' as the file owner
...can the file not be modified by the program?
Is this a curiosity of XP, or of the fact that it's running on an embedded computer with flash memory? If it were the latter, I'd expect there to be problems when creating brand new temporary files as well, but this seems to work just fine.
I'd once again value any suggestions.
Stephen
|
3,077,428 | 3,077,484 | Have you ever crashed a debugger? | Recently I was debugging a project and the debugger (GDB 7.1) crashed all of a sudden, because of an endless recursion while trying to print a graph structure. At first I couldn't even imagine that a debugger could crash (a stable version) but it had. So it's really interesting to me, have you ever crashed a debugger?
| Yes. My coworkers and I were debugging a nasty concurrency bug.
It crashed GDB, so we ran our program under GDB under GDB and eventually found the problem.
It was so meta ;)
|
3,077,450 | 3,077,464 | Viewing data in memory window | why can't I see the variable 'x' in memory window of VS2005 while stepping the code using debugger?
int main()
{
char *c = "String"; //visible
char x = 'a'; // not visible
}
| Both are visible in the memory window. For example in the memory window in the address field type &x and then you will see the character code of the char in hex.
For example if you have:
char x = 'x';
Then in the memory window you type &x you will see the number 0x78 which is in base10 the number 120.
assert('x' == 0x78);
Characters are just numbers.
By the way maybe you're looking for the watch window (where you can type in any value or expression and have it evaluated for you) or locals window (which shows you all of the variables that are visible to the current scope).
|
3,077,634 | 3,077,681 | error when compiling c++ code with g++ | i get error of this type:
"in function ... multiple definition of ..."
"... first defined here"
"warning: size of symbol ... changed from to in "
*the code is compiled with the flags: -ansi -Wall -pedantic-errors -Werror
*STL is used
is there any explanation for that?
thank you in advance
| Explanation? The error message you quoted is already an explanation as exhaustive as it can ever get. Something (a variable) is defined more than once in the same scope. The compiler gave you the name of the offending variable. The compiler reported the error at the second definition and supplied an additional message that points out the first definition. That's everything you need to know to find the problem and then some. What more to explain here?
|
3,077,748 | 3,077,767 | is std::vector same as array[number]? |
Possible Duplicate:
Are std::vector elements guaranteed to be contiguous?
does std::vector always contain the data in sequential memory addresses as array[number]?
| For all types except bool, the standard requires the elements are contiguous in memory:
23.2.4/1 ... The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()
Do keep in mind that std::vector<bool> has special requirements and is not the same as an array of bool.
|
3,077,769 | 3,078,087 | How do I open a Open File dialog in OS X using C++? | I'm working on an application using OpenGL and C++ that parses some structured input from a file and displays it graphically. I'd like to start an Open File dialog when the application loads to allow the user to choose the file they want to have displayed. I haven't been able to find what I need on the web. Is there a way to achieve this in C++? If so, how? Thank you in advance.
| You have two choices, a quick one, and a good one:
Quick and pretty simple, use the Navigation Services framework from Carbon and NavCreateGetFileDialog(). You'll be done quick, and you'll have to learn almost nothing new, but your code won't run in 64-bit (which Apple is pushing everyone towards) and you'll have to link the Carbon framework. Navigation Services is officially removed in 64-bit, and is generally deprecated going forward (though I expect it to linger in 32-bit for quite a while).
A little more work the first time you do it (because you need to learn some Objective-C), but much more powerful and fully supported, wrap up NSOpenPanel in an Objective-C++ class and expose that to your C++. This is my Wrapping C++ pattern, just backwards. If you go this way and have trouble, drop a note and I'll try to speed up posting a blog entry on it.
|
3,077,850 | 3,077,852 | Any way to determine if class implements operator() | I'm trying to find is there's a way to check if a class is a functional because i want to write a template which uses it?
Is there an easy way to do this? Or do I just wrap things in a try/catch? Or perhaps the compiler won't even let me do it?
| If you have a function template written like:
template <typename T>
void f(T x)
{
x();
}
you will be unable to instantiate it with any type that is not callable as a function taking no arguments (e.g., a class type that overloads operator() taking no arguments is callable as a function that takes no arguments). You would get a compilation error if you tried to do so.
This is the simplest way to require the type with which a template is instantiated to have certain properties: just rely on the type having those properties when you write the template, and if the type doesn't have one of the required properties, it will be impossible to instantiate the template with that type.
|
3,078,012 | 3,078,021 | Implementing custom STL-like data structures | I have already implemented and tested the data structure and would now like to make it compatible with the collection of STL algorithms. Guidelines for implementing a custom iterator and the like. Specifically:
What is the minimum set of operations that must be supported? (e.g. ++, +=, ==, !=?)
Are there any properties of these operations that algorithms expect?
Ideally, these answers would be part of a bigger reference for implementing a STL-compatible data structure, but I'm not sure that such a document exists.
| You should consult the SGI STL documentation. It has detailed requirements for each of the STL components, including containers and iterators.
Effectively, for iterators, there are various types--input iterators, output iterators, forward iterators, bidirectional iterators, and random-access iterators. The specification for each algorithm indicates the type of iterator required.
|
3,078,019 | 3,078,057 | Why doesn't this C++ code work? | int Socket::Connect(const std::string& host, int port)
{
if(this->_connected)
throw "Socket is already connected";
// Get the IP from the string
hostent* ip = gethostbyname(host.c_str());
/*if(server == NULL)
throw strerror(WSAGetLastError());*/
// Information for WinSock.
sockaddr_in addr;
// Clear up the memory
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = *((in_addr *)ip->h_addr);
// Try and connect
if(WSAConnect(this->_socket, (sockaddr *)&addr, sizeof(addr), NULL, NULL, NULL, NULL) != 0)
throw strerror(WSAGetLastError()); // this is being thrown but not caught?
this->_connected = true;
return 0;
}
The error is
"Unknown Error"
and here is the main function
int _tmain(int argc, _TCHAR* argv[])
{
try{
Socket* socket = new Socket();
if(socket->Connect("google.com", 80) == 0)
std::cout << "[-] connected..." << endl;
std::string line = socket->RecvLine();
std::cout << line << endl;
}
catch(char* errcstr)
{
std::cout << errcstr << endl;
}
catch(int err)
{
std::cout << err << endl;
}
catch(std::string errstr)
{
std::cout << errstr << endl;
}
catch(exception ex)
{
std::cout << ex.what() << endl;
}
system("pause");
return 0;
}
So it should catch any exceptions as far as I know. How can I fix this? (There shouldn't an exception at all since it's connected to google.com and winsock is initialized etc)
UPDATE: The error is actually being thrown after WSAConnect but there shouldn't be a problem connecting and none of my catch statements are being used for some reason.
UPDATE 2: Well now it catches the error but it says "Unknown Error" which is useless to me. Why won't it connect to google?
SOLVED: thanks!
| strerror() returns a char* on windows so you need a catch(char* error)
|
3,078,053 | 3,078,086 | Trying to use STL without smart pointers - trying to avoid temporary object creation | I particularly like the simplicity of using STL containers in the straightforward way.
I have never really figured out how to get the Boost library working on my dev platforms, in fact I don't think I've even tried. I guess you could say I am just trying to delay the inevitable since Boost is clearly a helpful library that I should be using.
But my question is essentially the same as this topic: How to initialise a STL vector/list with a class without invoking the copy constructor
I have std::list<ExpensiveClass> mylist; and I just want a function that pushes a new instance into the list and calls the default constructor, rather than copying it from a temporary stack instance of it. In the other topic there was mention of move constructors. I looked them up and quite frankly it does nothing but strike fear into my heart. Two ampersands!!
Would it work if I just made an array of ExpensiveClass objects? ExpensiveClass *mylist = new ExpensiveClass[20]; Does this call the constructor 20 times?
Seems to me I should just use boost:ptr_list.
| Inserting an object into a container invokes the copy constructor on that object. There's really no way around that (yet), hence why pointer containers are used for large objects: it's dirt cheap to copy a pointer.
If you choose to use a container of smart pointers, you can either use one of the Boost pointer containers or you can use an STL container of shared_ptrs.
To answer your question about:
ExpensiveClass *mylist = new ExpensiveClass[20];
The default constructor for ExpensiveClass is called 20 times: once for each element of the array.
|
3,078,077 | 3,078,784 | How to iterate through a sequence of bounded types with Boost.Variant | struct A
{
std::string get_string();
};
struct B
{
int value;
};
typedef boost::variant<A,B> var_types;
std::vector<var_types> v;
A a;
B b;
v.push_back(a);
v.push_back(b);
How can I iterate iterate through the elements of v to get access to the a and b objects ?
I'm able to do it with boost::get but the syntax is really cumbersome.:
std::vector<var_types>:: it = v.begin();
while(it != v.end())
{
if(A* temp_object = boost::get<A>(&(*it)))
std::cout << temp_object->get_string();
++it;
}
I've tried to use the visitation technique but I didn't get too far and the code is not working :
template<typename Type>
class get_object
: public boost::static_visitor<Type>
{
public:
Type operator()(Type & i) const
{
return i;
}
};
...
while(it != v.end())
{
A temp_object = boost::apply_visitor(get_object<A>(),*it);
++it;
}
EDIT 1
A hackish solution is :
class get_object
: public boost::static_visitor<A>
{
public:
A operator()(const A & i) const
{
return i;
}
A operator()(const B& i) const
{
return A();
}
};
| Edit:
If it's as UncleBens suggests, then you can simply do this:
BOOST_FOREACH(var_types& vt, v) {
if (vt.which() == 0)
cout << get<A>(vt).get_string() << endl;
}
Original:
The template parameter for static_vistor is the return type of its methods. This means the two classes need to share a common return type for a single visitor. It should look something like this:
class ABVisitor : public static_visitor<string> {
public:
string operator()(const A& a) const {
return a.get_string();
}
string operator()(const B& b) const {
return lexical_cast<string>(b.value);
}
};
Here's an example of iteration using this visitor.
BOOST_FOREACH(var_types& vt, v)
cout << apply_visitor(ABVisitor(), vt) << endl;
|
3,078,148 | 3,078,303 | Controlling output of program | I'm writing a code to output fibonacci series in C++, which is simple enough, but since I'm new to programming, I'm considering ways to control
I was wondering if there's a way to control time for when outputs come out without processing time being included (e.g. If it takes .0005 seconds to process my input and I want it to repeat the output in 1 second rather than 1.0005 seconds).
I also am wondering if there's a way to just have it output (say 1) and then have it wait for me to press enter, which will make it output the second part (2).
Also, I'd appreciate any other suggestions on how to control output.
| If you're on Windows, a quick way to pause is to call system("pause"); This isn't a very professional way of doing things, however.
A way to pause with the std namespace would be something like this:
cout << "Press Enter to continue . . ." << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
As for your main question... If you're just dealing with text output to the user, it's not possible for them to notice a five microsecond delay. They can notice if your interval lengths fluctuate by tens of milliseconds, however. This is why sleep(..) functions sometimes fail.
Let's take your example of wanting to output another number in the Fibonacci sequence once per second. This will work just fine:
#include <ctime>
#include <limits>
#include <iostream>
void pause() {
std::cout << "Press Enter to continue . . ." << std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
int main() {
clock_t next = clock();
int prev1, prev2, cur = 0;
for (int i = 0; i < 47; ++i) {
if (i < 2) cur = i;
else cur = prev1 + prev2;
prev2 = prev1;
prev1 = cur;
while (next > clock());
std::cout << (i+1) << ": " << cur << std::endl;
next += CLOCKS_PER_SEC;
}
pause();
return 0;
}
The next number in the sequence is computed and ready to print prior to the wait, thus the computation time will not add any delay to the timed output.
If you want your program to continue outputting at a fixed rate while your program works in the background, you'll need to look into threads. You can have your results added to a queue in one thread, while another thread checks for results to print once per second.
|
3,078,162 | 3,078,206 | Parsing a grammar with Boost Spirit | I am trying to parse a C-function like tree expressions like the following (using the Spirit Parser Framework):
F( A() , B( GREAT( SOME , NOT ) ) , C( YES ) )
For this I am trying to use the three rules on the following grammar:
template< typename Iterator , typename ExpressionAST >
struct InputGrammar : qi::grammar<Iterator, ExpressionAST(), space_type> {
InputGrammar() : InputGrammar::base_type( ) {
tag = ( qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z_0-9") )[ push_back( at_c<0>(qi::_val) , qi::_1 ) ];
command = tag [ at_c<0>(qi::_val) = at_c<0>(qi::_1) ] >> "(" >> (*instruction >> ",")
[ push_back( at_c<1>(qi::_val) , qi::_1 ) ] >> ")";
instruction = ( command | tag ) [qi::_val = qi::_1];
}
qi::rule< Iterator , ExpressionAST() , space_type > tag;
qi::rule< Iterator , ExpressionAST() , space_type > command;
qi::rule< Iterator , ExpressionAST() , space_type > instruction;
};
Notice that my tag rule just tries to capture the identifiers used in the expressions (the 'function' names). Also notice that the signature of the tag rule returns a ExpressionAST instead of a std::string, like in most examples. The reason I want to do it like this is actually pretty simple: I hate using variants and I will avoid them if possible. It would be great to keep the cake and eat it too I guess.
A command should start with a tag (the name of the current node, first string field of the AST node) and a variable number of arguments enclosed by parentheses, and each of the arguments can be a tag itself or another command.
However, this example does not work at all. It compiles and everything, but at run time it fails to parse all my test strings. And the thing that really annoys me is that I can't figure how to fix it, since I can't really debug the above code, at least in the traditional meaning of the word. Basically the only way I see I can fix the above code is by knowing what I am doing wrong.
So, the question is that I don't know what is wrong with the above code. How would you define the above grammar?
The ExpressionAST type I am using is:
struct MockExpressionNode {
std::string name;
std::vector< MockExpressionNode > operands;
typedef std::vector< MockExpressionNode >::iterator iterator;
typedef std::vector< MockExpressionNode >::const_iterator const_iterator;
iterator begin() { return operands.begin(); }
const_iterator begin() const { return operands.begin(); }
iterator end() { return operands.end(); }
const_iterator end() const { return operands.end(); }
bool is_leaf() const {
return ( operands.begin() == operands.end() );
}
};
BOOST_FUSION_ADAPT_STRUCT(
MockExpressionNode,
(std::string, name)
(std::vector<MockExpressionNode>, operands)
)
| As far as debugging, its possible to use a normal break and watch approach. This is made difficult by how you've formatted the rules though. If you format per the spirit examples (~one parser per line, one phoenix statement per line), break points will be much more informative.
Your data structure doesn't have a way to distinguish A() from SOME in that they are both leaves (let me know if I'm missing something). From your variant comment, I don't think this was your intention, so to distinguish these two cases, I added a bool commandFlag member variable to MockExpressionNode (true for A() and false for SOME), with a corresponding fusion adapter line.
For the code specifically, you need to pass the start rule to the base constructor, i.e.:
InputGrammar() : InputGrammar::base_type(instruction) {...}
This is the entry point in the grammar, and is why you were not getting any data parsed. I'm surprised it compiled without it, I thought that the grammar type was required to match the type of the first rule. Even so, this is a convenient convention to follow.
For the tag rule, there are actually two parsers qi::char_("a-zA-Z_"), which is _1 with type char and *qi::char_("a-zA-Z_0-9") which is _2 with type (basically) vector<char>. Its not possible to coerce these into a string without autorules, But it can be done by attaching a rule to each parsed char:
tag = qi::char_("a-zA-Z_")
[ at_c<0>(qi::_val) = qi::_1 ];
>> *qi::char_("a-zA-Z_0-9") //[] has precedence over *, so _1 is
[ at_c<0>(qi::_val) += qi::_1 ]; // a char rather than a vector<char>
However, its much cleaner to let spirit do this conversion. So define a new rule:
qi::rule< Iterator , std::string(void) , ascii::space_type > identifier;
identifier %= qi::char_("a-zA-Z_") >> *qi::char_("a-zA-Z_0-9");
And don't worry about it ;). Then tag becomes
tag = identifier
[
at_c<0>(qi::_val) = qi::_1,
ph::at_c<2>(qi::_val) = false //commandFlag
]
For command, the first part is fine, but theres a couple problems with (*instruction >> ",")[ push_back( at_c<1>(qi::_val) , qi::_1 ) ]. This will parse zero or multiple instruction rules followed by a ",". It also attempts to push_back a vector<MockExpressionNode> (not sure why this compiled either, maybe not instantiated because of the missing start rule?). I think you want the following (with the identifier modification):
command =
identifier
[
ph::at_c<0>(qi::_val) = qi::_1,
ph::at_c<2>(qi::_val) = true //commandFlag
]
>> "("
>> -(instruction % ",")
[
ph::at_c<1>(qi::_val) = qi::_1
]
>> ")";
This uses the optional operator - and the list operator %, the latter is equivalent to instruction >> *("," >> instruction). The phoenix expression then just assigns the vector directly to the structure member, but you could also attach the action directly to the instruction match and use push_back.
The instruction rule is fine, I'll just mention that it is equivalent to instruction %= (command|tag).
One last thing, if there actually is no distinction between A() and SOME (i.e. your original structure with no commandFlag), you can write this parser using only autorules:
template< typename Iterator , typename ExpressionAST >
struct InputGrammar : qi::grammar<Iterator, ExpressionAST(), ascii::space_type> {
InputGrammar() : InputGrammar::base_type( command ) {
identifier %=
qi::char_("a-zA-Z_")
>> *qi::char_("a-zA-Z_0-9");
command %=
identifier
>> -(
"("
>> -(command % ",")
>> ")");
}
qi::rule< Iterator , std::string(void) , ascii::space_type > identifier;
qi::rule< Iterator , ExpressionAST(void) , ascii::space_type > command;
};
This is the big benefit of using a fusion wrapped structure that models the input closely.
|
3,078,185 | 3,078,296 | What can glStencil do? | I'm wondering what the stencil buffer is and what it can do.
| http://en.wikipedia.org/wiki/Stencil_buffer
Basically, the stencil buffers allows you to draw only in parts "marked" in the stencil buffer, rejecting pixels where this "mark" doesn't have certain value.
Is used to clip rendering in non-rectangular shapes, and to do shadow volumes.
|
3,078,237 | 3,078,241 | Defining volatile class object | Can the volatile be used for class objects?
Like:
volatile Myclass className;
The problem is that it doesn't compile,
everywhere when some method is invoked, the error says:
error C2662: 'function' : cannot convert 'this' pointer from 'volatile MyClass' to 'MyCLass &'
What is the problem here and how to solve it?
EDIT:
class Queue {
private:
struct Data *data;
int amount;
int size;
public:
Queue ();
~Queue ();
bool volatile push(struct Data element);
bool volatile pop(struct Data *element);
void volatile cleanUp();
};
.....
volatile Queue dataIn;
.....
EnterCriticalSection(&CriticalSection);
dataIn.push(element);
LeaveCriticalSection(&CriticalSection);
| Yes, you can, but then you can only call member functions that are declared volatile (just like the const keyword). For example:
struct foo {
void a() volatile;
void b();
};
volatile foo f;
f.a(); // ok
f.b(); // not ok
Edit based on your code:
bool volatile push(struct Data element);
declares a non-volatile member function that returns a bool volatile (= volatile bool). You want
bool push(struct Data element) volatile;
|
3,078,257 | 3,078,426 | Access objective-c from c++ | Can somebody point me in the right direction for this. I've found lots of info on using c++ in obj c but not the other way around. I am making an iPhone game in c++ but need to tap into some of the features the iPhone has to offer.
Thanks
| There's actually no difference between "using C++ in Objective-C" and "using Objective-C in C++" - they're both actually using Objective-C++ (which is a distinct language).
Just make sure that you're compiling the source file as Objective-C++: either rename it with a .mm extension, or add the compiler flag -x objective-c++ to affect all of your source files.
Then you can do just about anything that you would do in Objective-C.
|
3,078,316 | 3,078,478 | Static Linking Function in a DLL Project | I don't know why but I thought I could statically link a function from an Import Library. It would seem I am the only one who has ever tried because I can't for the life of me find a similar post. Is there a way to selectively static link functions from a dynamically linked project without creating a new project and/or recompiling it as static? The module itself communicates over an interface and I'm not really big on exporting functions. I just want to static link the code to create the object....
how bad would it be to turn this into a macro?
IClassFactory* CF = NULL;
hr = CoGetClassObject (
CLSID_CF,
CLSCTX_INPROC_SERVER,
NULL,
IID_IClassFactory,
(void**)&CF );
Interface* Instance = NULL;
hr = CF->CreateInstance (
NULL,
IID_Interface,
(void**)&Instance );
| If this is your own project (or you have source code and are willing to modify it), you could use inline functions for the functions you don't want to dynamically link.
|
3,078,469 | 3,078,473 | C++: overloading mathematical operators | I am looking to overload, let's say, the addition operator and have it add two objects of the same class. When I declare this "operator+" prototype function in the class declaration in the header file, I pass in both objects as parameters. I get a compiler error saying that "binary 'operator +' has too many parameters". I was searching around for an answer online and found out that declaring an inline function just outside the class declaration in the header file compiled out. I'm wondering what I was doing wrong or if I'm missing something here. Here is the code I am using in the header file.
class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
Person operator+(Person r, Person i);
};
This compiles with the error I mentioned above. Below is the code that compiles fine.
class Person
{
private:
int age;
double weight;
public:
Person::Person(); //default constructor
Person::~Person(); //default desctructor
};
inline Person operator+(Person r, Person i)
{
return Person(0,0);
}
| If you declare oparator+ as an instance function then the first argument is being passed as this object and thus you need only one more argument. Read this for more info, in particular try to understand the const concept:
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
The best approach as advised in the referenced artice is:
class Person
{
...
Person &operator+=(const Person &i);
const Person operator+(const Person &i) const;
...
};
Person &Person::operator+=(const Person &i) {
... // Do the compound assignment work.
return *this;
}
const Person Person::operator+(const Person &i) const {
Person result = *this; // Make a copy of myself. Same as MyClass result(*this);
result += i; // Use += to add other to the copy.
return result; // All done!
}
if you decide to use const version remember that you will only be able to call const methods on this and i references. This is the preferred way.
The article I referenced to explains the idea of overloading += first and then defining + using += in more details. This is a good idea since += operator must be separately overloaded.
Additionally - David Rodríguez suggests operator+ to be implemented as a free function regardless of the presence of += .
|
3,078,486 | 13,480,142 | How to Create a webservice by Qt | I am looking for a tool or plugin that help me to create web service as DOT NET does for Linux.
| From the OP Edit in question:
After search, I found that Qt does not have any thing to write web
services
gSOAP is an Open Source Solution for this problem, currently we use
it.
|
3,078,602 | 3,078,616 | C++: How to add external libraries | I'm trying to add SVL to my project.
Without it I'm getting hundreds of errors (undefined reference...). After adding -lSVL all errors are gone, but gcc says: "cannot find -lSVL". Everything else (SDL, SDL_TTF, SDL_Mixer...) works fine.
| You should inform gcc of the path where libsvl.a is installed, for example:
gcc -lsvl -L/my/path/
Also, pay attention to the case if you work under Linux ("SVL" is different from "svl").
|
3,078,742 | 3,078,856 | C++: Difference between NVI and Template Method Patterns? | What is the difference between NVI ( Non-Virtual Interface ) and the Template Method patterns?
They seem very similar and I've read both that they're basically the same and that they're subtly different with Template being somehow more general.
| NVI is an idiom, Template Method is a pattern. NVI is an implementation of the Template Method Pattern using dynamic dispatch in C++; it is also possible to create template methods in C++ using template metaprogramming to eliminate the dynamic dispatch.
A pattern is more general than an idiom, and languages may use different idioms to implement the pattern.
|
3,078,851 | 3,078,881 | C++, get the name of the function | In C++, is there a way to get the function signature/name from it's pointer like this?
void test(float data) {}
cout << typeid(&test).name();
I want to use this data for logging.
| If you just want to log the current function name, most of the compilers have __FUNCTION__ macro, which will give you the current function name at compile time.
You may also look for stack walking techniques (here is an example for Windows), which can provide you more information about the current call stack and function names at runtime.
|
3,078,897 | 3,078,910 | unsigned _stdcall.... implicitly an int? | A function with this signature:
unsigned _stdcall somefunction (LPVOID lParam);
does it mean that it implicitly returns an integer? As unsigned really isn't a value by itself? And _stdcall is a calling convention....
| unsigned is a shortcut for unsigned int, so this function returns an unsigned integer.
|
3,078,998 | 3,079,127 | c++ must delete a references? | in the following code:
class x
{
private:
someRef& m_ref;
public:
x(someRef& someRef):m_ref(someRef)
{
}
do I need to do:
~x()
{
delete m_ref;
}
which by the way doesnt work without getting the pointer...
basically I'm asking: Do I need to call a destructor on a reference member?
| No. You can only delete pointers, not references, and even then you must only delete objects that you allocated using the new operator. And then you must be sure to delete them only once. Here is the case in which you would need to use delete in your destructor:
class x
{
private:
someObj* m_ptr;
public:
x():m_ptr(new someObj())
{
}
~x()
{
delete m_ptr;
}
But in general it's best to avoid even this and use smart pointers instead.
|
3,079,067 | 3,079,078 | Size of empty class and empty function? | What will be solution in the following code
Class A{}
void func(){}
printf("%d,%d",sizeof(A),sizeof(func));
| Size of an empty class is non zero(most probably 1), so as to have two objects of the class at different addresses.
http://www2.research.att.com/~bs/bs_faq2.html#sizeof-empty explains it better
class A{};
void func(){}
std::cout<<sizeof(A)<<std::endl<<sizeof(&func));// prints 1 and 4 on my 32 bit system
|
3,079,104 | 3,079,285 | Getting shared_ptr to call a member function once its reference count reaches 0 | I'm creating a wrapper for a HANDLE that does not work with DuplicateHandle, so instead I am trying to wrap the handle in a shared_ptr.
Imagine the following code:
class CWrapper
{
public:
CWrapper() :
m_pHandle(new HANDLE, &CWrapper::Close)
{
//code to open handle
}
private:
void Close()
{
//code to close handle
}
std::shared_ptr<HANDLE> m_pHandle;
}
I have also tried creating close with a HANDLE parameter (not ideal). Either way, I get the compiler error "Term does not evaluate to a function taking 0 arguments". Is this because of the implicit this pointer? How do I fix this? How do I call a member function from the shared pointer?
| I think you have your abstractions the wrong way around.
shared_ptr gives you a copyable "handle" to a shared resource that can't itself be copied. Using shared_ptr with a type that doesn't perform its own cleanup when it is deleted isn't an optimal use.
If make your class' single responsibility to clean up this inherently non-copyable resource properly in its destructor, then you can use shared_ptr to provide shared ownership which is what its single responsibility should be. (I consider HANDLE to be non-copyable as if you try to make a simple copy of a HANDLE the copies cannot be treated as independent; the last copy must be correctly closed so the owners of copies would need to know about other copies in existence.)
class CWrapper
{
public:
CWrapper()
{
// code to open handle
}
~CWrapper()
{
// code to close handle
}
private:
// prevent copying
CWrapper(const CWrapper&);
CWrapper& operator=(const CWrapper&);
HANDLE mHandle;
};
Now use shared_ptr<CWrapper> where you need to shared the handle, you can use a typedef if you think that this is too verbose.
A custom deleter is an overly complex solution, IMHO.
|
3,079,299 | 3,079,304 | why can I not get access to my DLL function | I'm trying to load a DLL dynamically using LoadLibrary(), which works, however I cannot then get the address of the function in the DLL that I'm trying to call.
DLL function: (in CPP file)
_declspec(dllexport) void MyDllFunc()
{
printf("Hello from DLL");
}
Calling code:
typedef void (*MyDllFuncPtr)();
int _tmain(int argc, _TCHAR* argv[])
{
HINSTANCE LoadMe;
LPCWSTR str = L"C:\\Users\\Tony\\Documents\\Visual Studio 2008\\Projects\\DLL Loading\\Release\\MyDll.dll";
LoadMe = LoadLibrary(str);
if(LoadMe != 0)
printf("Successfully Loaded!\r\n");
else
printf("Loading Failed \r\n" );
MyDllFuncPtr func;
func = (MyDllFuncPtr)GetProcAddress(LoadMe, "MyDllFunc");
if (func != NULL)
func();
FreeLibrary(LoadMe);
}
func returns NULL!!!
What am I doing wrong?
This is a Win32 Console project.
| Write
extern "C" _declspec(dllexport) void MyDllFunc()
|
3,079,366 | 3,079,741 | 2D OpenGL scene slows down with lots of overlapping shapes | I'm drawing 2D shapes with OpenGL. They aren't using that many polygons. I notice that I can have lots and lots of shapes as long as they don't overlap. If I get a shape behind a shape behind.... etc.. it really starts lagging. I feel like I might be doing something wrong. Is this normal and is there a way to fix this (I can't omit rendering because I do blending for alpha). I also have CW backface culling enabled.
Thanks
| Are your two cases (overlapping and non-overlapping) using the exact same set of shapes? Because if the overlapping case involves a total area of all your shapes that is larger than the first case, then it would be expected to be slower. If it's the same set of shapes that slows down if some of them overlap, then that would be very unusual and shouldn't happen on any standard hardware OpenGL implementation (what platform are you using?). Backface culling won't be causing any problem.
Whenever a shape is drawn, the GPU has to do some work for each pixel that it covers on the screen. If you draw the same shape 100 times in the same place, then that's 100-times the pixel work. Depth buffering can reduce some of the extra cost for opaque objects if you draw objects in depth-sorted order, but that trick can't work for things that use transparency.
When using transparency, it's the sum of the area of each rendered shape that matters. Not the amount of the screen that's covered after everything is rendered.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.