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 |
|---|---|---|---|---|
525,903 | 525,904 | Opening a file with std::string | This should be a fairly trivial problem. I'm trying to open an ofstream using a std::string (or std::wstring) and having problems getting this to work without a messy conversion.
std::string path = ".../file.txt";
ofstream output;
output.open(path);
Ideally I don't want to have to convert this by hand or involve c-s... | In the path string, use two dots instead of three.
Also you may use 'c_str()' method on string to get the underlying C string.
output.open(path.c_str());
|
525,926 | 526,398 | Window message procedures in Linux vs Windows | In Windows when you create a window, you must define a (c++)
LRESULT CALLBACK message_proc(HWND Handle, UINT Message, WPARAM WParam, LPARAM LParam);
to handle all the messages sent from the OS to the window, like keypresses and such.
Im looking to do some reading on how the same system works in Linux. Maybe it is beca... | In principle it is absolutely the same. However, it has nothing to do with communication with the OS (nor does it on win32, using user32.dll is entirely optional)
A GUI application has an event loop somewhere, which processes messages from a queue at some level.
There are a lot of libraries typically used to "hide" thi... |
525,934 | 525,952 | Memory Allocation in std::map | I am doing a report on the various C++ dictionary implementations (map, dictionary, vectors etc).
The results for insertions using a std::map illustrate that that the performance is O(log n). There are also consistent spikes in the performance. I am not 100% sure what's causing this; I think they are caused by memory... | You are right: it is O(log n) complexity. But this is due to the sorted nature of map (normally binary tree based).
Also see http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html there is a note on insert. It’s worst case is O(log n) and amortized O(1) if you can hint where to do the insert.
Maps are norm... |
526,270 | 526,682 | Standard behavior of tellp on empty ostringstream | I have a question on the standard behavior of calling tellp on an empty ostringstream. I have a function foo which calls tellp the first thing:
void foo(std::ostream& os)
{
std::ostream::pos_type pos = os.tellp();
// do some stuff.
}
int main()
{
std::ostringstream os;
foo(os);
}
In Visual Studio 2005... | 27.6.2.4:
pos_type tellp();
Returns: if fail() != false, returns
pos_type(-1) to indicate failure.
Otherwise, returns
rdbuf()->pubseekoff(0, cur, out).
And pubseekoff returns -1 on fail. But am not sure why this happens for you in the case of ostringstream, maybe was too tired to find the words about undefined... |
526,474 | 526,480 | Using C code from C++ using autotools | I am writing a (my first) C++ class on top of some code written in C, but I can only get the C++ to compile by declaring the C functions in a extern block. My project uses autotools; is there any way to automate this process so I don't have to maintain two header files?
| Yes create wrapper header files which include your C header files like so...
//Wrapper.h
#ifdef __cplusplus
extern "C"
{
#include "Actual.h"
}
#else
#include "Actual.h"
#endif
//Use.cpp
#include "Wrapper.h"
int main()
{
return 0;
}
//Use.c
#include "Wrapper.h"
/*or #include "Actual.h" */
int main()
{
... |
526,583 | 527,138 | modify an open file c++ | Under Windows is there a way to modify a file/executable opened by another process using c++?
| The OS holds the executable file open for read-only sharing as long as it's running, so there's no way to modify it directly. You can, however, open it for reading (if you specify read-sharing in your CreateFile call), and make a modified copy of it, while it's running.
I don't know if that's what you had in mind, but ... |
526,761 | 528,902 | Set QLineEdit focus in Qt | I am having a qt question. I want the QLineEdit widget to have the focus at application startup. Take the following code for example:
#include <QtGui/QApplication>
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QLineEdit>
#include <QtGui/QFont>
int main(int argc, char *argv[])
{
QApp... | Keyboard focus is related to widget tab order, and the default tab order is based on the order in which widgets are constructed. Therefore, creating more widgets changes the keyboard focus. That is why you must make the QWidget::setFocus call last.
I would consider using a sub-class of QWidget for your main window that... |
526,797 | 526,893 | Good tools for creating a C/C++ parser/analyzer | What are some good tools for getting a quick start for parsing and analyzing C/C++ code?
In particular, I'm looking for open source tools that handle the C/C++ preprocessor and language. Preferably, these tools would use lex/yacc (or flex/bison) for the grammar, and not be too complicated. They should handle the late... | Parsing C++ is extremely hard because the grammar is undecidable. To quote Yossi Kreinin:
Outstandingly complicated grammar
"Outstandingly" should be interpreted literally, because all popular languages have context-free (or "nearly" context-free) grammars, while C++ has undecidable grammar. If you like compilers and... |
526,855 | 526,872 | How should I deploy an MFC application? | I created an application in VS 2008 Express as an MFC app just to take advantage of the easy GUI creation. I might re-do this app in pure win32 since no other MFC classes are used (just a button and a text box, the button fires off the main program, all win32). My only question that determines whether I stay in MFC or ... | Statically link MFC and it's just another .exe.
You can just give that to the user or create an installer with either the microsoft .msi tool or a regular setup.exe with something like innosetup.
Edit - the error message in your comment is about another dll that is part of a 3rd party library. You can't (easily) take ... |
527,166 | 527,179 | Creating a new vector using a transform | I have a vector of integers and I want to convert it to a vector of pairs (pair consists of a bool and a int). My current code is simple like this:
std::vector<int> a;
std::vector<std::pair<bool,int> > b;
a.push_back(1);
a.push_back(2);
a.push_back(3);
for(int i = 0; i < a.size(); ++i)
{
... | 1. You could make a functor and std::for_each:
struct F {
F(std::vector<std::pair<bool,int> > &b) : m_b(b){
}
void operator()(int x) {
m_b.push_back(std::make_pair(false, x));
}
std::vector<std::pair<bool,int> > &m_b;
};
std::for_each(a.begin(), a.end(), F(b));
Though this may prove to b... |
527,413 | 527,983 | how boost::function and boost::bind work | I dislike having magic boxes scattered all over my code...how exactly do these two classes work to allow basically any function to be mapped to a function object even if the function<> has a completely different parameter set to the one im passing to boost::bind
It even works with different calling conventions (i.e. me... | boost::function allows anything with an operator() with the right signature to be bound as the parameter, and the result of your bind can be called with a parameter int, so it can be bound to function<void(int)>.
This is how it works (this description applies alike for std::function):
boost::bind(&klass::member, instan... |
527,663 | 527,670 | Optimising Iterator Definitions | This is a (hopefully) really simple question - I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment.
So this code:
std::SomeSTLContainer::const_iterator it = container.begin();
std::SomeSTLContainer::const_iterator itEnd = container.end();
would be 'slow... |
I have been told recently that using C++ style initialisation is better than traditional (and more common) assignment.
This is simply wrong.
I understand the reason for this - the first example causes default construction and initialisation then subsequent assignment rather than specific construction and direct assi... |
527,700 | 527,736 | What is a good desktop programming language to learn for a web developer? | I'm want to learn a desktop programming language, preferably C, C++ or C#. I'm a PHP/HTML/CSS programmer and I would like to get into desktop applications. I need something pretty powerful and I would like to be able to create applications with Windows GUI's.
What would the Stack Overflow community recommend? Is there... | edit:
A web programmer wants to create Windows applications and you recommend C? What's wrong with you people?!
/edit
Obviously C#.
C# will be easier to get into and will let you build Windows applications using WinForms or WPF and all the new Microsoft toys in .NET. If you know your way around PHP, you should already ... |
527,742 | 527,788 | Overloading operator<< for primitive types. Is that possible? | Hey. Is it possible to overload operator<< for primitive types? Fx lets say that I want to write a std::endl each time want to write a int. Can I overload operator<< for int, so that it automatic puts a std::endl to the output? I have tried with this,
std::ostream& operator<<(std::ostream& strm, int & i)
{
strm << i... | As zabzonk said, the standard library provides an (ostream&, int) overload so you can't define another.
To simulate what you were doing (though it is completely pointless in its present form :) :
class EndlinedInteger {
public:
EndlinedInteger(int i) : i(i) { }
friend ostream& operator<<(ostream&, EndlinedInteg... |
527,887 | 527,897 | C/C++ optimize data structures, array of arrays or just array | Working with a program that uses 16bytes 4v4 one byte matrices :
unsigned char matrix[4][4];
and a few 256bytes 16v16 one byte matrices:
unsigned char bigMatrix[16][16];
Very often due to data manipulation I am forced to loop column wise in the program making cache misses.
Will the performance improve if I use an arr... | It makes no difference. The data is laid out in the exact same way in either case, and is accessed in the same way too. I'd be surprised if it didn't generate exactly the same assembly, even.
However, with a 256byte table, you're unlikely to get cache misses in any case. The CPU's L1 cache is typically between 32 and 1... |
527,999 | 529,022 | Is it OK to use C-style cast for built-in types? | After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?
| I would not, for the following reasons:
Casts are ugly and should be ugly and stand out in your code, and be findable using grep and similar tools.
"Always use C++ casts" is a simple rule that is much more likely to be remembered and followed than, "Use C++ casts on user-defined types, but it's OK to use C-style casts... |
528,107 | 528,374 | Is it possible to use boost library in visual studio 2008 64 bit version? | I tried to use boost library in 64 bit mode of VS2008 but I'm getting "header file not found" errors.
is it any possible to use boost library under 64 bit mode of VS2008?
it worked fine in 32 bit mode. that's why I'm suspicuous bout 64 but ;(
Or anybody have good link to show setting up 64 bit mode to use boost?
thanks... | Boost works fine with VS2008. Are you sure you have your include paths set up correctly?
I usually a reference to the boost libraries to the Options|Projects and Solutions|VC++ Directories settings. Make sure you set the "Include Files" setting for both win32 and x64.
Most of the libraries are header only and it doesn'... |
528,117 | 528,125 | Compiler Error with const function | I am not sure whether I am missing something basic. But I am unable to understand why the compiler is generating the error for this code:
class A
{
};
class B
{
public:
B();
A* get() const;
private:
A* m_p;
};
B::B()
{
m_p = new A;
}
A* B::get() const
{
//This is compiling fine
return m_p;
}... | const in the function signature tells the compiler that the object's members may not be modified. Yet you return a non-const pointer to a member, thus allowing a violation of that promise.
In your class B, you make/break no promise since you don't return a pointer to a member, you return a copy of it (and the member ha... |
528,409 | 528,974 | customizing assert macro | On Windows/c++, I want to customize the assert dialog box to ignore an assertion forever, so I can be more aggressive with assertions. I understand how hard it is to write a correct assert macro, and do not wish to do this, just hook the dialog code. Is there an easy way (or concise hack) to do this?
article on asser... | Look into the
_CrtSetReportHook function or the newer _CrtSetReportHook2. You can use it to install a hook that remembers "seen" messages, and reports them as handled when seen again.
|
528,494 | 713,682 | Use domain-specific-language files inside C++ project | I am developping a DSL with its own graphical editor. Such files have a .own extension. I also have a small tool that compiles .own files into .h files.
X.own --> X.h and X/*.h
I have written a simple .rules file to launch the generation.
My problem is the following :
Most of my source files include X.h, but a change i... | jheriko's answer is interesting, because it provides a way to launch custom tool, then generate build dependencies. But it's not very usable, because you then lose all possibilities to use "custom build tools" toolkit, in which you can
choose to always compile files with some precise extension
manually skip custom bu... |
528,559 | 528,588 | C/C++ best way to send a number of bytes to stdout | Profiling my program and the function print is taking a lot of time to perform. How can I send "raw" byte output directly to stdout instead of using fwrite, and making it faster (need to send all 9bytes in the print() at the same time to the stdout) ?
void print(){
unsigned char temp[9];
temp[0] = matrix[0][0]... | IO is not an inexpensive operation. It is, in fact, a blocking operation, meaning that the OS can preempt your process when you call write to allow more CPU-bound processes to run, before the IO device you're writing to completes the operation.
The only lower level function you can use (if you're developing on a *nix ... |
528,854 | 528,983 | using C++ boost regex | I am not an expert in boost, though I have used ublas extensively. Recently, my supervisor asked me to build boost regex for the gcc platform. My question is:
Why can't I use the regex as it is, like ublas?
Please give detailed answer.
| I'm assuming that by "can't use the regex as it is" you mean "without having to build it seperately".
Short answer: uBLAS is "header-only" (http://www.boost.org/doc/libs?view=filtered_header-only), and Regex is not.
A "header-only" library's implementation entirely resides in header (.hpp) files. To use it, one only ha... |
529,071 | 529,137 | XCode automatically deactivating breakpoints | I'm using xcode in C++. I'm trying to debug my project, but at random intervals, it seems to ignore my breakpoints. There are three things that it does:
1) Sometimes, when I run, it automatically switches to "de-activate break points" mode. (the relevant button goes light and says "Activate")
2) Sometimes when I run, A... | Try unchecking the Load symbols lazy in the Debugging panel in Preferences
alt text http://img.skitch.com/20090209-gj947qk7dxdyms1wij4q5em2f2.jpg
|
529,210 | 529,942 | Change Properties.settings for a .net deployed application | Hi All,
I have two .net applications, these applications want to talk to each other, I made a setting in the first project as follows
[CompilerGeneratedAttribute()]
[GeneratedCodeAttribute("SettingsSingleFileGenerator", "9.0.0.0")]
public sealed partial class Settings :ApplicationSettingsBase
{
[UserScopedSe... | User level app settings are isolated in a subdirectory of AppData. One app cannot find the settings of another app. Just use a plain file.
|
529,284 | 529,344 | C/C++ AQtime profiler questions | I need to profile my console program with AQ. It is in one big file (for optimizations purposes).
void function1();
void function2()
// etc more declarations
int main{
//alot of loops, and function uses
function1();
function1();
}
Profiling on "Elapsed time" default profile just gives me that main is usin... | AQtime will only profile the routines you tell it to profile. Its startup wizard is pretty helpful in terms of helping you configure this correctly; I'd recommend paying pretty careful attention to it, but the general procedure is:
Create an area. Configure that area for line or routine profiling.
Add source files to ... |
529,697 | 529,715 | How do I make a pointer to a multidimensional array which has an unknown size? | how do I make a pointer to a multidimensional array, which have a unknown size? I've tried this:
int **triangles;
triangles = new int[numTriangles][3];
But i get this error:
cannot convert 'int (*)[3]' to 'int**' in assignment
| triangles = new int[numTriangles*3];
Then access it as:
triangles[numTriangles*triangleIndex+vertexIndex] = blah;
But this is tedious and error prone so I suggest using boost.multi_array instead, or rolling your own (really simple):
template<class T>
class Matrix {
public:
Matrix(int _w, int _h) : data(_w*_h), w(... |
529,706 | 530,084 | Using Iterator parsing with Boost::Spirit Grammars | When I attempt to use the iterator form of parsing for a Spirit grammar I get a argument passing conversion error from the iterator type to const char*. How do I fix this?
There are some restrictions. I'm using an iterator adapter on large inputs, so it is not feasible for me to convert to a C style string.
Here is s... | Hard to tell from the code as posted, since it contains a few basic errors.
After correction of these, it compiles fine on my machine (with MSVC++7.1):
#include <boost/spirit/core.hpp>
#include <vector>
#include <string>
using namespace std;
using namespace boost::spirit;
struct ex : public grammar<ex> {
template <type... |
529,875 | 529,996 | C++ Passing a dynamicly allocated 2D array by reference | This question builds off of a previously asked question:
Pass by reference multidimensional array with known size
I have been trying to figure out how to get my functions to play nicely with 2d array references. A simplified version of my code is:
unsigned int ** initialize_BMP_array(int height, int width)
{
... | Use a class to wrap it, then pass objects by reference
class BMP_array
{
public:
BMP_array(int height, int width)
: buffer(NULL)
{
buffer = (unsigned int **)malloc(height * sizeof(unsigned int *));
for (int i = 0; i < height; i++)
{
buffer[i] = (unsigned int *)malloc(width * siz... |
530,244 | 530,725 | calling C# from c++ com add-in | I have a COM add-in written in C++ (not C++ / CLI). I want to call a C# library objects/methods from this C++ com library.
I guess the CCW comes into picture here, which i am currently reading about.
Are there any quick pointers to this stuff from your experience?
Also, i have a method in my Com add-in that i would lik... | I have this links for you:
COM Interop Part 1 Sample
Create DCOM application from within .Net environment: Part V
C++ to C# call
|
530,282 | 532,434 | Do I need to create an interface for every self-created class I use in XPCOM? | I'm a noob to XPCOM development. In the course of writing XPCOM code in C++, I need to create addtional classes for use inside my XPCOM component. Do I need to create another XPCOM component for such classes? Can't I just add the new class in the header file?
| No, not at all. XPCOM describes the external interface. "Internal" classes are compiled by your C++ compiler. That compiler won't snitch on you, so XPCOM will never know they exist.
For your own sanity, it does make sense to keep those internal classes in their own header.
|
530,462 | 530,512 | In C++ does std::multiset keep a stable sorting order? | Suppose I have two items, a and b, that compare the same. So a < b is false, and b < a is false. If these items are inserted into a std::multiset (or std::multimap) as keys, do I have any guarantees of their final sorted order?
I've checked a couple of references, but I couldn't find the answer. I'm tempted to think th... | This thread implies that it is not guaranteed by the current standard but is met by all known current implementations, and gives a link to the C++0x draft standard that includes a guarantee.
|
530,519 | 530,557 | std::mktime and timezone info | I'm trying to convert a time info I reveive as a UTC string to a timestamp using std::mktime in C++. My problem is that in <ctime> / <time.h> there is no function to convert to UTC; mktime will only return the timestamp as local time.
So I need to figure out the timezone offset and take it into account, but I can't fin... | mktime assumes that the date value is in the local time zone. Thus you can change the timezone environment variable beforehand (setenv) and get the UTC timezone.
Windows tzset
Can also try looking at various home-made utc-mktimes, mktime-utcs, etc.
|
530,614 | 530,618 | Print leading zeros with C++ output operator? | How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf like this:
printf("%05d", zipCode);
I know I could just use printf in C++, but I would prefer the output operator <<.
Would you just use the following?
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
... | This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question.
#include <iostream>
#include <iomanip>
using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;
// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::se... |
530,741 | 531,290 | What's the difference between a procedural program and an object oriented program? | I'm fairly new to programming but I've been reading some interesting discussions on StackOverflow about various programming approaches. I'm still not 100% clear on what the difference is between procedural programming and object oriented programming. It sounds like object oriented programming still uses procedures (met... | The difference between the two is subtle but significant.
In a procedural program, modules interact by reading and writing state that is stored in shared data structures.
In an object oriented program, modules in the form of objects interact by sending messages to other objects.
|
531,133 | 531,141 | Should I put many functions into one file? Or, more or less, one function per file? | I love to organize my code, so ideally I want one class per file or, when I have non-member functions, one function per file.
The reasons are:
When I read the code I will always
know in what file I should find a
certain function or class.
If it's one class or one non-member
function per header file, then I won't
incl... | IMHO, you should combine items into logical groupings and create your files based on that.
When I'm writing functions, there are often a half a dozen or so that are tightly related to each other. I tend to put them together in a single header and implementation file.
When I write classes, I usually limit myself to... |
531,477 | 531,489 | Strange assembly from array 0-initialization | Inspired by the question Difference in initalizing and zeroing an array in c/c++ ?, I decided to actually examine the assembly of, in my case, an optimized release build for Windows Mobile Professional (ARM processor, from the Microsoft Optimizing Compiler). What I found was somewhat surprising, and I wonder if someone... | The reason for lines 2 and 5 is because you specified a 0 in the array initializer. The compiler will initialize all constants then pad out the rest using memset. If you were to put two zeros in your initializer, you'd see it strw (word instead of byte) then memset 8 bytes.
As for the padding, it's only used to align... |
531,684 | 531,727 | What is the best way to take screenshots of a Window with C++ in Windows? | What is the best (easiest) way to take a screenshot of an running application with C++ under Windows?
| You have to get the device context of the window (GetWindowDC()) and copy image (BitBlt()) from it. Depending on what else you know about the application you will use different methods to find which window's handle to pass into GetWindowDC().
|
531,722 | 531,758 | C++ for the C# Programmer | I have a good understanding of OO from java and C# and I'm lucky in my engineering courses to have been exposed to the evils of both assembler and C (pointers are my playground :D ).
However, I've tried looking into C++ and the thing that gets me is the library code. There are so many nice examples of how to perform... | I'd suggest that you work your way through the excellent Andrew Koenig and Barbara Moo book "Accelerated C++" (sanitised Amazon link). This book teaches you C++ rather than assume that you know C and then look at the C++ bits bolted on.
In fact, you dive in and are using STL containers in the early chapters.
Highly re... |
531,916 | 531,928 | error C2039: 'memchr' : is not a member of '`global namespace'' | It has been quite a while since I am getting this error in the standard <cstring> header file for no apparent reason. A google search brought up many answers but none of them worked.
| Ok I fixed it myself. It was a stupid mistake! I have a file called "String.h" in a library project which is being picked up by the <cstring> header. Probably because I have added the path to <String.h> as an additional include directory in my test project (where I am getting this error.) Hope this helps someone.
|
531,941 | 533,372 | How to set up Google C++ Testing Framework (gtest) with Visual Studio 2005 | It is not documented on the web site and people seem to be having problems setting up the framework. Can someone please show a step-by-step introduction for a sample project setup?
| What Arlaharen said was basically right, except he left out the part which explains your linker errors. First of all, you need to build your application without the CRT as a runtime library. You should always do this anyways, as it really simplifies distribution of your application. If you don't do this, then all of... |
531,957 | 551,134 | Editor core buffer type and syntax highlighting | I've been thinking a lot about making an editor core functionality wise compatible to vim, similar to yzis.
The biggest questions are what buffer type to use.
Requirement are:
possibility to implement fast syntax highlighting, regex on top of it.
possibility to implement multiple syntax highlightings in a single file.... | A good text editor should be useful for all kinds of work a programmer might do, and that includes opening files that may sometimes be several gigabytes in size. Therefore I would not recommend a mind set where everything is to be buffered in RAM.
I would recommend setting up a search tree of slices representing the fi... |
531,998 | 532,121 | Is there a way to set the environment path programmatically in C++ on Windows? | Is there a way to set the global windows path environment variable programmatically (C++)?
As far as I can see, putenv sets it only for the current application.
Changing directly in the registry (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) is also an option though I would prefer API methods if th... | MSDN Says:
Calling SetEnvironmentVariable has no
effect on the system environment
variables. To programmatically add or
modify system environment variables,
add them to the
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session
Manager\Environment registry key, then
broadcast a WM_SETTINGCHANGE mess... |
532,092 | 532,105 | Weird behaviour of C++ destructors | #include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< vector<int> > dp(50000, vector<int>(4, -1));
cout << dp.size();
}
This tiny program takes a split second to execute when simply run from the command line. But when run in a debugger, it takes over 8 seconds. Pausing the debugger r... | Running in the debugger changes the memory allocation library used to one that does a lot more checking. A program that does nothing but memory allocation and de-allocation is going to suffer much more than a "normal" program.
Edit
Having just tried running your program under VS I get a call stack that looks like
ntdll... |
532,248 | 532,271 | Communication between inherited classes | I have 3 classes in different files:
X
|
-------
| |
Y Z
I will be creating several objects of inherited classes Y and Z.
A specific function in class Z should be executed only if some flag variable is set by class Y.
Where should I create this flag variable (which class) and what should be the declarati... | Consider template method as a replacement for the infamous flags.
|
532,524 | 532,546 | How can you parse simple C++ typedef instructions? | I'd like to parse simple C++ typedef instructions such as
typedef Class NewNameForClass;
typedef Class::InsideTypedef NewNameForTypedef;
typedef TemplateClass<Arg1,Arg2> AliasForObject;
I have written the corresponding grammar that i'd like to see used in parsing.
Name <- ('_'|letter)('_'|letter|digit)*
Type <- Name
T... | I would alter the grammar slightly
ShortName <- ('_'|letter)('_'|letter|digit)*
Name <- ShortName
Name <- Name::ShortName
Type <- Name
Type <- Name Templates
Templates <- '<' Type (',' Type)* '>'
Instruction <- "typedef" Type Name ';'
Also your grammar leaves out the following cases
Multiple typedef targets.
Point... |
532,663 | 532,890 | Why does wgluseFontBitmaps consume too much memory on some computers? | I'm creating a game in OpenGL which loads the entire Arial Unicode MS font when it loads. The program uses on avg. 10 megs of memory on my computer (op sys is WinXP SP2) and runs without problems, but when I move the program to my laptop (with Vista) the wglUseFontBitmaps hangs and allocates memory fluently and never r... | How many glyph display lists are you trying to generate with wglUseFontBitmaps()? Can you show us your invocation? Perhaps Vista is trying to do all 60000-some-odd glyphs in one go, and XP is doing some sort of on-demand construction?
I've had good luck with FreeType2 and MS Arial Unicode, though it does take some ti... |
532,702 | 532,821 | Any way to make this relatively simple (nested for memory copy) C++ code more efficient? | I realize this is kind of a goofy question, for lack of a better term. I'm just kind of looking for any outside idea on increasing the efficiency of this code, as it's bogging down the system very badly (it has to perform this function a lot) and I'm running low on ideas.
What it's doing it loading two image container... | I think the array accesses (are they real array accesses or operator []?) are going to kill you. Each one represents a multiply.
Basically, you want something like this:
for (int y=0; y < height; y++) {
unsigned char *destBgr = imgRgb.GetScanline(y); // inline methods are better
unsigned char *destBW = imgBW.G... |
532,755 | 532,806 | What are the valid values of the expression (uninitialized_bool ? 1 : 2)? | What is the set of valid outputs for the following, according to the standard?
bool x;
cout << (x ? 1 : 2);
edit: unknown(google) has got it. In gcc my code was crashing because of sprite.setFrame(isPressed ? 0 : 1) with the conditional returning 28!
|
Using a bool value in ways described
by This Standard as "undefined" such
as by examining the value of an
unitialized automatic variable, might
cause it to behave as it is neither
true or false.
Welcome to the world of undefined behaviour. But first, why would you want to do that?
|
532,779 | 542,784 | Is there anything like GhostDoc for C++ | When I'm developing in C#, I heavily use GhostDoc to speed up the process of commenting my code. I'm currently working on a C++ project and I haven't found an equivalent tool. I know about Doxygen, but from what I know it is used to create documentation outside the code, not comments in the code. Are there any good equ... | Visual Assist helps by providing custom scripts executed while typing (or on other).
For example, you can have a script for comments like this :
/************************************************************************/
/* My comment : $end$ */
/******... |
532,780 | 535,133 | CATIA-CAA CATKeyboardEvent | I know there are only a few CAA Programmers in the world but I try it anyway...
I can't get keyboard events to work. I found this code which looks reasonable but the Notification doesn't fire.
AddAnalyseNotificationCB(CATFrmLayout::GetCurrentLayout()->GetCurrentWindow()->GetViewer(),
CATKeyboard... | There is a much denser group of developers for CAA at:
http://www.3ds.com/alliances/c-java-developers/forum/
The same question came up, with several people mentioning that this API was unauthorized, and therefore you can't rely on it, even if it works.
The other samples there are essentially the same code as yours, but... |
533,038 | 533,561 | redirect std::cout to a custom writer | I want to use this snippet from Mr-Edd's iostreams article to print std::clog somewhere.
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
int main()
{
std::ostringstream oss;
// Make clog use the buffer from oss
std::streambuf *former_buff =
std::clog.rdbuf(oss.rdbuf());... | I encourage you to look at Boost.IOStreams. It seems to fit your use-case nicely, and using it is surprisingly simple:
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <iostream>
namespace bio = boost::iostreams;
class MySink : public bio::sink
{
public:
std::streamsi... |
533,065 | 533,085 | C++ class member function naming rules | I'm trying to encapsulate some functions from the C socket library into my own C++ class. I'd like to define a member function that uses the same name as its corresponding C function, but with a different signature. For example, I'd like to write the function
ssize_t MyClass::write(const void *buf);
which makes a ca... | Have you tried calling the C function expliciting that it lives in the global namespace, like ::write?
|
533,076 | 533,201 | Understanding C++ compilers from a Java / C# perspective | I'm a moderately experienced Java / C# programmer, and I've recently started learning C++. The problem is, I'm having trouble understanding how to structure the various header and code files. This seems mostly due to my lack of understanding as to how the compiler links everything together. I've tried reading some text... | The C++ FAQ is an excellent resource about all the idiosyncrasies of C++, but it's probably a little more advanced than you're looking for -- most of the questions (not just the answers) are mysteries even to fairly experienced C++ developers.
I think if you google for C++ tutorials, you'll be able to find something. ... |
534,007 | 534,073 | Performance on strings initialization in C++ | I have following questions regarding strings in C++:
1>> which is a better option(considering performance) and why?
1.
string a;
a = "hello!";
OR
2.
string *a;
a = new string("hello!");
...
delete(a);
2>>
string a;
a = "less";
a = "moreeeeeee";
how exactly memory management is handled in c++ when a bigger string i... | All the following is what a naive compiler would do. Of course as long as it doesn't change the behavior of the program, the compiler is free to make any optimization.
string a;
a = "hello!";
First you initialize a to contain the empty string. (set length to 0, and one or two other operations). Then you assign a new v... |
534,044 | 29,600,223 | How do I tear down observer relationship in multithreaded C++? | I have a Subject which offers Subscribe(Observer*) and Unsubscribe(Observer*) to clients. Subject runs in its own thread (from which it calls Notify() on subscribed Observers) and a mutex protects its internal list of Observers.
I would like client code - which I don't control - to be able to safely delete an Observer... | The "ideal" solution would involve using shared_ptr and weak_ptr. However, in order to be generic, it also has to account for the issue of Subject being dropped before some of its Observer (yes, that can happen too).
class Subject {
public:
void Subscribe(std::weak_ptr<Observer> o);
void Unsubscribe(std::weak_p... |
534,088 | 534,320 | Several machines running same software, some won't connect to firebird | I'm pretty perplexed... I've got 5 different test computers, all relatively blank Windows XP machines running similar hardware specs. I run a silent install of the FireBird (Classic) database and my application. Some computers require "localhost:" (or 127.0.0.1) before the database location to make a connection, and so... | For anybody's future reference, the answer is in the services. Apparently it's not being registered as a service for some reason, and on the working computers, was at some point registered, probably through some sort of far earlier tests of Interbase is my best guess.
C:\Windows\System32\drivers\etc and opening up the... |
534,183 | 534,373 | compiling c++ applications so they can work on other computers as well | So I have this very simply SDL application I want to be able to pass to my friend without having him download a whole bunch of SDL packages.
how can I go about this? I was told to use this line to compile:
(note that I use ubuntu linux and so does my friend, and that this application compiles and runs without the "-Wl... | In the long run your best bet would be to figure out how to build .debs and then your friend's system's package management can take care of installing all the dependencies needed. If you want to distribute the packages more widely, using the platform's native packaging system as intended will save you and your users a... |
534,201 | 534,259 | Is it possible to measure function coverage with gcov? | Currently we use gcov with our testing suite for Linux C++ application and it does a good job at measuring line coverage.
Can gcov produce function/method coverage report in addition to line coverage?
Looking at the parameters gcov accepts I do not think it is possible, but I may be missing something. Or, probably, is... | I guess what you mean is the -f option, which will give you the percentage of lines covered per function. There is an interesting article about gcov at Dr. Dobb's which might be helpful. If "man gcov" doesn't show the -f flag, check if you have a reasobably recent version of the gcc suite.
Edit: to get the percentage o... |
534,215 | 534,243 | How to get unique hardware/software signature from a windows pc in c/c++ | I'm developing a small windows app using c++ and i would like to get some kind of fingerprint of the software/hardware on a pc so that i can allow the app to be run only on certain pc's.
I am aware that the app can be cracked but i'm really interested in implementing something like this.
Any ideas how could i achieve... | It basically depends on how tight you want to couple your software to the underlying hardware. For example you could get some hardware information from the registry, read out the MAC address from the LAN card, retrieve the gfx manufacturer, the CPU id, etc. and hash all these data.
You could then use this hash as a cha... |
534,555 | 534,902 | Using SFINAE to detect POD-ness of a type in C++ | The original title here was
Workaround for SFINAE bug in VS2005 C++
This is tentative use of SFINAE to make the equivalent for the is_pod template class that exists in TR1 (In VS2005 there's no TR1 yet). It should have its value member true when the template parameter is a POD type (including primitive types and struct... | The biggest problem with your approach is you don't do SFINAE here - SFINAE only applies to parameter types and return type here.
However, of all the SFINAE situations in the standard, none applies to your situation. They are
arrays of void, references, functions, or of invalid size
type member that is not a type
poin... |
534,861 | 534,936 | compiling a C++ class in Xcode: error during compilation: stl vector | I have a C++ class that compiles fine on linux with gcc and on widows in visual studio.
boid.h:
#ifndef BOID_CLASS_HEADER_DEFINES_H
#define BOID_CLASS_HEADER_DEFINES_H
#include "defines.h"
class Boid {
public:
// Initialize the boid with random position, heading direction and color
Boid(float SceneRadius,f... | Are you including the C++ header in a .m file?
.m files are treated as .c files with Objective-C extensions.
.mm files are treated as .cpp files with Objective-C extensions, then it's called Objective-C++
Just rename any .m file to .mm, right-click or ctrl-click and select rename on the file in Xcode.
|
535,223 | 535,260 | Why can't I push this object onto my std::list? | Just started programming in C++.
I've created a Point class, a std::list and an iterator like so:
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
std::list <Point> pointList;
std::list <Point>::iterator iter;
I then push new points onto pointList.
Now, I'm... | That should be a valid bit of code.
#include <iostream>
#include <list>
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
int main()
{
std::list<Point> points;
points.push_back(Point(0, 0));
points.push_back(Point(1, 1));
points.push_back(Po... |
535,317 | 535,338 | Checking value exist in a std::map - C++ | I know find method finds the supplied key in std::map and return an iterator to the element. Is there anyway to find the value and get an iterator to the element? What I need to do is to check specified value exist in std::map. I have done this by looping all items in the map and comparing. But I wanted to know is ther... | You can use boost::multi_index to create a bidirectional map - you can use either value of the pair as a key to do a quick lookup.
|
535,444 | 535,647 | Custom manipulator for C++ iostream | I'd like to implement a custom manipulator for ostream to do some manipulation on the next item being inserted into the stream. For example, let's say I have a custom manipulator quote:
std::ostringstream os;
std::string name("Joe");
os << "SELECT * FROM customers WHERE name = " << quote << name;
The manipulator quo... | It's particularly difficult to add a manipulator to a C++ stream, as one has no control of how the manipulator is used. One can imbue a new locale into a stream, which has a facet installed that controls how numbers are printed - but not how strings are output. And then the problem would still be how to store the quoti... |
535,592 | 535,595 | Any nice place to communicate with c++/game developers? | I'm a game programmer working in Korea.
I started Stackoverflow recently and I found it helps me a lot.
Also I think communicating with other developers is a good way to learning and improving myself.
Stackoverflow is the only site I know to communicate (especially in English).
Any other nice place to communicate(ask/a... | Gamedev.net has a great community of game developers, along with tons of great articles and resources related to game programming.
|
535,688 | 535,698 | Passing a variable of type int[5][5] to a function that requires int** | I'd like to test a function that takes runtime-allocated multidimensional arrays, by passing it a hardcoded array.
The function has a signature of void generate_all_paths(int** maze, int size) and the array is defined as int arr[5][5] = {REMOVED}.
I'm not exactly sure how to properly coerce the array for the function (... | This multi dimensional array topic unfortunately confuses so many C++ programmers. Well, here is the solution:
void generate_all_paths(int (*maze)[5], int size);
That is what the function declaration has to look like. An alternative, but fully equivalent is
void generate_all_paths(int maze[][5], int size);
Both are ... |
535,713 | 536,137 | How do you make sense of the error: cannot convert from 'int []' to 'int []' | When compiling the following code:
void DoSomething(int Numbers[])
{
int SomeArray[] = Numbers;
}
the VS2005 compiler complains with the error C2440: 'initializing' : cannot convert from 'int []' to 'int []'
I understand that really it's trying to cast a pointer to an array which is not going to work. But how do ... | There are three things you need to explain to the person you're trying to help:
Arrays can't be passed by value to a function in C++. To do what you are trying to do, you need to pass the address of the start of the array to DoSomething(), as well as the size of the array in a separate int (well, size_t, but I wouldn... |
536,123 | 536,187 | Unicode Basics on Windows | I have a C++ library which I deliver to other developers. One of them needs i18n, so he asked me if I could add L prefix to the strings in the API.
I don't know much about i18n so I have some basic questions:
When I compile my lib with Unicode, can other developers use this build as usual ? Or shall developers also c... | Adding the L prefix changes the string from a char array into a short array. A better alternative is to wrap all your strings with the "TEXT" macro, i.e.
TEXT("My string")
If your build is a Unicode build, all your strings become an array of shorts, but if not, they remain as an array of chars. Windows also provides t... |
536,148 | 536,265 | C++ string parsing (python style) | I love how in python I can do something like:
points = []
for line in open("data.txt"):
a,b,c = map(float, line.split(','))
points += [(a,b,c)]
Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas
How can this be don... | I`d do something like this:
ifstream f("data.txt");
string str;
while (getline(f, str)) {
Point p;
sscanf(str.c_str(), "%f, %f, %f\n", &p.x, &p.y, &p.z);
points.push_back(p);
}
x,y,z must be floats.
And include:
#include <iostream>
#include <fstream>
|
536,267 | 536,290 | C++ slicing in Java / C# | Can C++ slicing apply to other languages too, like Java/C#?
| Slicing means that if you assign a subclass instance to a superclass variable, the extra information contained by subclass is "sliced" off, because the superclass variable doesn't have the extra space to store this extra information of the subclass.
This doesn't happen in Java nor with C#, because all object variables ... |
536,314 | 536,348 | Texturing Spheres with Cubemaps (not reflection maps) | I want to texture a sphere with a cube map. So far my research has thrown up many many results on Google involving making OpenGL auto generate texture coordinates, but I want to generate my own coordinates.
Given an array of coordinates comprising the vertexes of an imperfect sphere (height mapped but essentially a sph... | Are you doing this via GLSL? In that case textureCube accepts a vec3 as texture coordinate, which is a unit vector on a sphere. In your case you would take the coordinate of your fragment with respect to the center of the sphere, normalize it and pass it as a coordinate. No need to worry about the internal representati... |
536,439 | 537,304 | Is modern C++ becoming more prevalent? | When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". std::vector was definitely an advanced topic, something you could learn about if you really wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory.
Today, everywhere I look I s... | Here's how I think things have evolved.
The first generation of C++ programmers were C programmers, who were in fact using C++ as C with classes. Plus, the STL wasn't in place yet, so that's what C++ essentially was.
When the STL came out, that advanced things, but most of the people writing books, putting together cu... |
536,464 | 536,498 | Factory object vs factory function | I have an ABC with several derived classes. To create these derived classes I use the factory pattern:
.h file:
class derivedFactory
{
public:
base* createInstance();
};
.cpp file:
base* derivedFactory::createInstance()
{
return new derived();
}
Is there any advantage to this over just having a free function... | It depends on how flexible your factory needs to be. If the factory needs external information (like from a configuration file, program options, etc) to determine how to construct objects, than an object makes sense. If all you will ever need is in the arguments to factory, than a function is probably fine.
The only ... |
536,469 | 536,523 | I have VS C++ Express. Is there a way to create .DEF files? | I would be extremely appreciative if anybody can help me.
I am learning C++ and I have been trying figure this one out.
Basically, VS C++ Express does not come with the .DEF
template. What other way can I go about creating this file?
Is there a parameter I can set in VS so that the linker
can create this on the fly?
Th... | You can find the syntax of a DF file defined in places like
Exporting from a DLL Using DEF Files
Module-Definition (.def) Files
The bottom of the first link also mentions alternatives to DEF files (e.g. the __declspec(dllexport) directive).
If you don't have a template to create a DEF file, you can create the file ma... |
536,771 | 536,833 | With this technology, would it be possible to compile and run silverlight IL in Flash? | I don't really understand this article. But it sounds like you can compile C/C++ for flash. If that's possible, how hard would it be to compile and run Mono inside flash?
Sounds stupid I know...maybe I'm going crazy with my age.
| Probably is possible, at the first time, but just compile. Let me see if I got where you want go.
Mono can run on-the-fly code, but even now that there is a C# Shell it first compiles to IL (and maybe JIT) and after that it executes. With that technology will be possible to make Flash generate .NET assemblies, but not... |
536,865 | 536,901 | libstdc++ 64bit and 32bit version on the same machine | I am trying to cross compile a version of my software for a 64bit platform. Can I have the 32bit and 64bit version of libstdc++ installed on the same machine without too much worries of breaking my linux install. The Os is 32bit ubuntu.
I have not cross compiled before and just wanted to check that if I set my CFLAGS a... | Sure you can.
Just put them into /usr/lib and /usr/lib64, respectively.
Can't check it on Ubuntu, but on Fedora they get there right from the packages:
[~#] repoquery -q -l libstdc++.i386
/usr/lib/libstdc++.so.6
/usr/lib/libstdc++.so.6.0.10
[~#] repoquery -q -l libstdc++.x86_64
/usr/lib64/libstdc++.so.6
/usr/lib64/lib... |
537,027 | 537,099 | Is it best practice to use COM properties or COM setters and getters in C++? | I am relatively new to development within COM, and I was wondering what the community standard was for access of COM object properties. I have seen both of the following conventions in code:
comObjectPtr->PutValue(value);
and
comObjectPtr->Value = value;
and both seem to work, but I was wondering if there was an inhe... | If I remember correctly, using the property assignment will throw an exception vs. a HRESULT returned in the setter if there is a problem.
Same thing is true of the getter method calls vs. property.
A "benefit" of using the property is that you can use the prop-get values directly instead of having to declare a variabl... |
537,595 | 537,635 | Which sector of software industry uses C++? | Like most people, I learnt C++ after C. I learnt C++ because it was one of those languages which fetched jobs. I am still studying (doing masters) though. One of my cousins has been working as a developer for around 12 years.
He advises me to learn Java so that I can land up in a good job. He says only few sectors like... | Best advice I ever got as an undergraduate was from my languages professor, who told me (paraphrasing here): "Don't memorize languages; don't marry yourself to a language. They're just tools. They all do the same basic things. Instead of learning a specific language, learn the foundations of good software development. ... |
537,820 | 537,851 | What's a good HTML template engine for C++? |
Possible Duplicate:
C++ HTML template framework, templatizing library, HTML generator library
Planning to write a website in C++. Would like to use a template system like Clearsilver, but maybe there's a better alternative?
| Wt (pronounced 'witty') is a C++ library and application server for developing and deploying web applications. It is not a 'framework', which enforces a way of programming, but a library.
|
538,056 | 538,107 | JIT compiler vs offline compilers | Are there scenarios where JIT compiler is faster than other compilers like C++?
Do you think in the future JIT compiler will just see minor optimizations, features but follow a similar performance, or will there be breakthroughs that will make it infinitely superior to other compilers?
It looks like the multi core para... | Yes, there certainly are such scenarios.
JIT compilation can use runtime profiling to optimize specific cases based on measurement of the characteristics of what the code is actually doing at the moment, and can recompile "hot" code as necessary. That's not theoretical; Java's HotSpot actually does this.
JITters can o... |
538,300 | 538,452 | check what number a string ends with in C++ | In a C++ MD2 file loader, I have a lot of frames, each with a name that ends with a number, such as
stand0
stand1
stand2
stand3
stand4
...
stand10
stand11
run0
run1
run2
etc.
How do I get what the string is without the number behind? e.g. a function that changed "stand10" to just "stand"
| Just to complete it, one with find_first_of:
string new_string = str.substr(0, str.find_first_of("0123456789"));
just one line :)
Also, for these things, I like to use regular expressions (althought this case is very simple):
string new_string = boost::regex_replace(str, boost::regex("[0-9]+$"), "");
|
538,476 | 538,510 | Change tab stop size in rendered HTML using Qt's QLabel class | I'm rendering some HTML in a QT QLabel. The HTML looks like this:
<pre>foo\tbar</pre>
(note that I've put "\t" where there is a tab chracter in the code).
This renders fine, but the tab character appears to be rendered as eight spaces, whereas I want it to be redered as 4. How can I change this without having to chan... | According to W3 (HTML4):
The horizontal tab character (decimal 9 in [ISO10646] and [ISO88591]) is usually interpreted by visual user agents as the smallest non-zero number of spaces necessary to line characters up along tab stops that are every 8 characters. We strongly discourage using horizontal tabs in preformatted... |
538,560 | 538,566 | Getting first byte in a char* buffer | I have a char* buffer and I am interested in looking at the first byte in the char* buffer, what is the most optimal way to go about this.
EDIT: Based on the negative votes I might want to explain why this question, I am aware of methods but in the code base that I have been looking for getting first byte people do al... | Just use
char firstByte = buffer[0];
|
538,609 | 538,627 | High resolution timer with C++ and Linux? | Under Windows there are some handy functions like QueryPerformanceCounter from mmsystem.h to create a high resolution timer.
Is there something similar for Linux?
| It's been asked before here -- but basically, there is a boost ptime function you can use, or a POSIX clock_gettime() function which can serve basically the same purpose.
|
538,623 | 538,675 | How portable is an STL typedef? | Is the following code portable?
template<typename In>
struct input_sequence_range : public pair<In,In> {
input_sequence_range(In first, In last) : pair<In,In>(first, last) { }
};
template<typename Arr>
input_sequence_range<Arr*> iseq(Arr* a,
typename iterator_traits<Arr*>::differenc... | difference_type must be an integral type so int* is out.
|
538,661 | 538,691 | How do I draw text with GLUT / OpenGL in C++? | How do I draw a text string onto the screen using GLUT / OpenGL drawing functions?
| There are two ways to draw strings with GLUT
glutStrokeString will draw text in 3D
(source: uwa.edu.au)
and glutBitmapString will draw text facing the user
(source: sourceforge.net)
|
538,711 | 538,777 | How do I delete the closest "Point" object in a STD::List to some x,y? | I have a point class like:
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
and a list of points:
std::list <Point> pointList;
std::list <Point>::iterator iter;
I'm pushing points on to my pointList (although the list might contain no Points yet if none have... | Use a std::list::iterator variable to keep track of the closest point as you loop through the list. When you get to the end of the list it will contain the closest point and can be used to erase the item.
void erase_closest_point(const list<Point>& pointList, const Point& point)
{
if (!pointList.empty())
{
... |
538,738 | 539,992 | Looking for a Hash Function /Ordered Int/ to /Shuffled Int/ | I am looking for constant time algorithm can change an ordered integer index value into a random hash index. It would nice if it is reversible. I need that hash key is unique for each index. I know that this could be done with a table look up in a large file. I.E. create an ordered set of all ints and then shuffle them... | The question is now if you need a really random mapping, or just a "weak" permutation. Assuming the latter, if you operate with unsigned 32-bit integers (say) on 2's complement arithmetics, multiplication by any odd number is a bijective and reversible mapping. Of course the same goes for XOR, so a simple pattern which... |
538,810 | 538,821 | How do I get the current mouse position in C++ / OpenGL? | I know that I can use a Mouse callback function for when a user clicks the mouse, but what if I want to know the current x/y position without the user clicking?
Will I have to use a different callback that gets called on any mouse movement and keep track of the x/y myself or is there a function I can call within GLUT/O... | Register a glutPassiveMotionFunc callback function
See info about callbacks
|
538,856 | 539,007 | Iterating hierarchy of nodes - Visitor and Composite? | Let's imagine I have a collection of nodes that I use for my Renderer class later on. Then I have a Visitor class that can visit node or whole collection. It's simple because my collection of nodes it's simply a wrapper to the std::list with few extra methods.
The problem is I'd like to have a tree like structure for n... | I have something very similar implemented for our system. I wanted a way to compose hierarchy of geometrical object and render them into the volume. I used composite pattern to compose my description (root was Node and then derived child was compositeNode (list of Nodes).
CompositeNode has method accept() which accepts... |
539,058 | 539,099 | How do I have an icon displayed when a setup CD is autoplayed in Windows | I have a setup CD to install a visual studio C++ application I made. It has three files: setup.exe,
AUTORUN.INF,
and app.msi. When I insert the CD the Windows AutoPlay popup shows a generic icon. How do I have my own icon displayed for setup.exe. I also want this for the drive icon after I insert the CD, I think th... | I hate autostart.
In AUTORUN.INF, you can specify the drive icon just next to the setup program:
[AutoRun]
open=setup.exe
icon=*youricon*.ico
|
539,218 | 539,230 | How do I specify a publisher for the setup.exe when a setup CD is autoplayed in Windows | I have a setup CD to install a visual studio C++ application I made. The AutoPlay popup shows "Publisher not specified" for running setup.exe. How do I specify a publisher?
| You need to Sign the executable with a digital certificate. This is to verify that the executable has not been tampered with and is from the publisher.
|
539,251 | 539,307 | Getting the size of an indiviual field from a c++ struct field | The short version is: How do I learn the size (in bits) of an individual field of a c++ field?
To clarify, an example of the field I am talking about:
struct Test {
unsigned field1 : 4; // takes up 4 bits
unsigned field2 : 8; // 8 bits
unsigned field3 : 1; // 1 bit
unsigned field4 : 3; // 3 bits
... | You can calculate the size at run time, fwiw, e.g.:
//instantiate
Test t;
//fill all bits in the field
t.field1 = ~0;
//extract to unsigned integer
unsigned int i = t.field1;
... TODO use contents of i to calculate the bit-width of the field ...
|
539,358 | 540,039 | Calling functions in a DLL from C++ | I have a solution in VS 2008 with 2 projects in it. One is a DLL written in C++ and the other is a simple C++ console application created from a blank project. I would like know how to call the functions in the DLL from the application.
Assume I am starting with a blank C++ project and that I want to call a function ca... | There are many ways to do this but I think one of the easiest options is to link the application to the DLL at link time and then use a definition file to define the symbols to be exported from the DLL.
CAVEAT: The definition file approach works bests for undecorated symbol names. If you want to export decorated symbol... |
539,536 | 539,570 | Disambiguate operator[] binding | I'm trying to compile code from an open source project, and I'm running into a problem where gcc claims that a particular line of code has an ambiguous interpretation. The problem involves a templated class and these two methods:
template <class X>
class A {
public:
X& operator[] (int i) { ... }
operator const ... | The following code compiles for me with g++ 3.x. I don't think your analysis of the problem is correct, but in any case could you post the error message you are getting.
template <class X>
struct A {
X& operator[] (int i) { static X x; return x; }
operator const X* () { return 0; }
};
class B {};
int main() {... |
539,628 | 539,827 | Why doesn't this C++ STL allocator allocate? | I'm trying to write a custom STL allocator that is derived from std::allocator, but somehow all calls to allocate() go to the base class. I have narrowed it down to this code:
template <typename T> class a : public std::allocator<T> {
public:
T* allocate(size_t n, const void* hint = 0) const {
cout << "yo!"... | You will need to provide a rebind member template and the other stuff that is listed in the allocator requirements in the C++ Standard. For example, you need a template copy constructor which accepts not only allocator<T> but also allocator<U>. For example, one code might do, which a std::list for example is likely to ... |
539,824 | 541,827 | Problem with thread-safe queue? | I'm trying to write a thread-safe queue using pthreads in c++. My program works 93% of the time. The other 7% of the time it other spits out garbage, OR seems to fall asleep. I'm wondering if there is some flaw in my queue where a context-switch would break it?
// thread-safe queue
// inspired by http://msmvps.com/blog... | If you want anything with decent performance I would strongly suggest dumping your R/W lock and just use a very simple spinlock. Or if you really think you can get the performance you want with R/W lock, i would roll your own based on this design(single word R/W Spinlock) from Joe Duffy.
|
539,877 | 539,887 | Should non-public functions be unit tested and how? | I am writing unit tests for some of my code and have run into a case where I have an object with a small exposed interface but complex internal structures as each exposed method runs through a large number of internal functions including dependancies on the object's state. This makes the methods on the external interf... | Short answer: yes.
As to how, I caught a passing reference on SO a few days ago:
#define private public
in the unit testing code evaluated before the relevant headers are read...
Likewise for protected.
Very cool idea.
Slightly longer answer: Test if the code is not obviously correct. Which means essentially any cod... |
539,908 | 541,841 | Interprocess Communication Between C# application and unmanaged C++ application | I have two Windows services, the first one written in C# and the second written in
unmanaged C++, I want to know how can I do two-way interprocess communication.
| If the interprocess communication is always going to be done on the same machine, named pipes is the way to go because they are faster than other options.
However, if there is even the slightest chance that this communication might occur across machine boundaries at some point, go with the socket approach. For C++, yo... |
539,939 | 540,193 | Isn't it possible to use 'Repeats' in the lookaheads for boost:regex? | I'm trying to extract some variables in my C++ code nested in blocks
for example, if I have
DEL_TYPE_NONE,
DEL_TYPE_DONE,
DEL_TYPE_WAIT,
I'd like to match
"DEL_TYPE_NONE"
"DEL_TYPE_DONE"
"DEL_TYPE_WAIT"
I made my pattern like this,
std::string pat("(?<=^[ \\t]?)[A-Z0-9_]+(?=,$)");
but I'm keep ... | I found the answer. No from this manual
Lookbehind
(?<=pattern) consumes zero characters,
only if pattern could be matched
against the characters preceding the
current position (pattern must be of
fixed length).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.