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< typen... | 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 trans... |
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 ... | 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_co... | 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 (som... |
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 st... |
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... | 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... | 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 m... | 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 destr... | 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... |
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. G... |
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 t... | 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-do... |
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 happ... | 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()... |
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 ... | 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... |
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 MF... | 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... | 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 st... |
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 a... |
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 i... | 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 chan... |
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... | 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 reposito... |
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(... | 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)
{
FILET... | 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 th... |
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... |
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 ad... | 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 Appli... |
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(), ... | 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 construc... |
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 ... |
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( exist... | 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 allocatio... | 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 par... |
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 ... | 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 t... | 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:
fu... |
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 /bo... | 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->P... |
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. Af... |
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... |
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 whic... | 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 ... |
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... |
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 ple... | 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 a... |
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... |
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... |
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 jus... | 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 con... |
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... | 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 th... |
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 wha... | 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 us... | 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 us... |
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... | 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;
cou... | 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... |
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 lin... | 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 proba... |
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 SUBP... | 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 comman... |
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... | 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... |
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 documentat... | 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... |
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... | 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 doe... |
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 << "Ent... | 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 Silverligh... | 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 issu... |
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 fr... | 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(),
... |
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 alr... | 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 ... | 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, ... |
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 ... | 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 issu... |
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 f... | 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.SetTextureStageSt... |
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 sys... |
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... | 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 o... |
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... | 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 originatin... |
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.... | 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 Graphic... |
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 ... | 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... |
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. Displ... | 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 p... | 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, &F... |
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 ... | 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 creden... |
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... | 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 ca... |
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 dep... | 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... |
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 everyt... | 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 b... | 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 ... |
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 b... | 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... | 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 tim... |
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 ... |
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. ... | 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 ... |
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()) {
// So... | 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
e... |
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... | 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 aft... | 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 resolv... |
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... |
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. Ima... | 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 did... | 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. ... |
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 t... | 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 automatic... |
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... | 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<< ... |
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 ... | 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 == ... |
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 ... | 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() : _metaDa... |
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 ... | 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 e... |
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... | 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 = ... | 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... | 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 th... | @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]:... |
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 ... |
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... | 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 occu... | 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 single... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.