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 |
|---|---|---|---|---|
1,177,739 | 1,177,988 | What are the rules for choosing from overloaded template functions? | Given the code below, why is the foo(T*) function selected ?
If I remove it (the foo(T*)) the code still compiles and works correctly, but G++ v4.4.0 (and probably other compilers as well) will generate two foo() functions: one for char[4] and one for char[7].
#include <iostream>
using namespace std;
template< typename T >
void foo( const T& )
{
cout << "foo(const T&)" << endl;
}
template< typename T >
void foo( T* )
{
cout << "foo(T*)" << endl;
}
int main()
{
foo( "bar" );
foo( "foobar" );
return 0;
}
| Formally, when comparing conversion sequences, lvalue transformations are ignored. Conversions are grouped into several categories, like qualification adjustment (T* -> T const*), lvalue transformation (int[N] -> int*, void() -> void(*)()), and others.
The only difference between your two candidates is an lvalue transformation. String literals are arrays that convert to pointers. The first candidate accepts the array by reference, and thus won't need an lvalue transformation. The second candidate requires an lvalue transformation.
So, if there are two candidates that both function template specializations are equally viable by looking only at the conversions, then the rule is that the more specialized one is chosen by doing partial ordering of the two.
Let's compare the two by looking at their signature of their function parameter list
void(T const&);
void(T*);
If we choose some unique type Q for the first parameter list and try to match against the second parameter list, we are matching Q against T*. This will fail, since Q is not a pointer. Thus, the second is at least as specialized as the first.
If we do the other way around, we match Q* against T const&. The reference is dropped and toplevel qualifiers are ignored, and the remaining T becomes Q*. This is an exact match for the purpose of partial ordering, and thus deduction of the transformed parameter list of the second against the first candidate succeeds. Since the other direction (against the second) didn't succeed, the second candidate is more specialized than the first - and in consequence, overload resolution will prefer the second, if there would otherwise be an ambiguity.
At 13.3.3.2/3:
Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if [...]
S1 is a proper subsequence of S2 (comparing the conversion sequences in the canonical form
defined by 13.3.3.1.1, excluding any Lvalue Transformation; the identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence) or, if not that [...]
Then 13.3.3/1
let ICSi(F) denote the implicit conversion sequence that converts the i-th argument in the list to the type of the i-th parameter of viable function F. 13.3.3.1 defines the implicit conversion sequences and 13.3.3.2 defines what it means for one implicit conversion sequence to be a better conversion sequence or worse conversion sequence than another.
Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then [...]
F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 according to the partial ordering rules described in 14.5.5.2, or, if not that, [...]
Finally, here is the table of implicit conversions that may participate in an standard conversion sequence at 13.3.3.1.1/3.
Conversion sequences http://img259.imageshack.us/img259/851/convs.png
|
1,177,944 | 1,177,961 | C++ programs, compiling with g++ | I am very aware of compiling C++ programs with g++ in linux environment. But, may be I am missing something, I am getting this strange output/behaviour.
I have source file in test.cpp.
To compile this, I did
(1)
g++ -c test.cpp
g++ -o test test.o
./test
Everything works fine.
But when I did compling and linking in same stage, like this
(2)
g++ test.cpp -o test
./test => Works fine
(3)
g++ -c test.cpp -o test => Doesn't work
In my last case, test is generated but is no more executable; but in my guess it should work fine.
So, what is wrong or do I need to change some settings/configuration ??
I am using g++ 4.3.3
Thanks.
| When you say:
g++ -c test.cpp -o test
The -c flag inhibits linking, so no executable is produced - you are renaming the .o file.
Basically, don't do that.
|
1,178,127 | 1,178,167 | Shared libraries memory space | Does a C++ shared library have its own memory space? Or does it share the caller process' one?
I have a shared library which contains some classes and wrapper functions.
One of this wrapper function is kinda:
libXXX_construct() which initializes an object and returns the pointer to the said object.
Once I use libXXX_construct() in a caller program where is the object placed?Is it in the "caller" memory space or is it in the library's memory space?
| A linked instance of the shared library shares the memory space of the instance of the executable that linked to it, directly or indirectly. This is true for both Windows and the UN*X-like operating systems. Note that this means that static variables in shared libraries are not a way of inter-process communication (something a lot of people thinks).
|
1,178,535 | 1,178,693 | How to compile open source framework in Visual Studio C++, that has "makefile" only and no solution file? | How to compile open source framework in Visual Studio C++, that has "makefile" only and no solution file?
| Unfortunately there is no silver bullet for this kind of change. Make and Visual Studio C++ style build are very different beasts. While they can do very similar operations, they can also have wildly different structures which makes providing a simple guide very difficult.
IMHO, the best way to achieve this is to start a new C++ project. Add in all of the existing files and go through the make file step by step attempting to convert every action to the equivalent C++ action.
|
1,179,006 | 1,179,105 | Numerical Conversion in C/C++ | I need to convert a C/C++ double to a 64 bit two's complement, where the Radix point is at bit number 19 (inclusive).
This means that for the format I want to convert to
0x0000 0000 0010 0000 is the number 1
0xFFFF FFFF FFF0 0000 is the number -1
0x0000 0000 0000 0001 is 0.95 x 10^-6
0xFFFF FFFF FFFF FFFF is -0.95 x 10^-6
So far I've though about using the modf function from the C standard library, but that doesn't really cover my needs. I've also looked at some type conversion classes in Boost, but I couldn't find the right solution there either. Does anyone know of a library or easy way to do this conversion? Maybe someone more familiar with Boost can point me in the right direction.
If this helps at all, here is some documentation of how doubles are stored.
Edit:
I have a follow up question, this is really for my own interest. What is 'Radix'? Here it's sort of like a decimal point. But, the only other time I've heard the term Radix was when I was learning about the Discrete Fast Fourier Transform. If I remember correctly, the Radix-II method is fast because there are fewer multiplies need to calculate the DFT.
| This should give the results you want:
double d = someValue();
int64_t fixed_point = static_cast<int64_t>(d * (1024*1024));
|
1,179,378 | 1,179,421 | Mysterious oneliner template code, any one? | I was reading this page :
C++ Tip: How To Get Array Length. The writer presented a piece of code to know the size of static arrays.
template<typename T, int size>
int GetArrLength(T(&)[size]){return size;} // what does '(&)' mean ?
.
.
.
int arr[17];
int arrSize = GetArrLength(arr); // arrSize = 17
Could anyone please shed the light on this code, because I couldn't understand how it really works.
| The function is passed a reference (&) to an array of type T, and size size.
|
1,179,669 | 1,179,692 | realloc function that would work for memory allocated using new instead of realloc | I'm aware that there is a realloc function that would allow me to resize the memory block (and it's paired with a free function). However, I'm trying to do the same to a c++ class with some member pointers allocated memory using new instead of realloc. Is there an equivalent keyword to realloc in c++ that would allow me to achieve the same goal when the memory is paired using new/delete rather than malloc or realloc and free?
Thanks in advance.
| No, there isn't. And frankly, if you are using new or new[]. your C++ code is probably not well designed. Look at using std::vector instead of new[], and at using values instead of new.
|
1,179,685 | 1,179,766 | How do I take ownership of an abandoned boost::interprocess::interprocess_mutex? | My scenario: one server and some clients (though not many). The server can only respond to one client at a time, so they must be queued up. I'm using a mutex (boost::interprocess::interprocess_mutex) to do this, wrapped in a boost::interprocess::scoped_lock.
The thing is, if one client dies unexpectedly (i.e. no destructor runs) while holding the mutex, the other clients are in trouble, because they are waiting on that mutex. I've considered using timed wait, so if I client waits for, say, 20 seconds and doesn't get the mutex, it goes ahead and talks to the server anyway.
Problems with this approach: 1) it does this everytime. If it's in a loop, talking constantly to the server, it needs to wait for the timeout every single time. 2) If there are three clients, and one of them dies while holding the mutex, the other two will just wait 20 seconds and talk to the server at the same time - exactly what I was trying to avoid.
So, how can I say to a client, "hey there, it seems this mutex has been abandoned, take ownership of it"?
| Unfortunately, this isn't supported by the boost::interprocess API as-is. There are a few ways you could implement it however:
If you are on a POSIX platform with support for pthread_mutexattr_setrobust_np, edit boost/interprocess/sync/posix/thread_helpers.hpp and boost/interprocess/sync/posix/interprocess_mutex.hpp to use robust mutexes, and to handle somehow the EOWNERDEAD return from pthread_mutex_lock.
If you are on some other platform, you could edit boost/interprocess/sync/emulation/interprocess_mutex.hpp to use a generation counter, with the locked flag in the lower bit. Then you can create a reclaim protocol that will set a flag in the lock word to indicate a pending reclaim, then do a compare-and-swap after a timeout to check that the same generation is still in the lock word, and if so replace it with a locked next-generation value.
If you're on windows, another good option would be to use native mutex objects; they'll likely be more efficient than busy-waiting anyway.
You may also want to reconsider the use of a shared-memory protocol - why not use a network protocol instead?
|
1,179,697 | 1,179,747 | C# books or web sites for C++ developers | I am looking for web sites or books that would help a C++ developer to pick up C#.
So far, this is the best one I've found.
| Frankly, when I learned .NET, it was difficult to understand it in many ways from a C++ background. I found that trying to fit C# into a C++ mindset actually worked against me - not for me.
I wouldn't focus on trying to find something that's C# for C++ developers - try to just find good resources for C# in general. Good, detail C# and .NET framework books will get you there, and your C++ background will just help you understand the details a bit better. Learning C# will be about learning the frameworks, the expected manner of doing things, and forgetting a lot of C++ habits.
I would recommend a couple of detailed books that aren't focused on beginner topics, such as CLR via C# and C# in Depth.
I also think that the Framework Design Guidelines was probably the most valuable resources for getting me to think in C#/.NET instead of C++ - it really goes into why the framework is the way it is, and learning how to write code that other C# developers will want to maintain. The guidelines are available online, but the book is very helpful in that it also explains the reasons behind the guidelines, not just the "rules."
|
1,179,879 | 1,181,773 | Where does context sensitivity get resolved in the C++ compilation process? | Yesterday I asked about C++ context sensitivity, see here. Among many excellent answers, here is the accepted one, by dmckee.
However, I still think there's something to be said about this (maybe some terminological confusion?). The question amounts to: what part of compilation deals with the ambiguity?
To clarify my terminology: A CFG is a grammar that has only one non-terminal symbol on the left-hand-side of the rule (eg. A->zC), a CSG is one that has a terminal (plus a non-terminal) on the left-hand-side (aAv->QT), where uppercase letters are nonterminals and lowercase are terminals.
Is any representation like the latter in the grammar parsing C++ source code?
Thank you, and sorry to push the issue.
| No C++ front end (parser, name/type resolver) that I know of
(including the one we built) implements a context sensitive parser using CSG grammar rules as you defined it. Pretty much they operate explicitly or implicitly with a context free grammar which still has ambiguities.
Many of them use a combination of top-down parsing and interwoven collection of type information to distinguish between the ambiguous cases.
Weaving the parsing and type collection together makes building a parser this way really messy and hard, producing the folk theorem "C++ is hard to parse".
Like many such "theorems", it isn't true, unless you also insist on parsing with one hand tied behind your back (e.g., recursive descent, LL(k), LALR [e.g., YACC]). If you use a parsing technology that can handle ambiguities, the C++ grammar is actually not so hard. We (and others, such as the
Elsa C++ parser) use GLR parsing technology for this reason. (We go a bit further and capture macro definitions, uses and preprocessor conditionals in the C++ grammer because we are interested in transforming the code before the processor has ruined it; normally preprocessor directives are treated completely separately in an independent preprocessor).
Elsa I think still interleaves the ambiguity resolution into the parsing process, but because the parsing is so clean this is easier to do. Our front end builds an AST with ambiguity nodes, and after the tree is built, we walk the tree using an attribute grammar evaluator to collect names, and types, and eliminate those branches of ambiguities that are type inconsistent. The latter is a really beautiful scheme, and completely decouples parsing and name resolution.
What is hard is actually doing the name resolution. C++ has a pretty arcane scheme for looking things up, and its spread across the 600 pages of the standard, as well as bent in various ways by various dialects. Keeping name resolution separate from parsing makes this ugliness more manageable, but the folk theorem should be "C++ is hard to name resolve".
|
1,179,937 | 1,179,951 | How does a C++ reference look, memory-wise? | Given:
int i = 42;
int j = 43;
int k = 44;
By looking at the variables addresses we know that each one takes up 4 bytes (on most platforms).
However, considering:
int i = 42;
int& j = i;
int k = 44;
We will see that variable i indeed takes 4 bytes, but j takes none and k takes again 4 bytes on the stack.
What is happening here? It looks like j is simply non-existent in runtime. And what about a reference I receive as a function argument? That must take some space on the stack...
And while we're at it - why can't I define an array or references?
int&[] arr = new int&[SIZE]; // compiler error! array of references is illegal
| everywhere the reference j is encountered, it is replaced with the address of i. So basically the reference content address is resolved at compile time, and there is not need to dereference it like a pointer at run time.
Just to clarify what I mean by the address of i :
void function(int& x)
{
x = 10;
}
int main()
{
int i = 5;
int& j = i;
function(j);
}
In the above code, j should not take space on the main stack, but the reference x of function will take a place on its stack. That means when calling function with j as an argument, the address of i that will be pushed on the stack of function. The compiler can and should not reserve space on the main stack for j.
For the array part the standards say ::
C++ Standard 8.3.2/4:
There shall be no references to references, no arrays of references,
and no pointers to references.
Why arrays of references are illegal?
|
1,180,069 | 1,180,250 | Finding edge in weighted graph | I have a graph with four nodes, each node represents a position and they are laid out like a two dimensional grid. Every node has a connection (an edge) to all (according to the position) adjacent nodes. Every edge also has a weight.
Here are the nodes represented by A,B,C,D and the weight of the edges is indicated by the numbers:
A 100 B
120 220
C 150 D
I want to structure a container and an algorithm that switches the nodes sharing the edge with the highest weight. Then reset the weight of that edge. No node (position) can be switched more than once each time the algorithm is executed.
For example, processing the above, the highest weight is on edge BD, so we switch those. Since no node can be switched more than once, all edges involved in either B or D is reset.
A D
120
C B
Then, the next highest weight is on the only edge left, switching those would give us the final layout: C,D,A,B.
I'm currently running a quite awful implementation of this. I store a long list of edges, holding four values for the nodes they are (potentially) connected to, a value for its weight and the position for the node itself. Every time anything is requested, I loop through the entire list.
I'm writing this in C++, could some parts of the STL help speed this up? Also, how to avoid the duplication of data? A node position is currently in five objects. The node itself that is there and the four nodes indicating a connection to it.
In short, I want help with:
Can this be structured in a way so that there is no data duplication?
Recognise the problem? If any of this has a name, tell me so I can google for more info on the subject.
Fast algorithms are always nice.
| As for names, this is a vertex cover problem. Optimal vertex cover is NP-hard with decent approximation solutions, but your problem is simpler. You're looking at a pseudo-maximum under a tighter edge selection criterion. Specifically, once an edge is selected every connected edge is removed (representing the removal of vertices to be swapped).
For example, here's a standard greedy approach:
0) sort the edges; retain adjacency information
while edges remain:
1) select the highest edge
2) remove all adjacent edges from the list
endwhile
The list of edges selected gives you the vertices to swap.
Time complexity is O(Sorting vertices + linear pass over vertices), which in general will boil down to O(sorting vertices), which will likely by O(V*log(V)).
The method of retaining adjacency information depends on the graph properties; see your friendly local algorithms text. Feel free to start with an adjacency matrix for simplicity.
As with the adjacency information, most other speed improvements will apply best to graphs of a certain shape but come with a tradeoff of time versus space complexity.
For example, your problem statement seems to imply that the vertices are laid out in a square pattern, from which we could derive many interesting properties. For example, that system is very easily parallelized. Also, the adjacency information would be highly regular but sparse at large graph sizes (most vertices wouldn't be connected to each other). This makes the adjacency matrix give a high overhead; you could instead store adjacency in an array of 4-tuples as it would retain fast access but almost entirely eliminate overhead.
|
1,180,694 | 1,180,729 | MFC: retrieve button ID programmatically | I have a CButton object called mouseCtrl, and in the DoDataExchange function, I have the following:
DDX_Control(pDX, IDC_MCCHECK, mouseMode);
Somewhere else in my program, I would like to be able to call a function/method of mouseMode so that I can retrieve the IDC_MCCCHECK id macro properly. Is there a function in MFC that can allow me to do that? Thanks in advance.
| mouseMode.GetDlgCtrlID()
|
1,180,805 | 1,180,828 | TCPL 5.9.9 (C++): Where would it make sense to use a name in its own initializer? | This is a question from the most recent version of Stroustrup's "The C++ Programming Language".
I've been mulling this over in my head for the past couple days.
The only thing I can come up with, (and this is probably incorrect) is something like this:
int* f(int n) {
int* a = &a - n * sizeof(int*);
return a;
}
My intent is to get the address of something higher up on the stack. Does this make any sense? Does anyone else have any other answers? Remember, this is in Chapter 5 (pointers, arrays, and structures) so the answer shouldn't involve something later on in the book.
| The only (barely) reasonable case I know of is when you want to pass a pointer to the object itself to its constructor. For example, say you have a cyclic linked list node:
class Node
{
public:
Node(Node* next): next(next) {}
private:
Node* next;
};
and you want to create a single-element cyclic list on the stack. You can do this:
Node n(&n);
A few other examples that aren't really practical (i.e. I don't see why you'd need that sort of thing), but otherwise valid:
int n = sizeof(n);
void* p = &p;
|
1,180,832 | 1,182,690 | Avoiding null pointer exceptions in a large c++ code base | I have inherited a large c++ code base and I have a task to avoid any null pointer exceptions that can happen in the code base. Are there are static analysis tools available, I am thinking lint, that you have used successfully.
What other things do you look out for?
| You can start by eliminating sources of NULL:
Change
if (error) {
return NULL;
}
Into
if (error) {
return DefaultObject; // Ex: an empty vector
}
If returning default objects does not apply and your code base already uses exceptions, do
if (error) {
throw BadThingHappenedException;
}
Then, add handling at appropriate places.
If you are working with legacy code, you could make some wrapper functions/classes:
ResultType *new_function() {
ResultType *result = legacy_function();
if (result) {
return result;
} else {
throw BadThingHappenedException;
}
}
New functionalities should start using new functions and have proper exception handling.
I know some programmers just don't get exceptions, including smart people like Joel. But, what ends up happening by returning NULL is that this NULL gets pass around like crazy since everybody would just think it's not their business to handle it and return silently. Some functions may return error code, which is fine, but the caller often ends up returning yet-another-NULL in response to errors. Then, you see a lot of NULL-checking in every single functions, no matter how trivial the function is. And, all it takes is just ONE place that doesn't check for NULL to crash the program. Exceptions force you to carefully think about the error and decide exactly where and how it should be handled.
It seems like you're just looking for easy solutions like static analysis tools (which you should always use). Changing pointers to references is also a great solution too. However, C++ has the beauty of RAII, which eliminates the need for having "try {} finally {}" everywhere, so I think it worths your serious consideration.
|
1,180,852 | 10,605,862 | Deterministic builds under Windows | The ultimate goal is comparing 2 binaries built from exact same source in exact same environment and being able to tell that they indeed are functionally equivalent.
One application for this would be focusing QA time on things that were actually changed between releases, as well as change monitoring in general.
MSVC in tandem with PE format naturally makes this very hard to do.
So far I found and neutralized those things:
PE timestamp and checksum
Digital signature directory entry
Debugger section timestamp
PDB signature, age and file path
Resources timestamp
All file/product versions in VS_VERSION_INFO resource
Digital signature section
I parse PE, find offsets and sizes for all those things and ignore byte ranges when comparing binaries. Works like charm (well, for the few tests I've run it). I can tell that signed executable with version 1.0.2.0 built on Win Server 2008 is equal to unsigned one, of version 10.6.6.6, build on my Win XP dev box, as long as compiler version and all sources and headers are the same. This seems to work for VC 7.1 -- 9.0. (For release builds)
With one caveat.
Absolute paths for both builds must be the same must have the same length.
cl.exe converts relative paths to absolute ones, and puts them right into objects along with compiler flags and so on. This has unproportional effects on whole binary. One character change in path will result in one byte changed here and there several times over whole .text section (however many objects were linked I suspect). Changing length of the path results in significantly more differences. Both in obj files and in linked binary.
Feels like file path with compile flags is used as some kind of hash, which makes it into linked binary or even affects placement order of unrelated pieces of compiled code.
So here is the 3-part question (summarized as "what now?"):
Should I abandon the whole project and go home because what I am trying to do breaks laws of physics and corporate policy of MS?
Assuming I handle absolute path issue (on policy level or by finding a magical compiler flag), are there any other things I should look out for? (things like __TIME__ do mean changed code, so I don't mind those not being ignored)
Is there a way to either force compiler to use relative paths, or to fool it into thinking the path is not what it is?
Reason for the last one is beautifully annoying Windows file system. You just never know when deleting several gigs worth of sources and objects and svn metadata will fail because of a rogue file lock. At least creating new root always succeeds while there is space left. Running multiple builds at once is an issue too. Running bunch of VMs, while a solution, is a rather heavy one.
I wonder if there is a way to setup a virtual file system for a process and its children so that several process trees will see different "C:\build" dirs, private to them only, all at the same time... A light-weight virtualization of sorts...
UPDATE: we recently opensourced the tool on GitHub. See Compare section in documentation.
| I solved this to an extent.
Currently we have build system that makes sure all new builds are on the path of constant length (builds/001, builds/002, etc), thus avoiding shifts in the PE layout. After build a tool compares old and new binaries ignoring relevant PE fields and other locations with known superficial changes. It also runs some simple heuristics to detect dynamic ignorable changes. Here is full list of things to ignore:
PE timestamp and checksum
Digital signature directory entry
Export table timestamp
Debugger section timestamp
PDB signature, age and file path
Resources timestamp
All file/product versions in VS_VERSION_INFO resource
Digital signature section
MIDL vanity stub for embedded type libraries (contains timestamp string)
__FILE__, __DATE__ and __TIME__ macros when they are used as literal strings (can be wide or narrow char)
Once in a while linker would make some PE sections bigger without throwing anything else out of alignment. Looks like it moves section boundary inside the padding -- it is zeros all around anyway, but because of it I'll get binaries with 1 byte difference.
UPDATE: we recently opensourced the tool on GitHub. See Compare section in documentation.
|
1,180,902 | 1,182,618 | Problem with iterating over a lots of images in OpenCv with mac os | I'm trying to iterator over some directories containing approximately 3000 images. I load the image. If the image is loaded I release it.
That is the smallest program that I can write to reproduce the error.
After loading and releasing 124 images the program stops loading images. I think this a memory issue but I don't understand what exactly causes the program to stop loading images.
I'm using OpenCV on my Mac. I don't know how exactly I can figure out which version I'm using.
Here is the Code from my project.
bool FaceDetectionStrategy::detectFace(std::string imagePath) {
IplImage *img = cvLoadImage(imagePath.c_str(), CV_LOAD_IMAGE_COLOR);
if (img) {
std::cout << "Image loaded " << imagePath << std::endl;
cvReleaseImage(&img);
} else {
std::cout << "Image not loaded " << imagePath << std::endl;
}
return true;
}
This method is called for every image in the directorys I'm iterating through. After 124 images the if(img) part evaluates to false and the else branch is executed. If I try to load images from other parts of the program later on they also won't load.
Edit it is not a memory issue. Mac Os standard max open files is 256 after changing it to 512 I can open 251 images. so it seems that OpenCV doesn't closes the image files after loading them.
| Searching the bugtracker from OpenCv showed this answer to the problem: cvLoadImage with Mac ImageIO leaves file handles open.
It seems that this is a bug in the OpenCV mac implementation and the only way to solve it is to install a newer version of OpenCV.
EDIT installing the last version of OpenCV from the repository trunk solves the problem. Sometimes it helps checking the BugTracker of the frameworks you are using...
|
1,180,977 | 1,180,987 | Reading data from a file | I'm doing an exercise where I store coordinates into a .txt file called mydata, and then read it back from that file. However, I"m having trouble reading it back.
code:
#include "std_lib_facilities.h"
// Classes----------------------------------------------------------------------
struct Point{
Point(int a, int b):x(a), y(b) {};
Point(){};
int x;
int y;
};
// Main-------------------------------------------------------------------------
int main()
{
vector<Point> original_points;
vector<Point> processed_points;
cout << "Please enter 7 coordinate pairs.\n";
int x, y;
while(cin >> x >> y){
if(x == -1 || y == -1) break;
original_points.push_back(Point(x, y));}
cout << "Please enter file to send points to.\n";
string name;
cin >> name;
ofstream ost(name.c_str());
if(!ost)error("can't open output file", name);
for(int i = 0; i < original_points.size(); ++i)
ost << original_points[i].x << ',' << original_points[i].y << endl;
ost.close();
cout << "Please enter file to read points from.\n";
string iname;
cin >> iname;
ifstream ist(iname.c_str());
if(!ist)error("can't write from input file", name);
while(ist >> x >> y) processed_points.push_back(Point(x, y));
for(int i = 0; i < processed_points.size(); ++i)
cout << processed_points[i].x << ',' << processed_points[i].y << endl;
keep_window_open();
}
To test to see if the data is being read from the file I am pushing it back into a processed points vector, but when I run the program and enter points, it doesn't output any points from the processed_points vector. I think the problem is in the...
while(ist >> x >> y)
and this isn't the correct way to read from a file. Any help would be appreciated, thanks.
| The , you're emitting in the line
ost << original_points[i].x << ',' << original_points[i].y << endl;
is what stands in your way, since you're NOT reading it back! Either use a space instead of that comma, or, DO read it back...
|
1,180,984 | 1,181,078 | Programmatically compute the start time of a process on Windows | I'm writing c/c++ code on Windows using Visual Studio. I want to know how to calculate the start time of my process effectively. Can I just use gettimeofday()? I've found the following code from google but I don't understand what it's doing really :
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
FILETIME ft;
unsigned __int64 tmpres = 0;
static int tzflag;
if (NULL != tv)
{
GetSystemTimeAsFileTime(&ft);
//I'm lost at this point
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
/*converting file time to unix epoch*/
tmpres /= 10; /*convert into microseconds*/
tmpres -= DELTA_EPOCH_IN_MICROSECS;
tv->tv_sec = (long)(tmpres / 1000000UL);
tv->tv_usec = (long)(tmpres % 1000000UL);
}
if (NULL != tz)
{
if (!tzflag)
{
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
| If I understand you right you want to know what time your process started, correct? So you'll want to look into GetProcessTimes
If the process you're interested in is the current process, you can use GetCurrentProcess() to get the process handle that you'll need to call GetProcessTimes() this returns a pseudo-handle that you don't need to close.
|
1,181,079 | 1,181,081 | string::size_type instead of int | const std::string::size_type cols = greeting.size() + pad * 2 + 2;
Why string::size_type? int is supposed to work! it holds numbers!!!
| A short holds numbers too. As does a signed char.
But none of those types are guaranteed to be large enough to represent the sizes of any strings.
string::size_type guarantees just that. It is a type that is big enough to represent the size of a string, no matter how big that string is.
For a simple example of why this is necessary, consider 64-bit platforms. An int is typically still 32 bit on those, but you have far more than 2^32 bytes of memory.
So if a (signed) int was used, you'd be unable to create strings larger than 2^31 characters.
size_type will be a 64-bit value on those platforms however, so it can represent larger strings without a problem.
|
1,181,118 | 1,546,329 | How to create project dependencies in netbeans (c/c++ plugin) | As I work on a c++ application, I realize I am making a lot of classes and functions that could be used in other projects. So I'd like to put all this code in a separate net beans project that can be "included" into other projects. (with code completion etc)
I've tried creating a new "static library" project, then I added the project to my main project (by going to preferences->link->libraries and adding my "library project"), but the code completion feature does not find the .h file of my library project when i try to #include it, the project also won't build.
What is the correct way to do this?
| Creating a static library and adding it to Linker->Libraries is correct.
But another small step is needed: add directory with shared *.h files to project properties -> C Compiler (or C++ Compiler) -> Include Directories.
Also take a look at Subprojects sample: File -> New Project -> Samples -> C/C++ -> Subproject Application.
|
1,181,245 | 1,181,254 | How do I open a new console window for a Visual C++ console application? | What I want to do is something like this:
ConsoleWindow1.Print("1");
ConsoleWindow2.Print("2");
When I run the program, two console windows pop up and one gets printed with 1 and the other gets printed with 2. Is there a simple way of doing this?
| One way I see, to write a console that prints argument given to exe, and write another application that call both with different arguments, I didn't try but may be you can open two by WIN32 functions, see How to Open Console Window in a Win32 Application
|
1,181,246 | 1,181,250 | Standard library sort and user defined types | If I want to sort a vector of a UDT by one of two types of variables it holds, is it possible for the standard library sort to do this or do I need to write my own sort function.
For example if you had
struct MyType{
int a;
int b;
};
vector<MyType> moo;
// do stuff that pushes data back into moo
sort(moo.begin(), moo.end()) // but sort it by lowest to highest for a, not b
So is this possible using the stdlib sort? Thanks.
| It is possible to use standard function if your type implements "bool operator < (...) const" and a copy constructor (compiler-generated or custom).
struct MyType {
int a;
int b;
bool operator < (const MyType& other) const {
... // a meaningful implementation for your type
}
// Copy constructor (unless it's a POD type).
MyType(const MyType &other)
: a(other.a), b(other.b) { }
// Some other form of construction apart from copy constructor.
MyType()
: a(0), b(0) { }
};
Alternatively, you can pass an ordering function (or a functor) as a third argument to sort() instead of implementing operator "<".
bool type_is_less(const MyType& t1, const MyType& t2) { ... }
...
std::sort(c.begin(), c.end(), type_is_less);
This is useful in the following situations:
you don't want to implement operator "<" for whatever reason,
you need to sort a container of built-in or pointer types for which you can't overload operators.
you wish to sort the sequence using different orderings. ex: sometimes you want a struct with first/last name members sorted by first name, other times by last name. two different functions (or functors) make such options trivial.
|
1,181,462 | 1,181,475 | Practical point of view: Why would I want to use Python with C++? | I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?
I'd appreciate a simple example - Boost::Python will do
| It depends on your point of view:
Calling C++ code from a python application
You generally want to do this when performance is an issue. Highly dynamic languages like python are typically somewhat slower then native code such as C++. "Features" of C++ such as manual memory management allows for the development of very fast libraries, which can then be called from python in order to gain performance.
Another reason is due to the fact that most libraries on both windows and *nix are written in C or C++, and it's a huge advantage to have this existing code base available.
Calling python code from a C++ application
Complex applications sometimes require the ability to define additional abilities. Adding behaviors in a compiled application is messy, requires the original source code and is time consuming. Therefore it's often strategic to embed a scripting language such as python in order to make the application more flexible and customizable.
As for an example: I think you need to clarify a bit what you're interested in if you want the sample to be of any help. The boost manual provides a simple hello world sample, if that's what you're looking for.
|
1,181,633 | 1,181,646 | Determine compile-time existence of include files in C++ | I'm trying to write some portable C++ library code that will initially rely on Boost.Regex, and then move to TR1 as compilers support it, and eventually to the C++0x specification after things get moved from the std::tr1 namespace to std. Here is some pseudo-code for what I'd like to do with the preprocessor:
if( exists(regex) ) // check if I can #include <regex>
{
#include <regex> // per TR1
if( is_namespace(std::tr1) ) // are we on TR1 or C++0x?
{
using std::tr1::regex;
} else
{
using std::regex;
}
} else // fall-back to boost
{
#include <boost/regex.hpp>
using boost::regex;
}
Granted, all of that would need to be in preprocessor directives, but if I knew how to accomplish that I wouldn't be asking here. :)
| You can't do it without relying on a third party thing before preprocessing. Generally, things like autoconf can be used to accomplish this.
They work by generating another header file with #define directives that indicate existence of headers/libraries you want to use.
|
1,181,816 | 1,181,913 | How to receive dynamic length data from a message queue? | I have to send and receive dynamic data using a SysV message queue for a university project.
The length of the data is transmitted in a separate message, size is therefor already known.
And this is how I try to receive the data. I have to admit that I'm not a C++ specialist, especially when it comes to memory allocation.
struct {
long mtype;
char *mdata;
} msg;
msg.mdata = (char *)malloc(size * sizeof(char));
msgrcv(MSGQ_ID, &msg, size, MSG_ID, 0);
The problem seems to be the malloc call, but I don't know how to do this right.
EDIT
What I try is to have a some sort of read method in a OO wrapper around the message queues. I'd like to read the data in the message queue into a char[] or a std::string. What I have now looks (simplified) like this.
bool Wrapper::read(char *data, int length)
{
struct Message {
long mtype;
std::string mdata;
};
Message msg;
msg.mdata = std::string(size, '\0');
if(msgrcv(MSGQ_ID, &msg, size, MSG_ID, 0) < 0)
{
return false;
}
memcpy(data, msg.mdata.c_str(), msg.mdata.size());
return true;
}
All I get is segmentation faults or completely corrupt data (although this data sometimes contains what I want).
| You can't pass a pointer to a structure that contains a std::string member to msgrcv, this violates the interface contract.
The second parameter passed to msgrcv needs to point to a buffer with sufficient space to store a 'plain' C struct of the form struct { long mtype; char mdata[size]; }; where size is the third parameter to msgrcv.
Unfortunately, determining the size of this buffer might depend on size due to possible alignment issues but you have to assume that it doesn't on a system that provides this sort of interface. You can use the standard offsetof macro to help determine this size.
As a vector stores its components contiguously, once you know the size of the buffer, you can resize a vector of char and use this to hold the buffer. Using a vector relieves you of the obligation to free or delete[] a buffer manually.
You need to do something like this.
std::string RecvMessage()
{
extern size_t size; // maximum size, should be a parameter??
extern int MSGQ_ID; // message queue id, should be a parameter??
extern long MSG_ID; // message type, should be a parameter??
// ugly struct hack required by msgrcv
struct RawMessage {
long mtype;
char mdata[1];
};
size_t data_offset = offsetof(RawMessage, mdata);
// Allocate a buffer of the correct size for message
std::vector<char> msgbuf(size + data_offset);
ssize_t bytes_read;
// Read raw message
if((bytes_read = msgrcv(MSGQ_ID, &msgbuf[0], size, MSG_ID, 0)) < 0)
{
throw MsgRecvFailedException();
}
// a string encapsulates the data and the size, why not just return one
return std::string(msgbuf.begin() + data_offset, msgbuf.begin() + data_offset + bytes_read);
}
To go the other way, you just have to pack the data into a struct hack compatible data array as required by the msgsnd interface. As others have pointer out, it's not a good interface, but glossing over the implementation defined behaviour and alignment concerns, something like this should work.
e.g.
void SendMessage(const std::string& data)
{
extern int MSGQ_ID; // message queue id, should be a parameter??
extern long MSG_ID; // message type, should be a parameter??
// ugly struct hack required by msgsnd
struct RawMessage {
long mtype;
char mdata[1];
};
size_t data_offset = offsetof(RawMessage, mdata);
// Allocate a buffer of the required size for message
std::vector<char> msgbuf(data.size() + data_offset);
long mtype = MSG_ID;
const char* mtypeptr = reinterpret_cast<char*>(&mtype);
std::copy(mtypeptr, mtypeptr + sizeof mtype, &msgbuf[0]);
std::copy(data.begin(), data.end(), &msgbuf[data_offset]);
int result = msgsnd(MSGQ_ID, &msgbuf[0], msgbuf.size(), 0);
if (result != 0)
{
throw MsgSendFailedException();
}
}
|
1,182,114 | 1,182,126 | scanf() causing strange results | I have a piece of code that presents an interesting question (in my opinion).
/*power.c raises numbers to integer powers*/
#include <stdio.h>
double power(double n, int p);
int main(void)
{
double x, xpow; /*x is the orginal number and xpow is the result*/
int exp;/*exp is the exponent that x is being raised to */
printf("Enter a number and the positive integer power to which\n the first number will be raised.\n enter q to quit\n");
while(scanf("%lf %d", &x, &exp) ==2)
{
xpow = power(x, exp);
printf("%.3g to the power %d is %.5g\n", x, exp, xpow);
printf("enter the next pair of numbers or q to quit.\n");
}
printf("Hope you enjoyed your power trip -- bye!\n");
return 0;
}
double power(double n, int p)
{
double pow = 1;
int i;
for(i = 1; i <= p; i++)
{
pow *= n;
}
return pow;
}
If you'll notice the order of numbers to be entered is the floating point number and then the decimal number (base number and then the exponent). But when I enter the input with an integer base and floating point exponent it produces a strange result.
[mike@mike ~/code/powerCode]$ ./power
Enter a number and the positive integer power to which
the first number will be raised.
enter q to quit
1 2.3
1 to the power 2 is 1
enter the next pair of numbers or q to quit.
2 3.4
0.3 to the power 2 is 0.09
enter the next pair of numbers or q to quit.
It seems to push the second number of the floating point exponent back onto the next input. I was hoping some one could explain what was going on behind the scenes. I know that this is the work of scanf() not checking its array boundaries but if some one could give me some deeper understanding I'd really appreciate it.
Thanks Stack Overflow.
-M.I.
Edit.
Just wanted to thank everyone for their input. Any other answers are more then welcome.
Thanks again, S.O.
| When reading the first "2.3" scanf read up to the "." realizes it is no longer a valid integer and stops. So ".3" is left in the buffer, then you type "2 3.4" so ".3\n2 3.4" is in the buffer. When scanf parses that it gets ".3" and "2" just like your example shows.
|
1,182,183 | 1,187,720 | MATLAB MEX interface to a class object with multiple functions | I am using the MEX interface to run C++ code in MATLAB. I would like to add several functions to MATLAB for handling a System object:
sysInit()
sysRefresh()
sysSetAttribute(name, value)
String = sysGetAttribute(value)
sysExit()
Since each MEX dll can contain one function, I need to find a way to store the pointer to the global System object which will exist until deleted by a call to sysExit.
How can I do this in MATLAB properly? Are there any ways to store global pointers across calls to MEX functions?
| One common approach is to have several m-file functions that provide the public interface, e.g. sysInit.m, sysRefresh.m, etc.
Each of these m-files calls the mex function with some kind of handle, a string (or number) identifying the function to call, and any extra args. For example, sysRefresh.m might look like:
function sysRefresh(handle)
return sysMex(handle, 'refresh')
In your sysMex mex function, you can either have the handle be a raw heap pointer (easy, but not very safe), or you can maintain a mapping in C/C++ from the handle ID to the actual object pointers. This solution requires a little extra work, but it's much safer. This way someone can't accidentally pass an arbitrary number as a handle, which acts as a dangling pointer. Also, you can do fancier things like use an onCleanup function to release all memory and resources when you unload the mex function (e.g. so you don't have to restart matlab when you recompile the mex function).
You can go a bit further if you like and hide the handle behind a Matlab class. Read up on the OO features for Matlab in the docs if you're interested. If you're using a recent version, you can take advantage of their much cleaner handle objects.
|
1,182,379 | 1,182,525 | Boost Libraries on Monodevelop | I am trying to link some Boost .hpp files with Monodevelop, but I don't know how to tell the IDE where Libraries are.
If I want to include the array.hpp file, I write #include<directories/array.hpp>, but because this file makes calls to other files, and the directories to those files in the array.hpp file are only /boost/somefile, there are several path errors. What can I do? Thanks in advance.
| For libraries like Boost you'll need to add the path to the includes/libraries in your project configuration.
In MonoDevelop this can be done by choosing Project->Options->Configurations, then choose the appropriate build type (you'll probably want to edit both Debug and Release eventually), and then Code Generation->Paths.
The Library section is for your built libraries, if any, and the Include section is for stuff like headers and includes.
In this particular case you'll want to add /usr/local/boost to the Include section (change the path as necessary).
Once you've done that, you should be able to use Boost like so:
#include <boost/array.hpp> // make sure you use angle brackets
|
1,182,396 | 1,182,453 | C++ array excercise-help needed | I'm C++ begginer. I did this excercise from Deitel's book:
Use a one-dimensional array to solve
the following problem. Read in 20
numbers, each of which is between 10
and 100, inclusive. As each number is
read, validate it and store it in the
array only if it is not a duplicate of
a number already read. After reading
all the values, display only the
unique values that the user entered.
Provide for the "worst case" in which
all 20 numbers are different. Use the
smallest possible array to solve this
problem.
Here is my code:
#include <iostream>
using namespace std;
bool compare(int arrayNum[],int arraySize,int element);
int main()
{
const int size=20;
int i=1;
int num[size];
int arrayElement;
int counter=0;
while(i<=20)
{
cin>>arrayElement;
if(i==1) //stores first element in array
num[0]=arrayElement;
//compare new element with stored elements
//if element is not a duplicate store it in array
else if (compare(num,size,arrayElement))
{
counter++;
num[counter]=arrayElement;
}
i++;
}
//displays array elements
for(int k=0;k<=counter;k++)
cout<<num[k]<<endl;
return 0;
}
//compare elements in array
bool compare(int arrayNum[],int arraySize,int element)
{
for(int j=0;j<arraySize;j++)
{
if(arrayNum[j]==element)
return false;
}
return true;
}
It works, but I'm not sure if I have interpreted the task correctly. I assume then I don't have to include conditional statement for range of numbers (10 to 100 inclusive), as this will be read from the keyboard and input by me. Therefore why was this instruction included? Also at the end it says
use the smallest possible array
I assume the max size has to be 20,but I don't think there is a way to dynamically expand array size (for example while storing new elements) as array size is const. I would appreciate if someone could help me with this. Any comments regarding code, or better solution are welcome.
|
As each number is read, validate
it and store it in the array
Emphasis mine. The text clearly says that your program has to validate the input. In other words, it has to check that the entered number is between 10 and 100, and if it is not, handle the error appropriately. So yes, you do need a conditional, although exactly what you do to handle the error is up to you.
And you're right, since arrays aren't dynamically resizable, the array size has to be at least 20.
|
1,182,806 | 1,182,821 | Sockets - send and receive | I'm currently writing a chat server in C++. When a user connects to it, I open a socket and I create two threads, one to receive and one to send data.
Now my question:
Do I have to check if the other thread is currently using the socket, or will the send/recv function just wait until the socket is ready?
| Sending and receiving from TCP socket simultaneously should be entirely fine. (barring any possible OS bugs)
|
1,182,837 | 1,214,732 | Tracing memory corruption on a production linux server | Guys, could you please recommend a tool for spotting a memory corruption on a production multithreaded server built with c++ and working under linux x86_64? I'm currently facing the following problem : every several hours my server crashes with a segfault and the core dump shows that error happens in malloc/calloc which is definitely a sign of memory being corrupted somewhere.
Actually I have already tried some tools without much luck. Here is my experience so far:
Valgrind is a great(I'd even say best) tool but it slows down the server too much making it unusable in production. I tried it on a stage server and it really helped me find some memory related issues but even after fixing them I still get crashes on the production server. I ran my stage server under Valgrind for several hours but still couldn't spot any serious errors.
ElectricFence is said to be a real memory hog but I couldn't even get it working properly. It segfaults almost immediately on the stage server in random weird places where Valgrind didn't show any issues at all. Maybe ElectricFence doesn't support threading well?.. I have no idea.
DUMA - same story as ElectricFence but even worse. While EF produced core dumps with readable backtraces DUMA shows me only "?????"(and yes server is built with -g flag for sure)
dmalloc - I configured the server to use it instead of standard malloc routines however it hangs after several minutes. Attaching a gdb to the process reveals it's hung somewhere in dmalloc :(
I'm gradually getting crazy and simply don't know what to do next. I have the following tools to be tried: mtrace, mpatrol but maybe someone has a better idea?
I'd greatly appreciate any help on this issue.
Update: I managed to find the source of the bug. However I found it on the stage server not production one using helgrind/DRD/tsan - there was a datarace between several threads which resulted in memory corruption. The key was to use proper valgrind suppressions since these tools showed too many false positives. Still I don't really know how this can be discovered on the production server without any significant slowdowns...
| Folks, I managed to find the source of the bug. However I found it on the stage server using helgrind/DRD/tsan - there was a datarace between several threads which resulted in memory corruption. The key was to use proper valgrind suppressions since these tools showed too many false positives. Still I don't really know how this can be discovered on the production server without any significant slowdowns...
|
1,183,063 | 1,183,110 | Filter C++ through a perl script? | I have a perl script I'd like to filter my cpp/h files through before gcc processes them normally -- basically as an extra preprocessing step. Is there an easy way to do this? I realize I can feed the cpp files to the script and have gcc read the output from stdin, but this doesn't help with the header files.
| The classic way to handle such a process is to treat the source code (input to the Perl filter) as a new language, with a new file suffix. You then tell make that the way to compile a C++ source file from this new file type is with the Perl script.
For example:
New suffix: .ccp
New rule (assuming .cc suffix):
.ccp.cc:
${FILTERSCRIPT} $<
Add the new suffix to the suffix list - with priority over the normal C++ rules.
The last point is the trickiest. If you just add the .ccp suffix to the list, then make won't really pay attention to changes in the .ccp file when the .cc file exists. You either have to remove the intermediate .cc file or ensure that .ccp appears before .cc in the suffixes list. (Note: if you write a '.ccp.o' rule without a '.ccp.cc' rule and don't ensure that that the '.cc' intermediate is cleaned up, then a rebuild after a compilation failure may mean that make only compiles the '.cc' file, which can be frustrating and confusing.)
If changing the suffix is not an option, then write a compilation script that does the filtering and invokes the C++ compiler directly.
|
1,183,076 | 1,183,135 | C++ Constructor call | I have written this small code snippet in C++, the output is also attached.
I fail to understand why the constructor is being called only once, while i can see two calls being made for destructor.
From what i understand, default constructor and overloaded assignment operator should be called at line 28.
Can someone please throw some light on this:
1 #include <iostream>
2 using namespace std;
3
4 class ABC {
5 char c;
6 public:
7 ABC() {
8 cout << "default" << endl;
9 }
10 ABC(char c) {
11 this->c = c;
12 cout << c << endl;
13 }
14 ~ABC() {
15 cout << hex << this << " destructor " << c << endl;
16 }
17 void method() {
18 cout << "method" << endl;
19 }
20 void operator= (const ABC& a) {
21 cout << "operator" << endl;
22 }
23
24 };
25
26 int main() {
27 ABC b('b');
28 ABC a = b;
29 }
Output in g++ version 4.0.1:
~/src$ g++ test.cpp
~/src$ ./a.out
b
0xbffff0ee destructor b
0xbffff0ef destructor b
| The code you have just call the copy constructor, this is the definition:
ABC(const ABC& a):c(a.c){
cout << "copying " << hex << &a << endl;
}
And you shoud see output like this:
b
copying 0x7fffebc0e02f
0x7fffebc0e02e destructor b
0x7fffebc0e02f destructor b
If you want to call default constructor and then the assignment operator you must use two separate statement:
ABC b('b');
ABC a;
a = b;
|
1,183,210 | 1,183,217 | How do Concepts differ from Interfaces? | How do Concepts (ie those recently dropped from the C++0x standard) differ from Interfaces in languages such as Java?
| Concepts are for compile-time polymorphism, That means parametric generic code. Interfaces are for run-time polymorphism.
You have to implement an interface as you implement a Concept. The difference is that you don't have to explicitly say that you are implementing a Concept. If the required interface is matched then no problems. In the case of interfaces, even if you implemented all the required functions, you have to excitability say that you are implementing it!
I will try to clarify my answer :)
Imagine that you are designing a container that accepts any type that has the size member function. We formalize the Concept and call it HasSize, of course we should define it elsewhere but this is an example no more.
template <class HasSize>
class Container
{
HasSize[10]; // just an example don't take it seriously :)
// elements MUST have size member function!
};
Then, Imagine we are creating an instance of our Container and we call it myShapes, Shape is a base class and it defines the size member function. Square and Circle are just children of it. If Shape didn't define size then an error should be produced.
Container<Shape> myShapes;
if(/* some condition*/)
myShapes.add(Square());
else
myShapes.add(Circle());
I hope you see that Shape can be checked against HasSize at compile time, there is no reason to do the checking at run-time. Unlike the elements of myShapes, we could define a function that manipulates them :
void doSomething(Shape* shape)
{
if(/* shape is a Circle*/)
// cast then do something with the circle.
else if( /* shape is a Square */)
// cast then do something with the square.
}
In this function, you can't know what will be passed till run-time a Circle or a Square!
They are two tools for a similar job, though Interface-or whatever you call them- can do almost the same job of Concepts at run-time but you lose all benefits of compile-time checking and optimization!
|
1,183,450 | 1,183,455 | How to divide a string into parts - Roman numerals | I'm trying to divide a string into parts for reading Roman numerals. For example if the user enters
"XI"
I want the program to be able to understand that I is 1 and X is 10 in order for a data validation like this to work.
if(string roman == "X") int roman += 10;
etc.
| To access an individual character from a string, use square brackets:
int num = 0;
char r = roman[0];
if (r == 'X') {
num += 10;
}
The above is by no means a complete example, but should be enough to get you started. This example looks at the first character in the string roman (characters are numbered starting at the left with index 0). It checks to see whether the character is 'X', and if so, increments the num variable by 10.
|
1,183,554 | 1,183,597 | C++ derive from a native type | In some C++ code, I use integers to store lots of changing data.
To analyze my program, I want to log certain changes to some of the variables, such as how often a certain value is assigned to, and how often that assignment is redundant (the new value is the same as the old value.)
If the type were a class Foo, I'd just derive a new LoggingFoo and add my logging data to the member function(s) I was interested in, and then call the parent member function.
I'd have to update my code to use the new type, but as long as I was originally consistent with typedefs, that's a one-line change.
My problem is that the variable I want to add logging to is an int. You can't derive from built in types in C++ (can you?)
My question is whether there's a clever way to derive from the basic types (int, float, double, etc).
The solution may be to define a new class that effectively is an int.. it defines every operation an int can do and just applies that operation to a private int data member.
This strategy will work, but perhaps others have already made such a class and I can just use a "fakeint.h" header file definition. Is there such a "proxy native class wrapper" type definitions already available somewhere before I implement them myself?
I do realize of course my proxy int can't be used interchangably with an int especially since existing function definitions all expect an int.. but for my app, this is all in an inner loop which is doing lots of simple native +-*^= operations, not used as function arguments or anything.
| Something like this...
template <typename T> class logging_type
{
private:
T value;
public:
logging_type() { }
logging_type (T v) : value(v) { } // allow myClass = T
operator T () { return value; } // allow T = myClass
// Add any operators you need here.
};
This will create a template class that's convertible to the original type in both directions. You'd need to add logging handling and overload operators for every operation used on that type in your code.
This still might not be quite what you want, because it's implicitly convertible to int (or whatever type you specify), so your code might silently convert your logging int to an int and you'd be left with incomplete logs. You can prevent this in one direction by adding an 'explicit' keyword to the constructor, but you can't do anything similar with the conversion operator. Unless you perhaps make it private... I haven't tried. Doing either of those things will somewhat defeat the purpose though.
Edit: Since c++11, you can add explicit to conversion operators.
|
1,183,572 | 2,197,447 | Accessing a bitmap resource fails with error code 0x716 | So I don't know why I keep getting this error. Here's the relevant code:
//////////////////////// In resource.h ///////////////////////////
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Freestyle.rc
//
#define IDB_BITMAP1 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
//////////////////////// In the resource file ////////////////////
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
.
.
.
/////////////////////////////////////////////////////////////////////////////
//
// Bitmap
//
IDB_BITMAP1 BITMAP "NOP.bmp"
//////////////////////// In DllMain: /////////////////////////////
// Save the global module we're attached to other files can access it.
g_hLocalModule = hModule;
UnsafePrintToLog(SIMPLE_FORMAT_STRING, "Starting session...");
// Display the splash screen.
CSplash splashScreen(IDB_BITMAP1);
//////////////In CSplash::CSplash(WORD resourceID) //////////////
BitmapSplash = LoadBitmap((HINSTANCE)g_hLocalModule, MAKEINTRESOURCE(resourceID));
if(BitmapSplash == NULL)
{
volatile int temp = GetLastError();
Exit("Could not load the splash screen bitmap.");
}
| Is the bitmap resource you're trying to load in the DLL, or in the application that loaded the DLL?
When loading resources in a DLL, there are two possible sources, which is why the hInstance parameter is crucial.
Using the HINSTANCE parameter that you get from DllMain means that the resource is part of your DLL.
If the resource is located in the application that loaded your DLL, you can pass NULL in as the first argument of LoadResource(), and the application's resources will be searched.
From the documentation for LoadResource:
If hModule is NULL, the system loads
the resource from the module that was
used to create the current process.
Hope that helps.
-Scott
|
1,183,670 | 1,183,677 | How to send POST request to some website using winapi? | I'd like to send HTTP POST request to website and retrieve the resultant page using winapi. How can I do that?
| The MSDN docs have sample code using WinHTTP:
IWinHttpRequest::Send Method
Posting Data to the Server
|
1,183,700 | 1,183,709 | What is the meaning of this C++ Error std::length_error | While running my program I get this error:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
Abort trap
I know that you can't do much without the code but I think that this error is too deep in the code to copy all of it. Maybe I can figure it out if I understand what this error means.
Is this a sign for an issue with reading or writing at the wrong memory address?
Is there something I can do to get more information about the problem from my program?
| It means you tried to create a string bigger than std::string::max_size().
http://msdn.microsoft.com/en-us/library/as4axahk(VS.80).aspx
An exception of type length_error Class
is thrown when an operation produces a
string with a length greater than the
maximum size.
|
1,183,716 | 1,186,340 | Python Properties & Swig | I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:
class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.
How do you create properties using swig?
| Ooh, this is tricky (and fun). SWIG doesn't recognize this as an opportunity to generate @property: I imagine it'd be all too easy to slip up and recognize lots of false positives if it weren't done really carefully. However, since SWIG won't do it in generating C++, it's still entirely possible to do this in Python using a small metaclass.
So, below, let's say we have a Math class that lets us set and get an integer variable named "pi". Then we can use this code:
example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H
class Math {
public:
int pi() const {
return this->_pi;
}
void pi(int pi) {
this->_pi = pi;
}
private:
int _pi;
};
#endif
example.i
%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
[essentially example.h repeated again]
example.cpp
#include "example.h"
util.py
class PropertyVoodoo(type):
"""A metaclass. Initializes when the *class* is initialized, not
the object. Therefore, we are free to muck around the class
methods and, specifically, descriptors."""
def __init__(cls, *a):
# OK, so the list of C++ properties using the style described
# in the OP is stored in a __properties__ magic variable on
# the class.
for prop in cls.__properties__:
# Get accessor.
def fget(self):
# Get the SWIG class using super. We have to use super
# because the only information we're working off of is
# the class object itself (cls). This is not the most
# robust way of doing things but works when the SWIG
# class is the only superclass.
s = super(cls, self)
# Now get the C++ method and call its operator().
return getattr(s, prop)()
# Set accessor.
def fset(self, value):
# Same as above.
s = super(cls, self)
# Call its overloaded operator(int value) to set it.
return getattr(s, prop)(value)
# Properties in Python are descriptors, which are in turn
# static variables on the class. So, here we create the
# static variable and set it to the property.
setattr(cls, prop, property(fget=fget, fset=fset))
# type() needs the additional arguments we didn't use to do
# inheritance. (Parent classes are passed in as arguments as
# part of the metaclass protocol.) Usually a = [<some swig
# class>] right now.
super(PropertyVoodoo, cls).__init__(*a)
# One more piece of work: SWIG selfishly overrides
# __setattr__. Normal Python classes use object.__setattr__,
# so that's what we use here. It's not really important whose
# __setattr__ we use as long as we skip the SWIG class in the
# inheritance chain because SWIG's __setattr__ will skip the
# property we just created.
def __setattr__(self, name, value):
# Only do this for the properties listed.
if name in cls.__properties__:
object.__setattr__(self, name, value)
else:
# Same as above.
s = super(cls, self)
s.__setattr__(name, value)
# Note that __setattr__ is supposed to be an instance method,
# hence the self. Simply assigning it to the class attribute
# will ensure it's an instance method; that is, it will *not*
# turn into a static/classmethod magically.
cls.__setattr__ = __setattr__
somefile.py
import example
from util import PropertyVoodoo
class Math(example.Math):
__properties__ = ['pi']
__metaclass__ = PropertyVoodoo
m = Math()
print m.pi
m.pi = 1024
print m.pi
m.pi = 10000
print m.pi
So the end result is just that you have to create a wrapper class for every SWIG Python class and then type two lines: one to mark which methods should be converted in properties and one to bring in the metaclass.
|
1,183,755 | 1,183,765 | Creating X Number of Nameless Objects | In a lot online judge problems, the format for the input is as follows: first line is the number of test cases. Let's say X. Then X lines after that are the conditions for each test case.
In the example below, there are two test cases. Each test case specify the upper and lower bound for which primes should be shown in the output.
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Now for my question. Right now, my program can handle one test case like so:
int main()
{
TestCase t;
t.setRange();
t.compute();
t.print();
}
How can I create X amount of TestCases without naming them all 't'?
X is specified at rumtime.
| You can make a std::vector<TestCase> allofem; and allofem.push_back(TestCase()) X times; remember to #include <vector> of course. Then you can loop on allofem and compute and then print on each item.
|
1,183,782 | 1,184,121 | Reading data from file created from outside | I'm trying to read from files created outside of the program, but am having some trouble. The program has the user create a file. Then it reads words from two .txt files created outside of the program, and then writes the words to the created file.
#include "std_lib_facilities.h"
int main()
{
string word;
cout << "Create file.\n";
char name[20];
cin >> name;
ofstream ost(name, ios::out);
cout << "Open first file.\n";
char filename[20];
cin >> filename;
ifstream ist(filename);
while(ist >> word) ost << word << " ";
ist.close();
cout << "Open second file.\n";
cin >> filename;
ifstream isttwo(filename);
while(isttwo >> word) ost << word << " ";
isttwo.close();
ost.close();
keep_window_open();
}
However, when I open the created file in notepad, it comes out blank. Is this because reading into a string is impossible because the files being read were created separately? I'm not really sure. Any help is appreciated.
| The code is correct. Just make sure when you write the name of the first file and the second one you write their extensions as well.
For example :
first.txt
second.txt
|
1,183,900 | 1,183,914 | Best way to rotate an image using SDL? | I am building a game and the main character's arm will be following the mouse cursor, so it will be rotating quite frequently. What would be the best way to rotate it?
| With SDL you have a few choices.
Rotate all your sprites in advance (pre-render all possible rotations) and render them like you would any other sprite. This approach is fast but uses more memory and more sprites. As @Nick Wiggle pointed out, RotSprite is a great tool for generating sprite transformations.
Use something like SDL_gfx to do real-time rotation/zooming. (Not recommended, very slow)
Use SDL in OpenGL mode and render your sprites to primitives, applying a rotation to the primitives.
Option 3 is probably your best bet because you gain all of the advantages of using OpenGL. It's really up to you how to want to do it. It's also a possibility that you can load your sprites, perform all rotation calculations with SDL_gfx and then save the rotated versions to an SDL_Surface in memory.
EDIT: In response to your comment I would recommend checking out Lazyfoo's SDL tutorials. Specifically, this one about rotation. There is also an OpenGl function, glRotatef, which can be useful in your case. A quick search brought back this little tidbit which could also be helpful.
|
1,183,971 | 1,183,997 | Using `getline(cin, s);` after using `cin >> n;` | int n;
std::cin >> n;
std::string s = "";
std::getline(cin, s);
I noticed that if I use cin, my program would hang the next time I reach the line getline(cin, rangeInput).
Since getline() is using cin, is that why it is causing the program to hang if I have previously used cin? What should I do if I want to get a line after using cin?
| You need to clear the input stream - try adding the following after your cin:
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
The accepted answer to this question gives a good explanation of why/when this is required.
|
1,184,086 | 1,317,921 | How to incorporate or implement a DOM API to v8? | I am writing a server application that is able to manipulate the DOM before it is served to the client.
I am using C++ and Google's v8 as a javascript engine but I don't see any DOM API in v8.
Is there an open source implementation for doing DOM manipulation on HTML?
If not how would you implement one?
| The DOM is created and linked to the V8 engine in Chrome. The V8 sources know nothing about the browser DOM. The quickest way to get this working for you would be to try to extract the parts of Chrome (Chromium, really) that load HTML into a structure, and the parts that link the DOM and DOM methods into V8. It's probably not as bad as you think. If anything, Google produces pretty clean C++, as far as I can tell from looking at the V8 source code. It's probably not as bad as you think.
|
1,184,433 | 1,184,455 | Execute a process and return its standard output in VC++ | What's the easiest way to execute a process, wait for it to finish, and then return its standard output as a string?
Kinda like backtics in Perl.
Not looking for a cross platform thing. I just need the quickest solution for VC++.
Any ideas?
| WinAPI solution:
You have to create process (see CreateProcess) with redirected input (hStdInput field in STARTUPINFO structure) and output (hStdOutput) to your pipes (see CreatePipe), and then just read from the pipe (see ReadFile).
|
1,184,599 | 1,250,722 | How to correctly configure netbeans 6.7 and c++ on windows? | I have installed and configured NetBeans 6.7 for c++ according to the official manual:
http://www.netbeans.org/community/releases/67/cpp-setup-instructions.html#mingw
Configuration window looks like this:
Unfortunately, at 'compile' command following line is displayed:
/usr/bin/make -f nbproject/Makefile-Debug.mk SUBPROJECTS= .build-conf
BUILD SUCCESSFUL (total time: 642ms)
Since i'm on windows and it's no /usr/bin/make, no executable is compiled :(. How to correctly configure NetBeans so it will use make from it's config, not from /usr/bin?
Updated
Problem is only with mingw/msys toolchain. It works OK with cygwin (same /usr/bin/make message is displayed, but executable IS created). So the question can be changed to: Can Netbeans 6.7 work with mingw on Windows, or i'm limited to cygwin?
| I had problems getting Netbeans 6.7.1/C++/MinGW working too. I don't know if this will help but I thought I'd describe my experience anyway.
I was having successful builds but Netbeans was unable to launch my executable. I was able to verify that the executable was being built and I could run it from an external command prompt. I was also unable to open the properties on my project.
After a day of searching the net, I found a tidbit of info that lead to the solution.
Basically, it all boiled down to not having the path to my build tools set in the windows environment path. After I set the path environment variable, I cleared all the Netbeans configuration so I could be sure about setting things up from scratch. You can do this by deleting the .netbeans folder in your user directory in c:/Documents and Settings.
That should all be done with Netbeans closed of course. Afterwards, start it up and setup your build configuration before you create any projects or load existing projects. Go to Tools/Options/C++ and point it at the build tools directory you added to your environment path (c:/MinGW/bin and c:/msys/1.0/bin) and the individual tools as required.
I have my msys stuff in the same directory as the MinGW stuff. As an extra precaution, you may want to make sure there are no same named programs in both bin directories that may cause grief.
I seem to have a C++ development environment now that I'm quite pleased with as I can use it in Windows and Linux. Hope something in there helps.
|
1,184,777 | 1,185,032 | DLLs and STLs and static data (oh my!) | OK..... I've done all the reading on related questions, and a few MSDN articles, and about a day's worth of googling.
What's the current "state of the art" answer to this question:
I'm using VS 2008, C++ unmanaged code. I have a solution file with quite a few DLLs and quite a few EXEs. As long as I completely control the build environment, such that all pieces and parts are built with the same flags, and use the same runtime libaries, and no one has a statically linked CRT library, am I ok to pass STL objects around?
It seems like this should be OK, but depending on which article you read, there's lots of Fear, Uncertainty, and Doubt.
I know there's all sorts of problems with templates that produce static data behind the scenes (every dll would get their own copy, leading to heartache), but what about regular old STL?
| We successfully pass STL objects around in our application which is made up from dozens of DLLs. To ensure it works one of our automated tests that runs at every build is to verify the settings for all projects. If you add a new project and misconfigure it, or break the configuration of an existing project, the build fails.
The settings we check are as follows. Note not all of these will cause issues, but we check them for consistency.
#defines
_WIN32_WINNT
STRICT
_WIN32_IE
NDEBUG
_DEBUG
_SECURE_SCL
Compiler options
DebugInformationFormat
WholeProgramOptimization
RuntimeLibrary
|
1,185,252 | 1,385,520 | Is there a way to access the underlying container of STL container adaptors? | Is there a standard way to access the underlying container of stack, queue, priority_queue ?
I found a method called : _Get_container() in VS2008 implementation of stack and queue, but no one for priority_queue! I think it is not standard anyway.
Also, I know it is a silly question! where can I find official documentation of the standard library ?
Just for clarification, I wasn't trying to mess up with the underlying container. All what I was trying to do is this :
template <class Container>
std::ostream& printOneValueContainer(std::ostream& outputstream, Container& container)
{
Container::const_iterator beg = container.begin();
outputstream << "[";
while(beg != container.end())
{
outputstream << " " << *beg++;
}
outputstream << " ]";
return outputstream;
}
// stack, queue
template
< class Type
, template<class Type, class Container = std::deque<Type> > class Adapter
>
std::ostream& operator<<(std::ostream& outputstream, const Adapter<Type>& adapter)
{
return printOneValueContainer(outputstream, adapter._Get_container());
}
.
.
.
std::stack<int> iStack;
.
.
std::cout << iStack << std::endl;
I hope you see that _Get_container() is not standard, and there is no one for priority_queue in VS2008 implementation.
| I spotted the following solution somewhere on the web and I'm using it in my projects:
template <class T, class S, class C>
S& Container(priority_queue<T, S, C>& q) {
struct HackedQueue : private priority_queue<T, S, C> {
static S& Container(priority_queue<T, S, C>& q) {
return q.*&HackedQueue::c;
}
};
return HackedQueue::Container(q);
}
int main()
{
priority_queue<SomeClass> pq;
vector<SomeClass> &tasks = Container(pq);
return 0;
}
Have fun :).
|
1,185,320 | 1,185,357 | Should we be teaching beginners to use a global namespace? | NOTE: I am pretty much a beginner myself. This question concentrates on C++ usage, since that is the only language I have experience with.
There seems to be a consensus on Stack Overflow to use using namespace std; in the code examples provided for C++. I originally learned it this way, and was never taught WHY this is a problem later on.
I was just wondering why people have a problem with using the prefix std:: in their example code. It seems capricious to declare a global namespace, especially since many of the questioners copy+paste the code from the example to their IDE. Namespaces are an advanced programming concept, but I think it would be best to prefix std:: and then explain later if beginners ask about it.
Why is it acceptable to teach beginners this usage?
| I think the answer is "it doesn't really matter". It's a subtlety that's fairly easy to pick up and correct later.
Every beginners' programming text I know of makes a lot of simplifications and uses a lot of handwaving to hide a lot of what's going on ("this line is magic. Just type it in, and we'll discuss what it does later").
Beginners have enough to worry about without having to fully understand everything in their code, and how/why it is bad, so often these simplifications are good things.
Although in this case I kind of agree with you.
Adding the std:: prefix wouldn't be a big deal, and it would demystify namespaces quite a bit. using namespace std is actually much harder to explain and understand properly.
On the other hand, it takes up space and adds noise to the code which should be as concise and clear as possible.
|
1,185,365 | 1,185,398 | Reading parts of a line (getline()) | Basically this program searches a .txt file for a word and if it finds it, it prints the line and the line number. Here is what I have so far.
Code:
#include "std_lib_facilities.h"
int main()
{
string findword;
cout << "Enter word to search for.\n";
cin >> findword;
char filename[20];
cout << "Enter file to search in.\n";
cin >> filename;
ifstream ist(filename);
string line;
string word;
int linecounter = 1;
while(getline(ist, line))
{
if(line.find(findword) != string::npos){
cout << line << " " << linecounter << endl;}
++linecounter;
}
keep_window_open();
}
Solved.
| You're looking for find:
if (line.find(findword) != string::npos) { ... }
|
1,185,367 | 1,185,432 | Generating a 3D GUI through CGI | I'm implementing a web application that is written in C++ using CGI.
Is it possible to use a 3D drawn GUI that also has animations?
Should I just include some kind of mechanism that generates animated gifs and uses an image map?
Is there another, more elegant way of doing this?
EDIT:
So it sums up to Java or Silverlight or Flash 10.
Is Flash 10 common already?
If not is Java a better choice since it's more wide spread?
| First: from some of your comments, it appears you're not planning to actually use your web application in a browser. If I'm wrong, see below. If I'm right, then you're perfectly fine to write whatever UI you want using whatever technology you want and connect to your web application via that UI program. There are issues you'll have to deal with: what platform, what technology, etc. But you'll have no problems connecting to your web application using such a UI; just follow the HTTP protocols in your socket programming or use a framework that does it for you.
That said, if you're planning to do 3d in-browser, you should look into the Google O3D API. It's a browser plugin, but it should give you everything you need to do 3d in-browser using the GPU rather than software rendering like Flash and Silverlight do.
If you're not willing to use a browser plugin and you're not trying to do your own UI program, then your only other option is to use Canvas and Chrome Experiments as @Kitsune has suggested.
|
1,185,385 | 1,185,402 | working with string arrays in c++ | I wanna create a list of 50 elements which consist of four chars each. Every four char string should go into a loop one by one and get checked for one of three letters (o, a, e) anywhere in the current string. dependent on whether or not these letters are identified different commands are executed
I tried all day im frustrated please help me....
| typedef std::list<std::string> MyList;
MyList myList = getMyList();
MyList::const_iterator i = myList.begin(), iEnd = myList.end();
for (; i != iEnd; ++i) {
const std::string& fourChars = *i;
if (fourChars.length() == 4) {
std::string::const_iterator j = fourChars.begin(),
jEnd = fourChars.end();
for (; j != jEnd; ++j) {
char c = *j;
switch (c) {
case 'o': case 'O': doO(); break;
case 'a': case 'A': doA(); break;
case 'e': case 'E': doE(); break;
default: // not oae
}
}
}
else {
// not 4 chars, what should we do?
}
}
|
1,185,426 | 1,185,930 | I need help on how to rotate an image with OpenGL using SDL | I'm making a game and the arm of the character will be constantly rotating since it will be following the mouse cursor. I've never worked with openGL before and I need some help getting started. If anyone knows any good websites to start learning and one that specifically contains rotation, please let me know.
I've already visited NeHe and went to that rotation tutorial but after attempting to go through the other basic tutorials, it still seems very confusing to me, so some clarification on the topic would also be appreciated.
Also, I don't know if this would change things, but I need to rotate about the player's "shoulder," so I need to know how to make the arm rotate about this point.
| Use glTranslate to move the origin of your coordinate system and glRotate to rotate around this origin. Anyway, you should probably get a book about the basics of computer graphics.
If you are serious about this, go for 3d computer graphics by Alan Watt.
|
1,185,464 | 1,185,509 | What's the idiomatic way to traverse a boost::mpl::list? | Edit: I've edited the sample to better resemble the problem I have, now the function depends on a regular parameter (and not only on template parameters) which means that the computations can't be made at compile time.
I wrote some code with a hand written typelist and now we've started using boost and I'm trying to move it to the mpl library.
I can't seem to find any decent documentation for mpl::list and I'm even failing to port the code to boost::mpl. I've got the feeling that even when (if?) I do succeed in porting the code it will still not be idiomatic. Can' you please let me know how the following should be written with boost (note that this is not the actual code, it's a contrived simplification).
Original code (codepad.org paste)
class nil {};
template <class Head, class Tail = nil>
struct type_list {
typedef Head head;
typedef Tail tail;
};
template <class List>
struct foo;
template <class Head, class Tail>
struct foo<type_list<Head, Tail> >{
template <class T>
static void* bar(T* obj, size_t size)
{
if (sizeof(Head) == size)
return reinterpret_cast<Head*>(obj);
// Otherwise check the rest of the list
return foo<Tail>::bar(obj, size);
}
};
template <>
struct foo<nil>
{
template <class T>
static void* bar(T*, size_t) { return NULL; }
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<type_list<char, type_list<bool,
type_list<double, type_list<long> > > >
>::bar(&n, 4);
std::cout<< p << std::endl;
}
Failed Attempt to use Boost (codepad.org paste)
#include <boost/mpl/list.hpp>
template <class List>
struct foo{
template <class T>
static void* bar(T* obj, size_t size)
{
typedef typename boost::mpl::front<List>::type type;
if (sizeof(type) == size)
return reinterpret_cast<type*>(obj);
// Otherwise check the rest of the list
return foo<typename List::next>::bar(obj, size);
}
};
template <>
struct foo<boost::mpl::list0<boost::mpl::na> >
{
template <class T>
static void* bar(T*)
{
return NULL;
}
};
#include <iostream>
int main()
{
int n = 3;
void *p = foo<boost::mpl::list<char, bool, double, long> >::bar(&n, 4);
std::cout << p << std::endl;
}
| Use boost::mpl::fold like this:
#include <boost/mpl/list.hpp>
#include <boost/mpl/fold.hpp>
#include <iostream>
using namespace boost::mpl;
// Initial state:
struct foo_start {
template <typename T>
static void * bar( T *, size_t ) { return 0; }
};
// Folding Step: add This to Prev
template <typename Prev, typename This>
struct foo_iteration {
struct type {
template <typename T>
static void * bar( T * obj, size_t size ) {
if ( sizeof(This) == size )
return reinterpret_cast<This*>(obj);
else
return Prev::bar( obj, size );
}
};
};
// foo is just calling mpl::fold now:
template <typename List>
struct foo : fold< List, foo_start, foo_iteration<_,_> >::type {};
int main() {
int n = 3;
void * p = foo< list<char, bool, double, long> >::bar( &n, 4 );
std::cout << p << std::endl;
}
Prints 0 here, but then I'm on amd64, so I need to change the 4 to an 8, and get something non-zero.
HTH
|
1,185,689 | 1,185,705 | Avoiding memory leaks while mutating c-strings | For educational purposes, I am using cstrings in some test programs. I would like to shorten strings with a placeholder such as "...".
That is, "Quite a long string" will become "Quite a lo..." if my maximum length is set to 13. Further, I do not want to destroy the original string - the shortened string therefore has to be a copy.
The (static) method below is what I come up with. My question is: Should the class allocating memory for my shortened string also be responsible for freeing it?
What I do now is to store the returned string in a separate "user class" and defer freeing the memory to that user class.
const char* TextHelper::shortenWithPlaceholder(const char* text, size_t newSize) {
char* shortened = new char[newSize+1];
if (newSize <= 3) {
strncpy_s(shortened, newSize+1, ".", newSize);
}
else {
strncpy_s(shortened, newSize+1, text, newSize-3);
strncat_s(shortened, newSize+1, "...", 3);
}
return shortened;
}
| The standard approach of functions like this is to have the user pass in a char[] buffer. You see this in functions like sprintf(), for example, which take a destination buffer as a parameter. This allows the caller to be responsible for both allocating and freeing the memory, keeping the whole memory management issue in a single place.
|
1,185,702 | 1,197,155 | Direct3D9 Rendering a D3DFMT_A8 texture | I have a texture using the D3DFMT_A8 format. I want to render this as if the colour is white (ie the RGB components are all 255) and use the texture data for alpha blending.
I would like to do this without having to write a pixel shader if possible (as to work with existing shaders without changes, and also the fixed function pipeline).
I can get the alpha blending bit to work just like any other texture, however the RGB components are all treated as black, whereas I need them to be treated as white...
| Seems that color/alpha operations interprets the color component of D3DFMT_A8 textures as rgb(0,0,0).
So you have to select the color component from the material/vertex color and the alpha component from the alphamap:
_d3d9Device.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1)
_d3d9Device.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_CURRENT)
_d3d9Device.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1)
_d3d9Device.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE)
Then you can modulate the color texture:
_d3d9Device.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE )
_d3d9Device.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_CURRENT)
_d3d9Device.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_TEXTURE)
Of course, alpha blending must be enabled:
_d3d9Device.SetRenderState( D3DRS_ALPHATESTENABLE, False)
_d3d9Device.SetRenderState( D3DRS_ALPHABLENDENABLE, True)
_d3d9Device.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA)
_d3d9Device.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA)
|
1,185,878 | 1,185,907 | Can I use C++ features while extending Python? | The Python manual says that you can create modules for Python in both C and C++. Can you take advantage of things like classes and templates when using C++? Wouldn't it create incompatibilities with the rest of the libraries and with the interpreter?
| It doesn't matter whether your implementation of the hook functions is implemented in C or in C++. In fact, I've already seen some Python extensions which make active use of C++ templates and even the Boost library. No problem. :-)
|
1,186,017 | 1,186,051 | How do I build a graphical user interface in C++? | All of my C++ programs so far have been using the command line interface and the only other language I have experience with is PHP which doesn't support GUIs.
Where do I start with graphical user interface programming in C++? How do I create one?
| Essentially, an operating system's windowing system exposes some API calls that you can perform to do jobs like create a window, or put a button on the window. Basically, you get a suite of header files and you can call functions in those imported libraries, just like you'd do with stdlib and printf.
Each operating system comes with its own GUI toolkit, suite of header files, and API calls, and their own way of doing things. There are also cross platform toolkits like GTK, Qt, and wxWidgets that help you build programs that work anywhere. They achieve this by having the same API calls on each platform, but a different implementation for those API functions that call down to the native OS API calls.
One thing they'll all have in common, which will be different from a CLI program, is something called an event loop. The basic idea there is somewhat complicated, and difficult to compress, but in essence it means that not a hell of a lot is going in in your main class/main function, except:
check the event queue if there's any new events
if there is, dispatch those events to appropriate handlers
when you're done, yield control back to the operating system (usually with some kind of special "sleep" or "select" or "yield" function call)
then the yield function will return when the operating system is done, and you have another go around the loop.
There are plenty of resources about event-based programming. If you have any experience with JavaScript, it's the same basic idea, except that you, the scripter, have no access or control over the event loop itself, or what events there are, your only job is to write and register handlers.
You should keep in mind that GUI programming is incredibly complicated and difficult, in general. If you have the option, it's actually much easier to just integrate an embedded webserver into your program and have an HTML/web based interface. The one exception that I've encountered is Apple's Cocoa + Xcode + interface builder + tutorials that make it easily the most approachable environment for people new to GUI programming that I've seen.
|
1,186,131 | 1,188,902 | Unhandled Exceptions from Managed C# User Control used in MFC Dialog | Our core application is built in MFC C++, but we are trying to write new code in .NET, and have created a User Control in .NET, which will be used on an existing MFC Dialog.
However, when a unexpected/unhandled exception is thrown from the User Control, it causes the MFC app to crash (illegal op style), with no ability to recover.
I've added
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
To the Constructor of the .NET user control, but it doesn't seem to catch anything.
Is there any way to add an event in MFC to handle these?
Quick google didn't return anything useful.
Thanks.
Edit: Still haven't been able to resolve this the way I'd like, looks like the best way to do it, is try and catch around all the .NET code, so no exceptions bubble up.
| I asked this same question a while ago: Final managed exception handler in a mixed native/managed executable?
What I have found is that the managed unhandled exception events ONLY fire when running in a managed thread. The managed WndProc is where the magic happens.
You have a few options: you could place a low-level override in CWinApp and catch Exception^. This could have unintended side-effects. Or, you could go with Structured Exception Handling (SEH) which will give you a hack at /all/ unhandled exceptions. This is not an easy road.
|
1,186,379 | 1,187,126 | Detecting memory leaks in C++ Qt combine? | I have an application that interacts with external devices using serial communication. There are two versions of the device differing in their implementations.
-->One is developed and tested by my team
-->The other version by a different team.
Since the other team has left, our team is looking after it's maintenance. The other day while testing the application I noticed that the application takes up 60 Mb memory at startup and to my horror it's memory usage starts increasing with 200Kb chunks, in 60 hrs it shoots up to 295 Mb though there is no slow down in the responsiveness and usage of application. I tested it again and again and the same memory usage pattern is repeated.
The application is made in C++,Qt 4.2.1 on RHEL4.
I used mtrace to check for any memory leaks and it shows no such leaks. I then used valgrind memcheck tool, but the messages it gives are cryptic and not very conclusive, it shows leaks in graphical elements of Qt, which on scrutiny can be straightaway rejected.
I am in a fix as to what other tools/methodologies can be adopted to pinpoint the source of these memory leaks if any.
-->Also, in a larger context, how can we detect and debug presence of memory leaks in a C++ Qt application?
-->How can we check, how much memory a process uses in Linux?
I had used gnome-system-monitor and top command to check for memory used by the application, but I have heard that results given by above mentioned tools are not absolute.
EDIT:
I used ccmalloc for detecting memory leaks and this is the error report I got after I closed the application. During application execution, there were no error messages.
|ccmalloc report|
=======================================================
| total # of| allocated | deallocated | garbage |
+-----------+-------------+-------------+-------------+
| bytes| 387325257 | 386229435 | 1095822 |
+-----------+-------------+-------------+-------------+
|allocations| 1232496 | 1201351 | 31145 |
+-----------------------------------------------------+
| number of checks: 1 |
| number of counts: 2434332 |
| retrieving function names for addresses ... done. |
| reading file info from gdb ... done. |
| sorting by number of not reclaimed bytes ... done. |
| number of call chains: 3 |
| number of ignored call chains: 0 |
| number of reported call chains: 3 |
| number of internal call chains: 3 |
| number of library call chains: 1 |
=======================================================
|
| 3.1% = 33.6 KB of garbage allocated in 47 allocations
| |
| | 0x???????? in
| |
| | 0x081ef2b6 in
| | at src/wrapper.c:489
| |
| | 0x081ef169 in <_realloc>
| | at src/wrapper.c:435
| |
| `-----> 0x081ef05c in
| at src/wrapper.c:318
|
| 0.8% = 8722 Bytes of garbage allocated in 35 allocations
| |
| | 0x???????? in
| |
| | 0x081ef134 in
| | at src/wrapper.c:422
| |
| `-----> 0x081ef05c in
| at src/wrapper.c:318
|
| 0.1% = 1144 Bytes of garbage allocated in 5 allocations
| |
| | 0x???????? in
| |
| | 0x081ef1cb in
| | at src/wrapper.c:455
| |
| `-----> 0x081ef05c in
| at src/wrapper.c:318
|
`------------------------------------------------------
free(0x09cb650c) after reporting
(This can happen with static destructors.
When linking put `ccmalloc.o' at the end (for gcc) or
in front of the list of object files.)
free(0x09cb68f4) after reporting
free(0x09cb68a4) after reporting
free(0x09cb6834) after reporting
free(0x09cb6814) after reporting
free(0x09cb67a4) after reporting
free(0x09cb6784) after reporting
free(0x09cb66cc) after reporting
free(0x09cb66ac) after reporting
free(0x09cb65e4) after reporting
free(0x09cb65c4) after reporting
free(0x09cb653c) after reporting
ccmalloc_report() called in non valid state
I have no clue, what this means, it doesn't seem to indicate any memory leaks to me? I may be wrong. Does anyone of you have come across such a scenario?
link|edit|delete
| Valgrind can be a bitch if you don't really read the manuals or whatever documentation is actually available (man page for starters) - but they are worth it.
Basicly, you could start by running the valgrind on your application with --gen-suppressions=all and then create a suppressions for each block that is originating from QT itself and then use the suppression file to block those errors and you should be left with only with errors in your own code.
Also, you could try to use valgrind thru a alleyoop frontend if that makes things easier for you.
There are also bunch of other tools that can be used to detect memory leaks and Linux Journal has article about those here: http://www.linuxjournal.com/article/6556
And last, in some cases, some static analysis tools can spot memory errors too..
|
1,186,552 | 1,186,830 | Deferred Shading DirectX demos? | I've been reading a lot about deferred shading and want to try and get into it. Problem is I can't find a sample which demonstrates how deferred shading can support so many lights simultaneously - I found one demo which was very simple with a single light in Code Sampler and an nVidia HDR sample butnothing beyond that.
Would anyone know where I should go for a good introductory tutorial (with code) on how to have deffered shading with lighting? I can make it work with one light but one light is a bit too simple (rather obviously :P). Also I only know how to make directional lights in deferred shading code and it's nice an dall but somewhat different to regular ways of rendering lights so I was wondering if there wree tutorials or anything I could find or just reading material that would help me figure out how writing shaders and special fx in deferred rendering works?
Thanks fo rany help!
| NVIDIA stuff is usually good: http://developer.nvidia.com/object/6800_leagues_deferred_shading.html
Here's a reasonable XNA tutorial as well: http://www.ziggyware.com/readarticle.php?article_id=155
In terms of blogs: Wolfgang Engel's is a good start, and Christer Ericson recently posted a bunch of links (in the Graphics section of his "Catching Up Part 2" post).
Oh, and the G-Buffer paper is required reading too. Less practical, but a good review of the process and rationale.
|
1,187,157 | 1,187,310 | DirectX9 Texture of arbitrary size (non 2^n) | I'm relatively new to DirectX and have to work on an existing C++ DX9 application. The app does tracking on a camera images and displays some DirectDraw (ie. 2d) content. The camera has an aspect ratio of 4:3 (always) and the screen is undefined.
I want to load a texture and use this texture as a mask, so tracking and displaying of the content only are done within the masked area of the texture. Therefore I'd like to load a texture that has exactly the same size as the camera images.
I've done all steps to load the texture, but when I call GetDesc() the fields Width and Height of the D3DSURFACE_DESC struct are of the next bigger power-of-2 size. I do not care that the actual memory used for the texture is optimized for the graphics card but I did not find any way to get the dimensions of the original image file on the harddisk.
I do (and did, but with no success) search a possibility to load the image into the computers RAM only (graphicscard is not required) without adding a new dependency to the code. Otherwise I'd have to use OpenCV (which might anyway be a good idea when it comes to tracking), but at the moment I still try to avoid including OpenCV.
thanks for your hints,
Norbert
| D3DXCreateTextureFromFileEx with parameters 3 and 4 being
D3DX_DEFAULT_NONPOW2.
After that, you can use
D3DSURFACE_DESC Desc;
m_Sprite->GetLevelDesc(0, &Desc);
to fetch the height & width.
|
1,187,692 | 1,188,176 | How to detect when an exception is in flight? | In C++ (MSVC) how can I test whether an exception is currently "in flight". Ie, code which is being called as part of a class destructor may be getting invoked because an exception is unwinding the stack.. How can I detect this case as opposed to the normal case of a destructor being called due to a normal return?
| Actually it's possible to do this, call uncaught_exception() in <exception> header.
One reason you might want to do this is before throwing an exception in a destructor, which would lead to program termination if this destructor was called as part of stack unwinding.
See http://msdn.microsoft.com/en-us/library/k1atwat8%28VS.71%29.aspx
|
1,187,843 | 1,187,855 | Win32: Monitoring for files being created or changed | 1) How can I use FindFirstChangeNotification / FindNextChangeNotification + ReadDirectoryChanges to detect certain files being created or removed?
2) Is the FILE_NOTIFY_CHANGE_LAST_WRITE a reliable indicator of a file change?
Application: I have an explicit list of files that may be located in different folders. Display contents depends on the first file in the lsit that actually exists. For this, I want to add an auto-refresh mechanism.
Thus I need to detect "more important" files being created, the current file being changed or removed.
The list isn't long (maybe a dozen or so files), so I could poll the files, but for some applications the polling interval should be 50..80ms, ad I wonder if the monitoring API's are a better choice.
Response times should not exceed 200ms (not including any stalls due to unresponsive disks or high system load), but under ideal conditions, update should appear "immediate" to a human operator, without incurring high system load.
| The monitoring functions are a much better and cleanerr solution than polling, which itself would affect performance. But your response times cannot be guaranteed - Windows is not an RTS.
|
1,187,879 | 1,188,183 | Passing a C++ method to an Objective-C method | I have a C++ class 'Expression' with a method I'd like to use in my Objective-C class 'GraphVC'.
class Expression {
double evaluate(double);
}
And my Objective-C class:
@implementation GraphVC : UIViewController {
- (void)plot:(double(*)(double))f;
@end
I thought that it would be easiest to pass around function pointers that take a double and return a double, as opposed to C++ objects, but I haven't had much success using functional.h. What's the best way to use my C++ method from Objective-C?
EDIT: Thanks for your quick responses. Allow me to elaborate a bit... I have a backend written in C++ where I manipulate objects of type Expression. There's subclasses for rational, polynomial, monomial, etc. My initial idea was to use mem_fun from , but I wasn't able to get code compiling this way. I also had trouble using bind1st to bind the this pointer.
Writing an Objective-C wrapper is a possibility, but I'd rather use the already existing evaluate() function, and I don't want to break the clean separation between the backend and the iPhone GUI classes.
I can't have a global expression or use a static method (I need to plot arbitrary Expression instances.
I should have more explicitly stated that I need to pass a C++ member function (not a static function or existing C function) to an Objective-C object. Has anyone had luck using C++'s <functional> to turn member functions into pointers I can use in an Objective-C object, or should I use an Objective-C wrapper?
| If you want to make a pointer to a method in C++, you need to include the class name, like this:
class Foo
{
public:
double bar(double d)
{
return d;
}
};
void call_using_obj_and_method(Foo *f, double (Foo::*m)(double d))
{
(f->*m)(3.0);
}
int main()
{
Foo f;
call_using_obj_and_method(&f, &Foo::bar);
return 0;
}
Note that you need an instance of the class as well. In my example this is another parameter, though you could let it be a global variable, or a singleton instance of class Foo.
Though, like jkp said, you can also solve the problem by making the method static or turning it into a regular function.
EDIT: I'm not sure if I understand your question correctly. I don't think you need to use functional. Here is how my example would look in Objective-C++:
#include <Cocoa/Cocoa.h>
class Foo
{
public:
double bar(double d)
{
return d;
}
};
typedef double (Foo::*fooMethodPtr)(double d);
@interface Baz : NSObject
{
}
- (void)callFooObj:(Foo *)f method:(fooMethodPtr)m;
@end
@implementation Baz
- (void)callFooObj:(Foo *)f method:(fooMethodPtr)m
{
(f->*m)(3.0);
}
@end
int main()
{
Foo f;
Baz *b = [[Baz alloc] init];
[b callFooObj:&f method:&Foo::bar];
return 0;
}
|
1,187,907 | 1,188,032 | Why do some of my keyboard events work and others do not? | I have the following examples in c++, the first works as expected the second does not. I also note that the Windows System keyboard has the same problem. Anybody know why or a work around/better way of doing this?
keybd_event(VK_LWIN,0x5b,0 , 0); /* Windows Key Press */
keybd_event(VkKeyScan('l'), 0, 0, 0); /* L key Press */
keybd_event(VkKeyScan('l'), 0, KEYEVENTF_KEYUP,0); /* L key Release */
keybd_event(VK_LWIN,0x5b,KEYEVENTF_KEYUP,0); /* Windows Key Release */
This one fails:
keybd_event(VK_CONTROL,0x11,0 , 0); /* Control Key Press */
keybd_event(VK_MENU,0xb8, 0, 0); /* Alt Press */
keybd_event(VK_DELETE,0x2e, 0, 0); /* Del Press */
keybd_event(VK_DELETE,0x2e, KEYEVENTF_KEYUP,0); /* Del Release */
keybd_event(VK_MENU,0xb8, KEYEVENTF_KEYUP,0); /* Alt Release */
keybd_event(VK_CONTROL,0x11,KEYEVENTF_KEYUP,0); /* Control Key Release */
| It's probable that that particular combination is protected by the system. Windows has this feature where you can set so that it asks you to press Crtl+Alt+Del before you can enter your username and password to log in. I remember reading somewhere that that feature is to make sure it's a real person entering the credentials and not a malicious program.
|
1,188,133 | 1,188,197 | Create a background process with system tray icon | I'm trying to make a Windows app that checks some things in the background, and inform the user via a systray icon.
The app is made with Not managed C++ and there is no option to switch to .net or Java.
If the user wants to stop the app, he will use the tray icon.
The app can't be a Service because of the systray side and because it must run without installing anything on the user computer ( it's a single .exe )
Using the typical Win32 program structure ( RegisterClass, WndProc and so on ) i dont know how can i place some code to run apart the window message loop.
Maybe i have to use CreateProcess() or CreateThread()? Is It the correct way to handle the Multithreading environment?
If i have to use CreateProcess()/CreateThread(), how can i comunicate between the two threads?
Thanks ;)
| As for the system tray icon, you'll need Shell_NotifyIcon.
See http://msdn.microsoft.com/en-us/library/bb762159.aspx
|
1,188,243 | 1,188,255 | Destructor that calls a function that can throw exception in C++ | I know that I shouldn't throw exceptions from a destructor.
If my destructor calls a function that can throw an exception, is it OK if I catch it in the destructor and don't throw it further? Or can it cause abort anyway and I shouldn't call such functions from a destructor at all?
| Yes, that's legal. An exception must not escape from the destructor, but whatever happens inside the destructor, or in functions it calls, is up to you.
(Technically, an exception can escape from a destructor call as well. If that happens during stack unwinding because another exception was thrown, std::terminate is called. So it is well-defined by the standard, but it's a really bad idea.)
|
1,188,335 | 1,188,469 | Why default return value of main is 0 and not EXIT_SUCCESS? | The ISO 1998 c++ standard specifies that not explicitly using a return statement in the main is equivalent to use return 0.
But what if an implementation has a different standard "no error" code, for example -1?
Why not use the standard macro EXIT_SUCCESS that would be replaced either by 0 or -1 or any other value depending on the implementation?
C++ seems to force the semantic of the program, which is not the role of a language which should only describe how the program behaves. Moreover the situation is different for the "error" return value: only EXIT_FAILURE is a standard "error" termination flag, with no explicit value, like "1" for example.
What are the reasons of these choices?
| Returning zero from main() does essentially the same as what you're asking. Returning zero from main() does not have to return zero to the host environment.
From the C90/C99/C++98 standard document:
If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.
|
1,188,939 | 1,188,950 | Representing 128-bit numbers in C++ | What's the best way to represent a 128-bit number in C++? It should behave as closely to the built-in numeric types as possible (i.e. support all the arithmetic operators, etc).
I was thinking of building a class that had 2 64 bit or 4 32 bit numbers. Or possibly just creating a 128 bit block of memory and doing everything myself.
Is there some easier/more standard way, or something that I'm less likely to screw up when implementing it myself? :)
It would also be nice if it could be extended to 256-bit, 512-bit, etc...
| Look into other libraries that have been developed. Lots of people have wanted to do this before you. :D
Try bigint C++
|
1,188,978 | 1,189,158 | extracting compressed file with boost::iostreams | I'm searching for a way to extract a file in c++ by using the boost::iostreams classes.
There is an example in the boost documentation. But it outputs the content of the compressed file to std::cout.
I'm looking for a way to extract it to a file structure.
Does anybody know how to do that?
Thanks!
| Boost.IOStreams does not support compressed archives, just single compressed files. If you want to extract a .zip or .tar file to a directory tree, you'll need to use a different library.
|
1,189,084 | 1,189,550 | What's the C++ GUI building option with the easiest learning curve - VS/Qt/wxWidgets/etc.? | I'm looking to be able to build GUI applications quickly and painlessly as possible. I'm competent (though not expert, and have no formal training) in C++, but have never used a GUI building toolkit or framework or anything. I am not a professional programmer and am totally inexperienced and ignorant when it comes to building GUI apps. Have spent hours researching trying to figure out what to do; only getting more confused and discouraged though.
Qt and wxWidgets seem like the most popular options for cross-platform apps, though cross-platform isn't necessarily all that important to me; Windows-only is fine if that means the fastest learning curve.
Qt seems cool and the Qt Creator is sweet looking with lots of good demos, except it has its own classes for everything, and I'm not overly keen on learning a bunch of stuff that's only applicable to the Qt platform itself rather than more generally. I suppose I could avoid using the Qt classes except for the GUI stuff where I have to use them, but I have no idea how wise or unwise that would be.
I was thinking Visual Studio would have the smallest learning curve, but when I open a test GUI app, I see a bunch of foreign looking stuff like carats (^) all over the place - I found online that these mean "handles", which I have trouble even understanding the definition or purpose of ("sort of like pointers but not really" is basically how I've read people define them).
I know pretty much nothing about wxWidgets, or how it compares with Qt.
So every option has a big learning curve - and ideally I'd like to know which one minimizes the time you have to spend learning the toolkit/framework itself. Since I'm likely never going to be making money from the programs I create, the time I spend learning a specific toolkit would be pretty costly. I just want to be able to make a functional program using the C++ knowledge I have, but in GUI form. At the moment it seems if I want to make a GUI app, I'd have to spend way more time learning the GUI framework I'd use than writing the functional part of the app itself.
Any input from people wiser and more experienced than me would be appreciated :)
| First and foremost, start simple. There's a lot to the subject. If you are finding it hard, don't try and take it in all at once.
Most of the good GUI packages have tutorials. The best advice I can give is that you try each of them, or at least a couple of them. They are the best short introduction you can have to the library you choose and if they are any good they narrow down what you need to absorb at first. That will give you some basis for comparison, because they are each trying to do very similar things (and you will see some of them before you are done), but they have different feels. You will likely find you have a preference for one and that's the one to get serious with. It will also give you a sense of what's hard about GUI programming as separate from the particulars of one package, which, if you have only used one, you won't have seen. Personally I find this sort of knowledge very helpful, because it makes me less intimidated by particulars.
Here's a list of tutorials in one place, though you have likely seen them already:
Qt's tutorial
WxWidgets' tutorial
Gtkmm book. Not quite a tutorial, though there are lots of examples.
.NET tutorials, either for WinForms or for WPF.
Second, it sounds to me that you need to get some in depth understanding of the concepts of GUI programming, not just a particular library. Here there is no substitute for a book. I don't know all of them by a long shot, but the best of the bunch will not just teach you the details of a toolkit, they will teach you general concepts and how to use them. Here are some lists to start with though (and once you have titles, Amazon and Stack Overflow will help to pick one):
List of Qt books
WxWidgets book (PDF version)
There are tons of WPF and WinForms books. I can't make a good recommendation here unfortunately.
Third, take advantage of the design tools (Qt Creator, VS's form building and so on). Don't start by trying to read through all the code they generate: get your own small programs running first. Otherwise it's too hard to know what matters for a basic program and what doesn't. The details get lost. Once you've got the basics down though, Do use them as references to learn how to do specific effects. If you can get something to work in the design tools, then you can look at particular code they generate to be able to try on your own hand-written programs. They are very useful for intermediate learning.
I'm not overly keen on learning a bunch of stuff that's only applicable to the Qt platform itself rather than more generally.
I second the comment of GRB here: Don't worry about this. You are going to need to learn a lot specific to the toolkit no matter which toolkit you use. But you will also learn a lot that's general to GUI programming with any of the decent toolkits, because they are going to have to cover a lot of the same ground. Layouts, events, interaction between widgets/controls, understanding timers -- these will come up in any GUI toolkit you use.
However do be aware that any serious GUI package is an investment of time. You will have a much easier time learning a second package if you decide to pick one up, but every large library has its personality and much of your time will be spent learning its quirks. That is, I think, a given in dealing with any complex subject.
I suppose I could avoid using the Qt classes except for the GUI stuff where I have to use them, but I have no idea how wise or unwise that would be.
You do not need most of the non-GUI classes of Qt to use Qt's GUI properly. There are a handful of exceptions (like QVariant) which you'll need just because the GUI classes use them. I found you can learn those on a case-by-case basis.
|
1,189,097 | 1,189,168 | C++ interpreter / console / snippet compiler | I am looking for a program where I can enter a C++ code snippet
in one window, press a button, and get output in another window.
Compilation should somehow be hidden behind the button. On a
per-snippet basis would be fine, full interactive probably asking
too much. It should run under Linux/Unix. Main use case would be
learning/testing/short debugging, etc.
Related stuff I found:
-- the Reinteract project for python (which i'm told sage has features similar to)
-- the same thread for C# here: C# Console?
-- the CINT interpreter from the CERN ROOT project
(which may be close, but maybe there are more comfortable apps around)
-- some programs called Quickly Compile or Code Snippet, which are M$.
| http://codepad.org/ works nicely for this purpose. By default, it will run what you paste when you hit submit and display the result (or any errors you might have).
|
1,189,687 | 1,189,741 | Solving our versioning and build problems | Where I work we need to rethink the way we develop software and keep track of each released version. Do you have any suggestions to solve our problems?
We develop on Windows in C++ using VS 2005 (and C++ Builder for some interface stuff)
We use GIT but in the worse possible way imaginable. We are somewhat open to move to another source control.
We have 40+ in-house developed DLL. Many of those can be updated frequently.
We have a few dramatically different projects that depend on those DLL.
We deliver 100+ systems a year, each of those requires custom configuration. The majority also requires custom patches. We try as much as we can to bring those patches back into the main trunk but forks are inevitable.
If a few years down the road we have to update a client's system, we should be able to get back the code used for that release and all the environment parameters. We need a way to validate that this code match the binaries on the client's system. Getting back the code should be as trivial as possible and maybe with the exception of the compiler we should have everything needed to compile by doing a few simple operations.
A programmer should be able to release an update for a client's system without depending on any other programmer no matter in what project (DLL) the patch is. He should be able to do it rapidly (less than 30 minutes). That make the concept of a single official release almost impossible.
Exchanging code between developer working on the same project should be easy and fast.
Considering our huge code base we want to limit how much a developer has to recompile when he gets a patch (sharing the binaries is a must).
A developer should be able to switch from one client's system release or branch to another easily (it's common to have to work on more than one release at the same time).
Edit:
-We don't use makefile so far but that's something we are willing to consider. Everything is built using VS solutions.
| Git in itself is perfectly suited for having a multitude of branches of source code. However, the maintenance of those branches will always reside at the user and lies outside the scope of a given version control system.
The only problem with Git is that it does not scale well for tracking compiled binary data over time. Binary data is mostly use-once and the diff/patch aspect which is important for source code is not important for compiled binary data. Instead, just create a .zip file for each source code version in Git containing a pre-compiled version of each DLL and put those .zip files on a network share.
If you've done that, it sounds like you should invest time into your build system to be efficient. The version system can help here, but you're probably running into build problems anyways:
Your Build System should only compile DLLs when the source has changed or the DLLs on which it depends has its interface changed. How tricky this is depends on the language used: C# DLLs have quite a strict interface which make this quite easy, while C has not an interface to speak of (just add one #define to a source file, and everything might have to be compiled)
Your Build System should reuse pre-compiled DLLs which should be stored somewhere. Preferably not in the same way as the source code since Git is not optimized for this.
Your Build System should cope branch changed OK. For example, Visual Studio leaves some files behind and does not always detect properly when a full rebuild has to be done.
Your Build System might have to use a compiler from a fixed location instead of the compiler-of-the-day installed on your developpers PC. You might want to put it under version control also, or at least make this dependency explicit.
In the end we rolled our own build system which was limited in speed by the time to do a stat() of all the files involved when nothing was changed. However, this took some time to build. Things to consider when building a system your own:
First construct a dependency graph: DLLs depends on its source files and other DLLs.
Use the modification times (mtime) of the files as a kind of 'version' of a file. Keep a cache of those mtimes, and consider a change in mtime a reason to update your cache.
When one mtime of a file has changed, you have to rebuild the DLL it belongs to. After a rebuld of the DLL, check whether the interface has changed. If the interface has changed, rebuild all the DLLs which depend on this one. This takes a graph traversal to only process DLLs once.
Bonus for making the compile run in parallel. Since you know your dependency graph, you also know which DLLs can be build in parallel.
And the good thing is that this is all version control system independent, so it's not wasted time. It might even be that a simple approximation is enough to be able to do it <30 minutes. It depends.
|
1,189,832 | 1,189,871 | Hide a file or directory using the Windows API from C | I want to modify a C program to make some of the files it creates hidden in Windows. What Windows or (even better) POSIX API will set the hidden file attribute?
| You can do it by calling SetFileAttributes and setting the FILE_ATTRIBUTE_HIDDEN flag. See http://msdn.microsoft.com/en-us/library/aa365535%28VS.85%29.aspx
This is not POSIX though. To create a 'hidden' file under a normal POSIX system like Linux, just start a filename with a dot (.).
|
1,190,017 | 1,190,329 | Should I use vcredist.exe or the msm's to install the Visual C++ runtime library | What are the pluses and minuses to using the vcredist.exe versus the msm files to install the Visual C++ 8.0 runtime libraries?
| MSM will give you a better streamline experience then vcredist, it will integrate with the progress bar and will rollback on error (or cancel).
From the developer side you will benefit by seeing the msm log in the main setup log file and it will execute its actions side by side with the setup action (with vcredist you will need to sequence it yourself).
Because of all of the above reasons I usually choose to use the msm (and its more or less one Wix liner to use it).
|
1,190,062 | 1,190,317 | Passing an operator along with other parameters | I have some VERY inefficient code in which many lines appear 4 times as I go through permutations with "<" and ">" operations and a variety of variables and constants. It would seem that there is a way to write the function once and pass in the operators along with the necessarily changing values and"ref" variables. What technique do I have to learn? "Delegates" have been suggested but I don't see how to use them in this manner. This is in C# 2.0, VS2005, but if the technique is generic and can be used with C++ too, that would be great.
Request for some code: The following appears in many guises, with different "<" and ">" signs as well as a mix of "+" and "-" signs:
if (move[check].Ypos - move[check].height / 200.0D < LayoutManager.VISIO_HEIGHT - lcac_c.top)
{
move[check].Ypos = move[check].Ypos + adjust;
.
.
.
| In C++, use the std::less and std::greater functors. Both of these methods inherit std::binary_function, so your generic function should accept instances of this type.
In .NET, the equivalent to std::binary_function is Func<T, U, R>. There are no equivalents to std::less and std::greater, but it is fairly trivial to create them. See the following example.
static class Functor
{
static Func<T, T, bool> Greater<T>()
where T : IComparable<T>
{
return delegate(T lhs, T rhs) { return lhs.CompareTo(rhs) > 0; };
}
static Func<T, T, bool> Less<T>()
where T : IComparable<T>
{
return delegate(T lhs, T rhs) { return lhs.CompareTo(rhs) < 0; };
}
}
Note, the above code uses the Func<> class from .NET 3.5. If this is not acceptable, consider defining you own delegate.
C++ invocation example:
void DoWork(const std::binary_function<int, int, bool>& myOperator,
int arg1, int arg2)
{
if (myOperator(arg1, arg2)) { /* perform rest of work */ }
}
void main()
{
DoWork(std::less<int>(), 100, 200);
DoWork(std::greater<int>(), 100, 200);
}
C# invocation example:
void DoWork(Func<int, int, bool> myOperator, int arg1, int arg2)
{
if (myOperator(arg1, arg2)) { /* perform rest of work */ }
}
void main()
{
DoWork(Functor.Less<int>(), 100, 200);
DoWork(Functor.Greater<int>(), 100, 200);
}
EDIT: I corrected the example of the functor class as applying < or > operators to a generic type doesn't work (in the same manner as it does with C++ templates).
|
1,190,064 | 1,190,090 | Is there a non-named pipes in windows api? | Posix provided both named and non-named pipes... Can you have a non-named pipes and windows and how to use them?
| Yes. They are called "Anonymous Pipes" in the Windows API documentation. For more details, see MSDN.
|
1,190,112 | 1,190,275 | Comparing default-constructed iterators with operator== | Does the C++ Standard say I should be able to compare two default-constructed STL iterators for equality? Are default-constructed iterators equality-comparable?
I want the following, using std::list for example:
void foo(const std::list<int>::iterator iter) {
if (iter == std::list<int>::iterator()) {
// Something
}
}
std::list<int>::iterator i;
foo(i);
What I want here is something like a NULL value for iterators, but I'm not sure if it's legal. In the STL implementation included with Visual Studio 2008, they include assertions in std::list's operator==() that preclude this usage. (They check that each iterator is "owned" by the same container and default-constructed iterators have no container.) This would hint that it's not legal, or perhaps that they're being over-zealous.
| OK, I'll take a stab. The C++ Standard, Section 24.1/5:
Iterators can also have singular
values that are not associated with
any container. [Example: After the
declaration of an uninitialized
pointer x (as with int* x;), x must
always be assumed to have a singular
value of a pointer. ] Results of most
expressions are undefined for singular
values; the only excep- tion is an
assignment of a non-singular value to
an iterator that holds a singular
value.
So, no, they can't be compared.
|
1,190,184 | 1,190,300 | How to use anonymous pipes in windows api (and pass to gtk function)? | I need to be able to pass int value representing fd (pipe fd) to gtk function as a first parameter
gint gdk_input_add gint source,
GdkInputCondition condition,
GdkInputFunction function,
gpointer data);
How do I do that, as CreatePipe returns HANDLE which is NOT int?
Thanks
| To convert a HANDLE value to a C file descriptor, call _open_osfhandle.
|
1,190,194 | 1,203,254 | Strange Eclipse C++ #define behaviour | (A case of over relying on an IDE)
I have some legacy C code that I compile as C++ for the purpose of Unit testing. The C source is C++ aware in that it conditionally defines based on environment.
E.g. (PRIVATE resolves to static):
#if!defined __cplusplus
#define PRIVATE1 PRIVATE
#endif
...
PRIVATE1 const int some_var;
The problem is I just can't seem to find out what PRIVATE1 resolves to or is in C++, the compiler complains of redefinition if I add a declaration but doesn't indicate where?
I have searched my MinGW/gcc include path, the C++ ISO specification and the C++ books available to me has been to no avail.
Edit:
Sure I checked the command line and makefiles before posting.
| Eclipse C++ managed project's are a little, well stupid!
If a project is declared C++ it still bases it's build on file extension, hence .h file preprocessed as C and not C++ header which pulls in a #define PRIVATE1 from another header file similarly wrapped by:
#ifdef __cpluplus.
The project is then linked by g++.
|
1,190,603 | 1,190,621 | Assigning int x = 'abc' ; | I was doing a code review and I saw assignment of single quoted strings to enum values:
enum
{
Option_1 = 'a',
Option_2 = 'b'
} ;
While this makes for slightly more readable code (though the enum's meaning should be pretty much in the name of the num), it looks silly to me.
I didn't know you COULD do that and after studying it, I can see that all that happens is the binary value of the "characters" you're using gets thrown into an int.
Does anyone else do this in practice? Or is this a bad practice?
| It is definitely perfectly legal according to ISO C and C++ standards. And it is a fairly reasonable practice if those enum values are serialized to text (e.g. CSV) files as those characters. Otherwise, I don't see much point. I guess it could give some debugging benefits, but all good C/C++ debuggers I know can resolve enum values to corresponding symbols anyway.
|
1,191,041 | 1,192,339 | Hiding the dialog on startup for a system tray application | I'm writing an application in C++ that runs as a system tray icon. When the application initially starts up the main dialog loads up and takes focus, which isn't the behavior I intend it to have. Is there a way to load the system tray icon without having the main dialog load up?
| If you used the standard mfc project wizard, then the code that displays the dialog is in your applications's InitInstance method.
Just comment out the dlg.DoModal() and m_pMainWnd = &dlg; parts and you will be fine.
Note that you might have to code your own message loop otherwise your application will just exit after these changes.
|
1,191,093 | 1,191,098 | I'm seeing artifacts when I attempt to rotate an image | This is the before:
http://img22.imageshack.us/img22/5310/beforedes.jpg
znd after:
http://img189.imageshack.us/img189/8890/afterr.jpg
EDIT:: Now that I look at imageshack's upload, the artifacts are diminished a great deal.. but trust me, they are more pronounced than that.
I don't understand why this is happening. Imageshack uploads them to jpg, but in my program they are in the image folder as .tif (The reason for .tif is because I couldn't get ANY other image to maintain their transparent parts).
But anyways, these artifacts follow the original top of the image as it rotates anywhere except the original.
Here's part of my code that loads the image
GLuint texture;
GLenum texture_format;
GLint nofcolors;
GLfloat spin;
bool Game::loadImage()
{
SDL_Surface * surface; // this surface will tell us the details of the image
if ( surface = SM.load_image("Images/tri2.tif") )
{
//get number of channels in the SDL surface
nofcolors = surface->format->BytesPerPixel;
//contains an alpha channel
if ( nofcolors == 4 )
{
if ( surface->format->Rmask == 0x000000ff )
texture_format = GL_RGBA;
else texture_format = GL_BGRA;
}
else if ( nofcolors == 3 ) //no alpha channel
{
if ( surface->format->Rmask == 0x000000ff )
texture_format = GL_RGB;
else texture_format = GL_BGR;
}
// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );
// Bind the texture object
glBindTexture( GL_TEXTURE_2D, texture );
// Set the texture’s stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0, texture_format, GL_UNSIGNED_BYTE, surface->pixels );
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}
else
{
SDL_Quit();
return false;
}
// Free the SDL_Surface only if it was successfully created
if ( surface )
{
SDL_FreeSurface( surface );
return true;
}
else return false;
}
void Game::drawImage()
{
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );
glTranslatef( float(S_WIDTH/2), float(S_HEIGHT/2), 0.0f );
glRotatef( spin, 0.0, 0.0, 1.0 );
// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );
glBegin( GL_QUADS );
{
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( -64, 0, 0 );
// Top-right vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 64, 0, 0 );
// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 64, 128, 0 );
// Bottom-left vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( -64, 128, 0 );
}
glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}
| Looks like the texture is set to GL_WRAP. Try GL_CLAMP_TO_EDGE instead.
|
1,191,240 | 1,191,249 | Invalid conversion from const char to char - Vowel Removal | I'm trying to remove vowels from a text file and am having some trouble. I'm receiving a compiler error in line 6 saying
invalid conversion from const char to char
I'm pretty sure this has to do with the way I'm setting up the file stream in my code. I'm using fstream since it's used for reading and writing, but I didn't include any of the open modes because I thought I could write and read to/from the file without them (I'm pretty sure you have to use one, I'm just not sure which one.) Also, I'm not sure if the way I set up the equals operator is legal or not(will it read it as if s[i] is equal to a or e or i or o or u).
Code:
#include "std_lib_facilities.h"
void vowel_removal(string& s)
{
for(int i = 0; i < s.length(); ++i)
if(s[i] == ('a' || 'e' || 'i' || 'o' || 'u')) s[i] = " ";
}
int main()
{
cout << "Enter file name.\n";
string filename;
cin >> filename;
fstream f(filename.c_str());
string word;
while(f>>word){
vowel_removal(word);
f << word;
}
keep_window_open();
}
| I think you mean invalid conversion from const char * to char
When you index a string you must assign a char not another string:
std::string s = "tie";
s[0] = 'l';
assert(s == "lie");
//s[0] = "l"; <--- not valid const char * to char
Also you must have both a right hand side and a left hand side for each comparison. You can't apply one left hand side to multiple right hand sides in C++.
if(s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
s[i] = ' ';
|
1,191,248 | 1,191,274 | Handling stdafx.h in cross-platform code | I have a Visual Studio C++ based program that uses pre-compiled headers (stdafx.h). Now we are porting the application to Linux using gcc 4.x.
The question is how to handle pre-compiled header in both environments.
I've googled but can not come to a conclusion.
Obviously I want leave stdafx.h in Visual Studio since the code base is pretty big and pre-compiled headers boost compilation time.
But the question is what to do in Linux. This is what I found:
Leave the stdafx.h as is. gcc compiles code considerable faster than VC++ (or it is just my Linux machine is stronger ... :) ), so I maybe happy with this option.
Use approach from here - make stdafx.h look like (set USE_PRECOMPILED_HEADER for VS only):
#ifdef USE_PRECOMPILED_HEADER
... my stuff
#endif
Use the approach from here - compile VC++ with /FI to implicitly include stdafx.h in each cpp file. Therefore in VS your code can be switched easily to be compiled without pre-compiled headers and no code will have to be changed.
I personally dislike dependencies and the mess stdafx.h is pushing a big code base towards. Therefore the option is appealing to me - on Linux you don't have stdafx.h, while still being able to turn on pre-compiled headers on VS by /FI only.
On Linux compile stdafx.h only as a precompiled header (mimic Visual Studio)
Your opinion? Are there other approaches to treat the issue?
| You're best off using precompiled headers still for fastest compilation.
You can use precompiled headers in gcc as well. See here.
The compiled precompiled header will have an extension appended as .gch instead of .pch.
So for example if you precompile stdafx.h you will have a precompiled header that will be automatically searched for called stdafx.h.gch anytime you include stdafx.h
Example:
stdafx.h:
#include <string>
#include <stdio.h>
a.cpp:
#include "stdafx.h"
int main(int argc, char**argv)
{
std::string s = "Hi";
return 0;
}
Then compile as:
> g++ -c stdafx.h -o stdafx.h.gch
> g++ a.cpp
> ./a.out
Your compilation will work even if you remove stdafx.h after step 1.
|
1,191,340 | 1,191,372 | Converting C++ Builder code to C# .NET (TComponent, TOjbect, TList, etc.) | Where can I find API documentation for TComponent, TObject, TList, etc.? I am converting some C++ code that was written using C++ builder into C#. I'm having trouble finding related documentation for these classes in order to find a C# equivalent.
| Use the official online reference. The link is directly to the index - just look up types and functions there as needed.
|
1,191,349 | 1,191,440 | Why doesn't this change the .txt file? | I'm trying to edit a text file to remove the vowels from it and for some reason nothing happens to the text file. I think it may be because a mode argument needs to be passed in the filestream.
[SOLVED]
Code:
#include "std_lib_facilities.h"
bool isvowel(char s)
{
return (s == 'a' || s == 'e' || s =='i' || s == 'o' || s == 'u';)
}
void vowel_removal(string& s)
{
for(int i = 0; i < s.length(); ++i)
if(isvowel(s[i]))
s[i] = ' ';
}
int main()
{
vector<string>wordhold;
cout << "Enter file name.\n";
string filename;
cin >> filename;
ifstream f(filename.c_str());
string word;
while(f>>word) wordhold.push_back(word);
f.close();
ofstream out(filename.c_str(), ios::out);
for(int i = 0; i < wordhold.size(); ++i){
vowel_removal(wordhold[i]);
out << wordhold[i] << " ";}
keep_window_open();
}
| Reading and writing on the same stream results in an error. Check f.bad() and f.eof() after the loop terminates. I'm afraid that you have two choices:
Read and write to different files
Read the entire file into memory, close it, and overwrite the original
As Anders stated, you probably don't want to use operator<< for this since it will break everything up by whitespace. You probably want std::getline() to slurp in the lines. Pull them into a std::vector<std::string>, close the file, edit the vector, and overwrite the file.
Edit:
Anders was right on the money with his description. Think of a file as a byte stream. If you want to transform the file in place, try something like the following:
void
remove_vowel(char& ch) {
if (ch=='a' || ch=='e' || ch=='i' || ch =='o' || ch=='u') {
ch = ' ';
}
}
int
main() {
char const delim = '\n';
std::fstream::streampos start_of_line;
std::string buf;
std::fstream fs("file.txt");
start_of_line = fs.tellg();
while (std::getline(fs, buf, delim)) {
std::for_each(buf.begin(), buf.end(), &remove_vowel);
fs.seekg(start_of_line); // go back to the start and...
fs << buf << delim; // overwrite the line, then ...
start_of_line = fs.tellg(); // grab the next line start
}
return 0;
}
There are some small problems with this code like it won't work for MS-DOS style text files but you can probably figure out how to account for that if you have to.
|
1,191,525 | 1,192,133 | I can't get the transparency in my images to work | Stemming from this question of mine: I'm seeing artifacts when I attempt to rotate an image
In the source code there, I am loading a TIF because I can't for the life of me get any other image format to load the transparency parts correctly. I've tried PNG, GIF, & TGA. I'd would like to be able to load PNGs. I hope the source code given in the question above will be enough, if not, then let me know.
For a better description of what happens when I attempt to load some other format -- One of the images I was attempting was a 128*128 orange triangle. Depending on the format, it would either make the entire 128*128 square orange, or make the transparent parts of the image white.
| OK, I'm new at OpenGL + SDL but here is what I have.. Loads all? formats SDL_image supports except I can't get .xcf to work and don't have a .lbm to test with.
//called earlier..
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//load texture
SDL_Surface* tex = IMG_Load(file.c_str());
if (tex == 0) {
std::cout << "Could not load " << file << std::endl;
return false;
}
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
//nearest works but linear is best when scaled?
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
width = tex->w;
height = tex->h;
//IMG_is* doesn't seem to work right, esp for TGA, so use extension instead..
std::string ext = file.substr(file.length() - 4);
bool isBMP = (ext.compare(".bmp") == 0) || (ext.compare(".BMP") == 0);
bool isPNG = (ext.compare(".png") == 0) || (ext.compare(".PNG") == 0);
bool isTGA = (ext.compare(".tga") == 0) || (ext.compare(".TGA") == 0);
bool isTIF = ((ext.compare(".tif") == 0) || (ext.compare(".TIF") == 0) ||
(ext.compare("tiff") == 0) || (ext.compare("TIFF") == 0));
//default is RGBA but bmp and tga use BGR/A
GLenum format = GL_RGBA;
if(isBMP || isTGA)
format = (tex->format->BytesPerPixel == 4 ? GL_BGRA : GL_BGR);
//every image except png and bmp need to be converted
if (!(isPNG || isBMP || isTGA || isTIF)) {
SDL_Surface* fixedSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
SDL_BlitSurface(tex, 0, fixedSurface, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, format, GL_UNSIGNED_BYTE, fixedSurface->pixels);
SDL_FreeSurface(fixedSurface);
} else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, format, GL_UNSIGNED_BYTE, tex->pixels);
}
SDL_FreeSurface(tex);
list = glGenLists(1);
glNewList(list, GL_COMPILE);
GLint vertices[] = {
0,0, 0,0,
0,1, 0,height,
1,1, width,height,
1,0, width,0
};
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glBindTexture(GL_TEXTURE_2D, texture);
glTexCoordPointer(2, GL_INT, 4*sizeof(GLint), &vertices[0]);
glVertexPointer(2, GL_INT, 4*sizeof(GLint), &vertices[2]);
glDrawArrays(GL_POLYGON, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glEndList();
And then to draw I set the color to opaque white (doesn't affect transparency?) then just call the list..
glColor4f(1,1,1,1);
glCallList(list);
And of course, any help for my code would be much appreciated too! :)
|
1,191,944 | 1,191,977 | Is there a way to access the private parts of a different instantiation of the same class template? | In my continuing adventure with templates, I've templated my Container class not just on the ItemType it holds, but also on a Functor argument that determines how it should order the items. So far, so good.
A little problem I've run into occurs when I want to copy the contents of one Container to another: If the two Containers have different Functor types, then they technically are unrelated classes. Therefore, Container A isn't allowed to access the non-public contents of Container B. Is there any good way to deal with this problem, other than making everything I need to access public? Some way to template a "friend" declaration, perhaps?
Example code to demonstrate the problem follows:
#include <stdio.h>
class FunctorA {};
class FunctorB {};
template <class ItemType, class Functor> class MyContainer
{
public:
MyContainer() : _metaData(0) {/* empty */}
template<class RHSFunctor> void CopyFrom(const MyContainer<ItemType, RHSFunctor> & copyFrom)
{
_metaData = copyFrom._metaData;
_item = copyFrom._item;
}
private:
int _metaData;
ItemType _item;
};
int main(int argc, char ** argv)
{
MyContainer<void *, FunctorA> containerA;
MyContainer<void *, FunctorB> containerB;
containerA.CopyFrom(containerB); // error, containerA::CopyFrom() can't access containerB's private data!
return 0;
}
| You can make a base template class templated just on ItemType, keep the data there, have the full-fledged 2-args template subclass that base, AND put the copy-from in the base class as it doesn't depend on the functor anyway. I.e.:
template <class ItemType> class MyContainerBase
{
public:
MyContainerBase() : _metaData(0) {/* empty */}
void CopyFrom(const MyContainerBase<ItemType> & copyFrom)
{
_metaData = copyFrom._metaData;
_item = copyFrom._item;
}
protected:
int _metaData;
ItemType _item;
};
template <class ItemType, class Functor> class MyContainer:
public MyContainerBase<ItemType>
{
// whatever you need here -- I made the data above protected
// just on the assumption you may need to access it here;-)
};
|
1,192,032 | 1,192,215 | 'D3DRS_SEPARATEDESTALPHAENABLE' : undeclared identifier - even though it's mentioned in the DirectX comments? | In d3d9types.h in the _D3DRENDERSTATETYPE struct the last 3 types are:
D3DRS_SRCBLENDALPHA = 207, /* SRC blend factor for the alpha channel when D3DRS_SEPARATEDESTALPHAENABLE is TRUE */
D3DRS_DESTBLENDALPHA = 208, /* DST blend factor for the alpha channel when D3DRS_SEPARATEDESTALPHAENABLE is TRUE */
D3DRS_BLENDOPALPHA = 209, /* Blending operation for the alpha channel when D3DRS_SEPARATEDESTALPHAENABLE is TRUE */
Notice it mentions that these will be used if 'D3DRS_SEPARATEDESTALPHAENABLE is TRUE', however there is no D3DRS_SEPARATEDESTALPHAENABLE in the struct whatsoever. The closest thing seems to be: "D3DRS_SEPARATEALPHABLENDENABLE" but I'm not at all sure if this is the same thing.
So i was just wondering what should be set to true for those last three renderstates to actually work (if anything?), I strongly think it's D3DRS_SEPARATEALPHABLENDENABLE but would like someone to please confirm?
| Yep, D3DRS_SEPARATEALPHABLENDENABLE. Looks like a typo in the comments.
From the DXSDK:
D3DRS_SRCBLENDALPHA
One member of the D3DBLEND enumerated
type. This value is ignored unless
D3DRS_SEPARATEALPHABLENDENABLE is
true. The default value is
D3DBLEND_ONE.
D3DRS_DESTBLENDALPHA
One member of the D3DBLEND enumerated
type. This value is ignored unless
D3DRS_SEPARATEALPHABLENDENABLE is
true. The default value is
D3DBLEND_ZERO.
D3DRS_BLENDOPALPHA
Value used to select the arithmetic
operation applied to separate alpha
blending when the render state,
D3DRS_SEPARATEALPHABLENDENABLE, is set
to TRUE.
Valid values are defined by the
D3DBLENDOP enumerated type. The
default value is D3DBLENDOP_ADD. If
the D3DPMISCCAPS_BLENDOP device
capability is not supported, then
D3DBLENDOP_ADD is performed. See
D3DPMISCCAPS.
|
1,192,070 | 1,192,074 | Good Readings on Unix/Linux Socket Programming? | though I haven't worked with sockets professionally, I find them interesting. I read some part of Unix Network Programming by Richard Stevens (considered to be the Bible I suppose as it is referred by everyone I ask) but the problem is the examples require a universal header unp.h which is a PIA to use.
Can some of you suggest a good reading for socket programming in Unix/Linux? Considering I am relatively experienced C/C++ coder.
| The canonical reference is UNIX Network Programming by W. Richard Stevens. upn.h is really just a helper header, to make the book examples clearer - it doesn't do anything particularly magic.
To get up and running very quickly, it's hard to go past Beej's Guide To Network Programming using Internet Sockets.
|
1,192,405 | 1,193,014 | MFC feature pack - How to get the font, style and size using CMFCPropertyGridProperty::GetValue | By using CMFCPropertyGridProperty::GetValue I'm able to get the contents of the property grid.
I have one property though that gets the font, where when you click on it, shows a dialog box to select the font, size and style.
Using this code:
CMFCPropertyGridProperty* pCurSel = m_wndPropList.GetCurSel();
CString test = pCurSel->GetValue();
I'm able to get the string on the field, However if you get the value as a string, you ONLY get the font name and the font size [ ex. tahoma(8) ]. I would like to get the value as a string so I could write these values on an XML file. The dialog box for selecting font, size and style must be returning a value of type DWORD (I suppose). But how do I extract it's return value so that I would literally get what is selected like 'tahoma', '10', and 'Bold'?
Please help... thanks...
| CMFCPropertyGridProperty* pCurSel = m_wndPropList.GetCurSel();
CMFCPropertyGridFontProperty* pFontProp = dynamic_cast<CMFCPropertyGridFontProperty*>(pCurSel);
if ( pFontProp ) {
LPLOGFONT font_info = pFontProp->GetLogFont();
// use font_info fields
}
LOGFONT structure description
|
1,192,833 | 1,193,739 | About WM_MOUSEHOVER, controls and Balloons | I have this code in the switch (msg) loop inside WindowProc on my GUI App.
case WM_MOUSEMOVE:
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_HOVER;
tme.dwHoverTime = 100;
tme.hwndTrack = hwnd;
TrackMouseEvent(&tme);
break;
case WM_MOUSEHOVER:
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), hwnd, AboutDlg);
break;
I was wondering if I could do anything to have event WM_MOUSEOVER only when I hover over a Control of the window (in this case a CHECKBUTTON)
I need this because I want some explanation about this checkbox (I don't want to write it on the label) to popup when the mouse is over it. I don't want either a DialogBox... is there any Balloon (or something without an OK button) that appears and dissappears instead a dialogbox or messagebox?
Thanks a lot
| It's called a tooltip. They often don't require you to track any mouse events at all. You can even make them look like speech balloons. To get started, read about them in MSDN.
|
1,193,134 | 1,193,691 | Is downcasting this during construction safe? | I have a class hierarchy where I know that a given class (B) will always be derived into a second one (D). In B's constructor, is it safe to statically cast the this pointer into a D* if I'm sure that nobody will ever try to use it before the entire construction is finished? In my case, I want to pass a reference to the object to yet another class (A).
struct A
{
D & d_;
A(D & d) : d_(d) {}
};
struct D; //forward declaration
struct B
{
A a;
B() : a(std::static_cast<D&>(*this)) {}
};
struct D : public B
{};
Is this code safe?
| @AProgrammer's answer made me realized that the static_cast could be easily avoided by passing the this pointer from the derived class to the base class. Consequently, the question boils down to the validity of the this pointer into the member-initializer-list.
I found the following note in the C++ Standard [12.6.2.7]:
[Note: because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized. ]
Therefore, using this in the member-initializer-list is perfectly valid, so I think the code presented is safe (as long as no members of D are accessed).
|
1,193,138 | 1,193,501 | Virtual base class data members | Why it is recommended not to have data members in virtual base class?
What about function members?
If I have a task common to all derived classes is it OK for virtual base class to do the task or should the derived inherit from two classed - from virtual interface and plain base that do the task?
Thanks.
| As a practice you should only use virtual inheritance to define interfaces as they are usually used with multiple inheritance to ensure that only one version of the class is present in the derived class. And pure interfaces are the safest form of multiple inheritance. Of course if you know what you are doing you can use multiple inheritance as you like, but it can result in brittle code if you are not careful.
The biggest drawback with virtual inheritance is if their constructors take parameters. If you have to pass parameters to the constructor of a virtual base class you force all derived classes to explicitly call the constructor (they cannot rely on a base class calling the constructor).
The only reason I can see for your explicit advise is that data in your virtual base class these might require constructor parameters.
Edit
I did some home work after Martin's comment, thank Marin. The first line is not quite true:
As a practice you should only use
virtual inheritance to define
interfaces as they are usually used
with multiple inheritance to ensure
that only one version of the class is
present in the derived class.
Virtual inheritance makes no difference if the base class is a pure interface (except for slightly different compiler errors, in vc8, if all the methods are not implemented). It only makes a real difference if the base class has data, in this case you end up with a diamond rather than a U shape
Non virtual virtual
A A A
| | / \
B C B C
\ / \ /
D D
In the virtual case B and C share the same copy of A.
However I still agree with everything else about pure interfaces being the safest form of multiple inheritance, even if they don't require virtual inheritance. And the fact that constructor parameters and virtual inheritance are a pain.
|
1,193,335 | 1,194,281 | Screen capture ignores some windows | I am working in MFC and I am trying to capture a bmp of the desktop.
I am using GetDC(NULL) to do this but it seems it ignores special skinned windows. It seems to ignore windows drawn with UpdateLayeredWindow. This behaviour seems to be happening only on Vista x64 and XP. I have also tried GetWindowDC with the desktop HWND but the result is the same.
NOTES:
1) Print Screen works.
2) On Vista if I enable Aero the screen captures are ok, "special" windows appear. So on Vista it only happens when Aero is disabled.
An ideas?
Thank you.
| When calling BitBlt(), add the CAPTUREBLT flag to "capture" layered windows
|
1,193,465 | 1,194,020 | access violation error when using map in dll | I tried to create a win32 dll using c++. It has a map declared globally. But when I try to access the map using the dll its giving a run time error that: WindowsError: exception: access violation reading 0x00000008. How to solve it?
Declaration: static map<int,urllib> url_container;
The urllib is a class.
Error occurance: url_container[ucid] = urllib();
The error occurs at the above point.
| Does this code
url_container[ucid] = urllib()
get called in a static initialiser for an other global object? If so there is no guarantee that url_container has been consutructed before the other global object.
Use an accessor function to control when the object is created, or use a singleton library like boost singleton
Accessor example
map<int,urllib> & get_url_container()
{
static map<int,urllib> url_container;
return url_container
}
As an aside I would suggest you try to avoid global objects. As you could spend the rest of your life debugging issues like this. Eventually the construction of one global object will depend on another etc. and the order of construction is not defined so it might work on one platform/compiler and fail on another.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.