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 |
|---|---|---|---|---|
6,266,014 | 6,266,370 | Can you give me an example when auto_ptr_ref is really necessary? | I would like to understand better the mechanics and the issues behind creating library and I have decided to start from the std::auto_ptr.
I am familiar with the syntax and the usage, however I am trying to understand the implementation details. I have implemented my version of the auto_ptr and it looks like this:
#ifn... | Your very first line
test::auto_ptr<double> copyConstructed(source<double>());
is already non-compilable by any standard-compliant compiler. MSVC will allow it when the C++ language extensions are enabled. Disable the extensions and you will immediately realize the need for auto_ptr_ref.
The mechanics behind auto_ptr_... |
6,266,081 | 6,266,100 | C++ deleting inherited class | Let's say there is a class Object and then another class Cat that inherits Object. Next, there is a list of Object* (pointers). Then, I create a new Cat and put it into the list. After some time I want to delete all Cats and call delete on each member of the list. Does it call destructor of Cat?
| Yes if you marked the destructor of object as virtual.
class Object {
public:
virtual ~Object(){} //make the base class destructor virtual
};
class cat : public Object {
public:
virtual ~cat(){} // now this gets called when a pointer to Object that is a cat is destroyed
}
|
6,266,389 | 6,266,428 | Initialization of non constant reference from a constant reference | int main(){
int x = 10;
const int&z = x;
int &y = z; // why is this ill formed?
}
Why is initializing non constant reference to int to a constant reference not correct? What is the reason behind this?
| Well, why shouldn't it be ill-formed?
It is ill-formed because it breaks the obvious rules of const correctenss. In C++ language you are not allowed to implicitly convert the constant access pass to a non-constant access path. It is the same for pointers and for references. That's the whole purpose of having constant a... |
6,266,544 | 6,266,584 | Implementing and calling a static method in a template class | My code is as below:
Interpolation.h
#ifndef INTERPOLATOR
#define INTERPOLATOR
#include <vector>
#include <utility>
template <class T>
class Interpolator
{
public:
static T InterpolateVector(const std::vector<std::pair<T, T>> & Vector, T At);
private:
static T GetBasisValue(T x);
};
template... | As written in the error message: 'Interpolator' : use of class template requires template argument list
You should write:
template <class T>
T Interpolator<T>::InterpolateVector(const std::vector<std::pair<T, T>> & Vector, T At) // Line #22
{
// ...
} // Line #25
|
6,266,804 | 6,266,884 | How to reuse table that would be based on different types in C++? | I have problems to re-use parts of C++ code.
I need to register a number of objects in a table with the following code:
typedef map<ResourceType_t, GeneralResource*> ResourceTable_t;
ResourceTable_t m_resourceTable;
template<class _Ty1,
class _Ty2> inline
pair<_Ty1, _Ty2> make_pair(_Ty1 _Val1, _Ty2 _Val2)
{ // ret... |
However, for my new case, I need to fill the table with objects of type SpecificResource.
Derive SpecificResource from GeneralResource and make it's destructor virtual:
class GeneralResource
{
virtual ~GeneralResource() {}
//..
};
class SpecificResource : public GeneralResource
{
//...
};
If GeneralR... |
6,267,049 | 6,267,073 | C++ concatenation between literal and constant | I am new to C++ and I want to know why the line below is not correct. (SERVER_NAME has been defined as a constant)
L"Initial Catalog=DatabaseName;Data Source=" << SERVER_NAME << ";"
I get these errors:
error C2296: '<<' : illegal, left operand has type 'const wchar_t [...'
error C2308: concatenating mismatched string... | operator<< is not a concatenation operator, it's a special overloaded operator by stream types to let you send data to stream. It only works if you're using a stream.
You have two options here. First, you can use a std::wstring:
std::wstring(L"Initial Catalog=DatabaseName;Data Source=") + SERVER_NAME + L";";
Or you ca... |
6,267,101 | 6,282,620 | Open an emacs org-mode file from C++ source code and automatically create an item | I'm working on a C++ project. Suppose I have the following directory structure:
project/
project/src
And I have the following files:
project/ChangeLog
project/todo.org
project/src/foo.cpp
I can work on the C++ source code in foo.cpp and then add a line into the ChangeLog file just with C-x 4 a as this page describes.... | While org-mode is documented extensively, I do find the online manual to be
very dense. Luckily, there are many good tutorials online, but it's sometimes
hard to find the answer to a specific problem.
I suggest reading the org-mode manual section on Capture. You'll need to do a
little setup and the specifics depend on ... |
6,267,196 | 6,267,225 | Question on Typedef usage in C++ | I wrote the following piece of code on codepad but I do not understand how/why it should compile.
#include<iostream>
using namespace std;
typedef double dObject;
typedef int iObject;
typedef void (*swapfuncptr)(dObject, dObject);
void swap(dObject a,dObject b) {
cout << a << " " << b << endl;
dObject tmp;
tmp = a;
... | int is implicitly convertable to double. Creating a typedef for double does not change that.
|
6,267,308 | 6,889,881 | gdb python programming: how to write code that will set breakpoints to every method of a C++ class? | I would like to be able to set breakpoints to every method of a C++ class in gdb.
I think the easiest way to do this is probably python, since now python has complete access to gdb. I know very little python, and with gdb on top of it, it's even harder. I am wondering if anyone knows how to write a class python code ... | Assuming you compiled with debugging symbols, you dont even need python for this:
rbreak source.cpp:.
|
6,267,418 | 6,267,683 | Eclipse and OpenCV on Ubuntu | I have installed Eclipse+CDT and OpenCV with:
$ sudo apt-get install libcv1 libcv-dev libcvaux1 libcvaux-dev \
libhighgui1 libhighgui-dev \
opencv-doc \
python-opencv
After that I've opened Eclipse and created a new c/c++ project.
So I've typed this code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#inclu... | Open a terminal and execute:
pkg-config --cflags opencv
On my system it returns:
-I/usr/local/include/opencv -I/usr/local/include
Those are the directories you'll have to add on Eclipse to compile your application.
Or, you could try replacing your includes for:
#include <opencv/cv.h>
#include <opencv/highgui.h>
|
6,267,477 | 6,276,428 | How to insert text to rich edit control in Win32 while preserving any previous formatting | I'm developing chat application in win32. Currently i'm dynamically allocating memory for rich edit controls text, append new line and set the new text with SetWindowText.
When a message arrives with specific keywords the app colors the line and appends it to the chat window. Everything's fine. Problem arises when next... | Ok, I've solved it. Apearantly I was replacing the text with unformated version of it. Here's how to properly append text to rich edit control:
CHARRANGE cr;
cr.cpMin = -1;
cr.cpMax = -1;
// hwnd = rich edit hwnd
SendMessage(hwnd, EM_EXSETSEL, 0, (LPARAM)&cr);
SendMessage(hwnd, EM_REPLACESEL, 0, (LPARAM)stringtoappend... |
6,267,575 | 6,268,232 | How to check if my window gets hidden/visible? | If i press the "show desktop" button in Windows7, my program will still think its not minimized, and if i press WIN+D while my program is focused, only then my program will catch this minimize command. How can i check for 100% sure that my program is visible or not?
Here is my main loop:
while(!done){
if(PeekMessag... | WM_ACTIVATE is sent when another window becomes active. When you say show desktop, no other window becomes active, so technically, your app is still active, even though it has been minimized.
You probably want to watch for WM_WINDOWPOSCHANGED. You can look at the flags to see what type of position event it was, or yo... |
6,267,596 | 6,267,879 | Windows: Message-only window appears when I call back from native to managed code | After quite some effort, I managed to capture Windows Messages from a third party MFC dll (I asked about that here). To make it short, I had to create a Message-only window with a message loop which captured the third party dll's messages.
Said Message-only window must remain hidden. And it does, initially, since I pas... | The window you create is not related to the console window you see. Something that you call creates a console window (or you program is marked as a console application in which case the console is created when your application is launched).
Put a breakpoint at AllocConsole() to find who is creating the console.
|
6,267,680 | 6,267,698 | How do I build an executable file in visual studio 2010 that doesn't rely on the .NET 4 SDK DLL/Library files? | How do I build an executable file in visual studio 2010 that doesn't rely on the .NET 4 SDK DLL/Library files?
I'm getting an error that informs that the system.dll is missing, I'm assuming this is part of the SDK.
| If you're building a .Net application this is simply not possible. A .Net application requires the .Net runtime to be installed on the machine that it is run on.
If you're trying to build a pure C++ application which has no .Net framework support then make sure the Common Language Runtime support is disabled for the ... |
6,267,771 | 6,268,013 | OpenCv No rule to make target | this is my first example with OpenCv:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "opencv/cv.h"
#include "opencv/highgui.h"
int main(int argc, char *argv[])
{
IplImage* img = 0;
img=cvLoadImage("/home/michele/Pictures/sensor.png"); // carica l'immagine
cvNamedWindow("mainWin", CV_... | I think you need to see a tutorial on how to configure Eclipse.
You could also try to compile your application manually (from the cmd-line):
g++ 1st.cpp -o app `pkg-config --cflags opencv` `pkg-config --libs opencv`
|
6,267,965 | 6,268,151 | Sending text to static control | I ve got problem here.
I want to get info from AVI file and then ask user what he wants to do with it. For this I have dialogbox and there (among other things) I have static text control where I want the info text to appear. The code:
BOOL GetAviInfo(LPSTR szFileName)
{
AVIFileInit();
PAVIFILE avi;... | DialogBox only returns after the dialog ends. DialogBox returns a hwnd which is where you should be sending the messages.
|
6,267,973 | 6,269,726 | boost::interprocess::scoped_lock application crash inside lock | I'm using boost::interprocess::scoped_lock, if the application crash for some reason inside the scope the mutex isn't released.
Next time the application is executed (without restarting the computer), the mutex is locked.
How's this intended to work?
I give a simple example of the code below.
{
boost::interprocess:... | That's seems perfectly logic to me :)
As your application crash, the mutex which maps to your OS interprocess communication mechanism (IPC) is not released. When your application restart it tries to get the mutex without success !
I suppose your application has different subsystems (processes) that need to be synchroni... |
6,268,228 | 6,268,289 | Why is my constructor with non const reference as argument allowed to be called with temporary objects? | I have a sample code below.
#include<iostream>
template<typename T>
class XYZ
{
private:
T & ref;
public:
XYZ(T & arg):ref(arg)
{
}
};
class temp
{
int x;
public:
temp():x(34)
{
}
};
template<typename T>
void fun(T & arg)
{
}
int main()
{
XYZ<temp> abc(temp());
fun(temp()); //Th... | XYZ<temp> abc(temp());
It compiles, because it is NOT a variable declaration. I'm sure you think its a variable declaration when the fact is that its a function declaration. The name of the function is abc; the function returns an object of type XYZ<temp> and takes a single (unnamed) argument which in turn is a funct... |
6,268,413 | 6,268,456 | How to make an "ambiguous symbol" unique with VS 2008 | I have some trouble with #define statements in my C++ code, however I'm not familiar how to handle this in VC++:
>filetaint.cpp
1>.\filetaint.cpp(272) : error C2872: 'UINT32' : ambiguous symbol
1> could be 'C:\Program Files\Microsoft SDKs\Windows\v6.0A\\include\basetsd.h(82) : unsigned int WIND::UINT32'
1> ... |
I want it to use the latter.
Then qualify your usage with the namespace name: LEVEL_BASE::UINT32.
Alternatively, remove the using directives from your code and qualify all of the names that you use from the libraries. It's a good idea to avoid using directives in most cases: they are far more trouble than they are... |
6,268,768 | 6,268,843 | C gotchas and mistakes for C++ programmers | If you are C programmer or C++ programmer that knows C well, can you tell me what are the most common mistakes/pattern/style that you noticed from C++ programmers? For example, do you noticed a difference between a C program written by a C programmer vs C program written by C++ programmer? If you can provide a list spe... | One thing that I see happen quite frequently is properly freeing allocated memory. Especially associated with structures containing dynamically allocated memory. With C++, destructors are automatically called and if properly written they take care of the associated objects clean up. With C you have to remember to ei... |
6,268,778 | 6,268,812 | looking for an explanation of .NET DataTable events and handling | I'm having trouble wrapping my head around .NET DataTable events, handling, actions, etc.
I have attempted to understand from the MSDN library, but I find I haven't got an understanding of how it all works together. I also haven't been able to find any other source (by googling) that explains the ins and outs of it.
... | It looks like you're getting confused between the events themselves and the EventArgs parameters that get passed to your actual event handler.
When you register to handle an event, there are a couple of things you have to know. I'll use your ColumnChanged event as an example.
The first is that the Event you're register... |
6,269,106 | 6,269,273 | C Server - "The connection was reset" | I modified beej's guide to networking example (as seen below) to pass back a html response to a browser. I am getting "The connection was reset" every few refreshes, and can't seem to figure out why? Its as if it is closing the connection before it sends out the html response.
Any ideas, or suggestions to debug?
Ed... | So there's 2 errors here (3 really, the last one being that if you want to talk to a browser you really have to implement HTTP properly which is non-trivial)
You're sending the response immediately when you accept a client. A browser being a bit slow might then receive a response even before it's finished sending a re... |
6,269,124 | 6,269,306 | Perfectly emulate nullptr | I got tired of waiting for compiler support of nullptr (gcc 4.6 does but it's so new few distributions support it).
So as a stop gap until nullptr is fully supported I decided to emulate it. There are two examples of emulation: one from here, and one from wikibooks.
Of note, neither implementation mentions an operator... | You compiled it with C++0x compiler that failed for unknown reason. It compiles fine in C++03.
|
6,269,313 | 6,270,235 | Functor that calls a function after dereferencing? | Is there a small functor in the C++ standard or in Boost that wraps around another functor, but dereferences a pointer before it calls that functor?
I'm thinking of something like this:
template<class F>
struct DerefCmp {
template<class T>
bool operator()(T* v) const {
return F(*v);
}
};
I'd use it in a cont... | I am not aware of any function object in the C++ Standard Library or in Boost that does this (that's not to say there isn't one; I am not familiar with everything in the Boost libraries :-P).
However, writing your own is rather straightforward. Consider the following:
template <typename Predicate>
class indirect_binar... |
6,269,542 | 6,269,622 | Is using zlib (or similar) compression worth/recommended when transmitting JPEG-compressed screen tiles over network (remote screencasting app)? | I'm starting to implement some sort of remote screencasting (VNC-alike) client/server software in C++ (Windows platform), which just transmits the screen updates (image tiles) over the network.
The screen is divided in blocks and each tile is compressed into JPEG (probably I'll use libjpeg-turbo), before sending over n... | Absolutely unneccessary.
Better option is to use both methods: count the colors in the block and use zlib/rle/etc for few colors and jpeg for many. That's the very basic approach. I recommend you to take a look at the Remote Framebuffer Protocol of the VNC.
|
6,269,676 | 6,269,796 | Visual Studio generated binaries | Need quick help from win developers. Please correct me where I got it wrong. Thank you!
I built a C++ library from the source code and got the following files:
*.dll. These go into a folder listed in the PATH environment variable.
*.lib. These go into a folder where Visual Studio searches for libraries.
*.pdb. These ar... | If you're going to debug the library on the same computer where you built it, you don't need to move .pdb files at all. Otherwise put them along with the .dll. You might also need to strip the full paths to pdb from the dll using the /PDBALTPATH option.
You probably won't need the .exp files at all, since you're using ... |
6,270,245 | 6,403,781 | Return C++ object to Java | I got a couple of JNI functions that have to work on the same c++ object. I would like to save that object in the java object through which the JNI functions are invoked, but it seems that Java has no way to store pointers for functions to access later.
Okay I realize that I'm doing a terrible job explaining myself so ... | I think the standard way of going about it is to use a long in java to store the pointer, that way your java code will work on both 32bit and 64bit systems. Obviously you need to compile a different C++ .so/.dll for each platform.
So a simple java wrapper for a C++ class with one method will look something like:
class ... |
6,270,272 | 6,270,341 | How would I get input from a QLineEdit in a Qt Creator GUI? | I am new to Qt Creator programming, and I am having an extremely difficult time finding decent resources to help get an absolute beginner started. I want to create a simple window that allows the user to input a string into a QLineEdit box, then pick a value from a drop-down box (QComboBox). They then click a push butt... | In Qt Creator, click Help | Contents, and then Qt Reference Documentation | Tutorials and Examples. There you will find dozens of example projects that you can try. Take a day or two to look through them before starting on your own project.
|
6,270,435 | 6,270,696 | Symbol lookup error problem in QT project | I am trying to add a new library to the Qt plugins folder.
That plugin is located here:
http://qt.gitorious.org/qt-solutions/qt-solutions/trees/master/qtjp2imageformat
It says that it requires jasper to build, so I downloaded jasper, and built it, generating a libjasper.a in my jasper/lib folder (which is in my home d... | You didn't say which distro you are using, but the simplest would be to install the jasper package and link your application to it's library.
by the way, did you build static library (.a) or dynamic (.so)? Try building a dynamic library
|
6,270,525 | 6,270,689 | Sending a C# string as an argument to a unmanaged C++ DLL function | I want to send my C# string to a C++ DLL function. I have succeeded, both with StringBuilder:
[C#]
public static extern int installHook(StringBuilder directory);
StringBuilder myText = new StringBuilder(512);
myfunc(myText);
[C++]
int OPENGLHOOK_API myfunc(char* directory)
{
::MessageBoxA(NULL,directory,"test123",... | I believe the problem is the default calling convention between the two languages. C# is __stdcall and c++ is __cdecl, I believe. Try explicitly stating __stdcall on your C++ method signatures and see if that doesn't resolve the error.
C++:
int OPENGLHOOK_API __stdcall installHook(wchar* directory)
C#:
[DllImport( "yo... |
6,270,565 | 6,270,818 | Passing XML between .NET and native c++ | I have a project in native c++ that currently communicates with a c# project through COM. I'd like to replace COM with a c++\cli wrapper. Both projects use XML, and pass it back and forth using COM Variant. If I switched to a c++/cli wrapper, what could I use to pass XML between the layers?
| Well, we had a similar arrangement and we switched to use a simple socket to pass the messages. In our case it was a native c/c++ app and a managed app - so two processes. Gave us the advantage to put them on separate PCs as well. If the native project is just a DLL you call into you might just want to add a SendMessag... |
6,271,110 | 6,271,156 | Basic security mistakes to avoid in C | As a beginner to C, i want to know what are the basic security tips every C programmer should be familiar with. Strictly referring to C.
| Think that the main problem is buffer overflow.
It may happen using function like fgets, or scanf, without specifying the max number of bytes to read. A malicious input string larger than allocated buffer may overrite the return address in the stack causing the execution of the supplied exploit.
|
6,271,399 | 6,271,808 | Would this cause a memory leak? | Okay, so I am having somewhat of a disagreement with someone else, and I was hoping someone who knows more about c++ than either of us can clear this up. Say we have this block of code somewhere inside a function(for a tilemap engine):
void loadTiles()
{
Tile* tile = new Tile();
Level->addTile(x, y, tile); //x and y ar... | Let's look at each piece of code.
1) Allocating memory
Tile* tile = new Tile();
This creates a new Tile object on the heap and stores the memory address in the variable tile. Keep in mind that the variable tile is only a pointer, not the object itself.
2) Copying the reference
void Level::addTile(int x, int y, Tile *... |
6,271,452 | 6,271,951 | Variable of a template class with a template class template parameter set to a base template of the derived template with the variable | I'm attempting to have a derived class (normal template) that has a variable of a template type that has as its template class parameter the type of a base class (normal template, same parameter as the derived class) of the derived class (the one with the variable). This makes VC++ incredibly angry at me, and I am inc... | Unqualified use of innocuousBase inside of derivOfDoom<> is interpreted as innocuousBase<VT>, much as unqualified use of derivOfDoom in that context would be interpreted as derivOfDoom<VT>. I don't remember offhand whether or not this is standard-conformant behavior, but the workaround is trivial: fully qualify innocuo... |
6,271,615 | 6,271,631 | Any way to prevent dynamic allocation of a class? | I'm using a C++ base class and subclasses (let's call them A and B for the sake of clarity) in my embedded system.
It's time- and space-critical, so I really need it to be kind of minimal.
The compiler complains about lack of a virtual destructor, which I understand, because that can get you into trouble if you alloca... | You can poison operator new in just the same way as you can a copy constructor. Just be sure not to poison placement new. A virtual destructor would still be a fine recommendation.
int main() {
char data[sizeof(Derived)];
if (condition)
new (data) Derived();
else
new (data) Base();
Base*... |
6,271,665 | 6,271,688 | Object's structure overriding defined methods? | I have a class called Object:
class Object {
public:
Vector pos;
float emittance;
Vector diffuse;
virtual float intersection(Ray&) {};
virtual Vector getNormal(Vector&) {};
};
And another class which inherits it:
class Sphere: public Object {
public:
float radius;
virtual float inters... | You did not declare the function as virtual and make sure that the method signature matches. Change it to:
class Object{
virtual float intersection(Ray) {};
virtual Vector getNormal(Vector) {};
}
class Sphere: public Object {
...
virtual float intersection(Ray ray) {
...
|
6,271,817 | 6,271,870 | Casteljau's algorithm - practical example | I have a dataset with about 50 points (x,y) and I would like to draw a smooth curve that can pass as closer as possible on those points.
I have heard about Casteljau's algorithm for splines but after hours searching on google I was not able to find a single piece of code I can use.
As far as I understood, to use this a... | How about in C#?
private void drawCasteljau(List<point> points) {
Point tmp;
for (double t = 0; t <= 1; t += 0.001) {
tmp = getCasteljauPoint(points.Count-1, 0, t);
image.SetPixel(tmp.X, tmp.Y, color);
}
}
private Point getCasteljauPoint... |
6,272,012 | 6,272,033 | Creating a multi-lined textbox/textfield in C++, not VC++ | I was wondering how to create a text box that can respond to the "enter" key and create a new line just like the field I am typing in now.
CreateWindow ("edit", 0, WS_CHILD | WS_VISIBLE | WS_BORDER, 5, 5, 130, 20, hwnd, (HMENU) 1000, GetModuleHandle (NULL), NULL);
That is what I have currently, but when I create it, i... | You need to use the "ES_MULTILINE" flag. See Edit Control Styles
|
6,272,335 | 6,272,379 | Trying to clip the cursor to my window isn't working? | I'm trying to make the windows cursor stay inside my window. I'm using freeglut and C++ Everything is working great so far, except for the part where I try to use ClipCursor to keep the cursor locked in my window, it moves freely like the command wasn't even called. It worked fine in a project I have that doesn't use g... | FindWindow must be failing. Try passing 0 as the first parameter.
|
6,272,392 | 6,272,431 | Simplifying find operation on vector | I'm using a vector for several arrays in my code due to the requirement of random access to the individual elements of the array. Some user GUI operations require searching through the array (but not enough to warrant the use of std::map), so littered through the code is this:
if (std::find(array.begin(), array.end(), ... | Use whatever you prefer. I believe doing a function is better though, it avoids the hassle of creating a new class and using it everywhere. Something like :
bool array_contains(searchFor)
{
return std::find(array.begin(), array.end(), searchfor) != array.end();
}
|
6,272,445 | 6,272,468 | C++: any way to prevent any instantiation of an abstract base class? | Aside from having a pure virtual function, is there a way to prevent an instantiation of an abstract base class?
I can do this:
class BaseFoo
{
virtual void blah() = 0;
};
class Foo : public BaseFoo
{
virtual void blah() {}
};
but I'd like to avoid a vtable. (as per my other question about virtual destructors... | A really obvious way is to declare a protected constructor, and to declare public constructors in the non-abstract derived classes.
This of course shifts the burden of corectness to the derived classes, but at least the base class is protected.
|
6,272,450 | 7,729,234 | How Do I Give a GtkEventBox a Transparent Background? | On a GTK dialog, I have a GtkLabel wrapped in a GtkEventBox so that it can receive click events (navigates to a web page for more info). Functionally it works great.
However, when I add the label to the event box, the label's background is no longer transparent -- the label now has the default window background color.... | GtkEventBox works by creating a new X window to receive the events. By default it uses an input/output window. Call gtk_event_box_set_visible_window to make the window invisible (and input only.)
|
6,272,676 | 6,272,713 | array of derived classes doesnt work if derived class has private variables | I have an abstract base class and 2 different classes that implements a virtual function from the baseclass.
I put these in an array, and for "derived1" class this works.
If I however make an array of "derived2" class that has some extra private variables, the code will compile but errors at runtime.
#include <iostream... | An array of derived1 objects (or derived2 objects) cannot be interpreted as an array of base objects. Arrays are not polymorphic. Only standalone object can be polymorphic, i.e. derived1 has IS-A relationship with base. But array of derived1 does not have IS-A relationship with array of base. Neither of your arrays (ne... |
6,272,794 | 6,273,177 | Debug Assertion Failed - C++ | I am trying to have a pointer in a struct point to an array of structs of another type. Here is my code:
struct Mesh
{
long masterRef; // The global fragment number
long polygonCount; // Number of polygons in the mesh
long vertexCount; // Number of verticies in t... | I think your problem is that you are "trying to have a pointer in a struct point to an array of structs". To declare a pointer to an array, you need a slightly different syntax: Mesh (*meshptr)[array_size];. As your structure stands now, meshptr is a pointer to a single Mesh object, not an array. Attempting to use t... |
6,272,817 | 6,272,973 | Why is vector(size) slower than new[]? | I was benchmarking some STL algorithms, and I was surprised by the time taken by the following code: (I measured the g++ compiled code [no optimizations] with the time command)
#include <vector>
struct vec2{
int x, y;
vec2():x(0), y(0) {}
};
int main(int argc, char* argv[]){
const int size = 200000000;
... | The speed will depend on implementation, but most likely reason for the vector being slower is that vector cannot default-construct its elements. Vector elements are always copy-constructed. For example
std::vector<vec2> tab(size);
is in reality interpreted as
std::vector<vec2> tab(size, vec2());
i.e. the second arg... |
6,272,925 | 6,272,959 | C++ Object Deserialization - Where to start | I have a chunk of bytes taken from a recording file that represents a C++ object. I've been given the class definition for the object. How do I convert the data(chunk of bytes) to an object?
I keep seeing references to boost but don't think I can use it since it was not used to serialize the object to begin with.
Anyo... | You're correct -- Boost.Serialization can't help you deserialize an object it didn't serialize. You'll need to do unformatted input with std::ifstream (calling its read member function to extract byte ranges). Be sure to open the stream in binary mode.
|
6,272,931 | 6,274,239 | loading and calling C# (assembly) from a sql stored proc | suppose I have simple C# code to print HELLO WORLD as shown in here
using System;
using System.Data;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
public class HelloWorldProc
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void HelloWorld()
{
SqlContext.Pipe.Send("HELLO WO... | Well, if you're going to go down this path, you might skip over using C# as a wrapper for your C++ dll (since it sounds like you're just trying to use the SQL Server CLR integration as a means to call into a C++ routine).
Instead, you could create and register a C++ COM+ Application (example) on the server and invoke t... |
6,272,966 | 6,272,987 | Problem with getting multiple random numbers |
Possible Duplicate:
Recommended way to initialize srand?
I am extracting frames from AVI. I want the user to choose wether he wants to get all frames from user given range or get all frames available or get user given number of random frames. First two functions work just fine. But with random frames I always get on... | You are initializing the pseudorandom number generator with the same seed. Initialize it just once, and with a semi-random (v.g., milliseconds in the system clock) number.
|
6,273,176 | 6,273,465 | What exactly is "broken" with Microsoft Visual C++'s two-phase template instantiation? | Reading questions, comments and answers on SO, I hear all the time that MSVC doesn't implement two-phase template lookup / instantiation correctly.
From what I understand so far, MSVC++ is only doing a basic syntax check on template classes and functions and doesn't check that names used in the template have atleast be... | I'll just copy an example from my "notebook"
int foo(void*);
template<typename T> struct S {
S() { int i = foo(0); }
// A standard-compliant compiler is supposed to
// resolve the 'foo(0)' call here (i.e. early) and
// bind it to 'foo(void*)'
};
void foo(int);
int main() {
S<int> s;
// VS2005 will res... |
6,273,185 | 6,273,268 | Getting cursor position on Mac OS X | I want to get the cursor position. Is there any standard function for this?
I'm trying to make my program in C++. I'd like to avoid Cocoa. Not that I have anything against it, but I'd like to make my program cross-platform.
| You can use the following Core Graphics API, in CGEvent.h:
CGEventRef event = CGEventCreate(NULL);
CGPoint cursor = CGEventGetLocation(event);
CFRelease(event);
(Note that you can still use Cocoa in a cross-platform program, you just need to separate platform-specific code into different files instead of using #define... |
6,273,275 | 6,273,322 | How to reclaim memory after glutMainLoop is activated? | According to OpenGL documentation,
3.1 glutMainLoop
glutMainLoop enters the GLUT event processing loop.
Usage
void glutMainLoop(void);
Description
glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program. Once called, this routine will never return. It will call ... | The "recommended" mechanism is to use the atexit or onexit function to schedule a function to be called when the program is exiting:
void exitProgram() {
// cleanup code
}
// then put this in main():
atexit( exitProgram );
Note that as soon as a program exits, the operating system cleans up all resources, includi... |
6,273,437 | 6,273,662 | When is aggregate initialisation valid in C++11? | Lets say we have the following code:
#include <iostream>
#include <string>
struct A
{
A() {}
A(const A&) { std::cout << "Copy" << std::endl; }
A(A&&) { std::cout << "Move" << std::endl; }
std::string s;
};
struct B
{
A a;
};
int main()
{
B{A()};
}
Here, I believe struct A is not an aggregate, as it has ... | According to the new standard, clause 8.5.1 (Aggretates), a sufficiently simple type (e.g. no user-defined constructors) qualifies as an aggregate. For such an aggregate Foo, writing Foo x{a, b, ... }; will construct the members from the list items.
Simple example:
struct A
{
std::unordered_map<int, int> a;
std::st... |
6,273,670 | 6,273,722 | C++ std::sort on vector<object*> - Assignment of Read-only Location | UPDATED SOLUTION:
With my particular problem, the sort call was inside a Render function marked as const. By either removing the const (not my preference) or putting the sort in another function (in this case, the bottom of my Update), the problem is taken care of. As several answerer's suggested, it WAS a const prob... | Just from your code, I guess that your Object::GetDist() method is not const. In C++, a const object of a class can call only const members.
If this is the case then you have 2 ways to remove this error.
(1) Make GetDist as const:
class Object {
int GetDist () const; // <-- add const
};
(2) Change SortByDistance:
b... |
6,273,793 | 6,273,857 | How to specialize Iterator by its value type, in C++? | Is it possible to specialize an Iterator template parameter by its value_type?
I have a function with the following prototype.
template<typename InputIterator>
void f(InputIterator first, InputIterator last);
And I want to handle specially if InputIterator::value_type is SomeSpecificType.
| You can use some intermediate structs to get the partial template specialisation that you need. Something like this should do the trick
template<typename T, typename V>
struct f_impl
{
static void f( T first, T last ) {...}; //Default version
};
template<typename T>
struct f_impl<T, SomeSpecificType>
{
static voi... |
6,273,958 | 6,274,011 | Are the default constructor and destructor ever inline? | I'm curious if the default constructor and destructor that the compiler generates are inline or not, because I can justify it either way. On the one hand, you want the default constructor/destructor to not be inline so that adding them later doesn't break ABI (because object files compiled when only the defaults were t... | The C++ standard says, in 12.1[class.ctor]/5
An implicitly-declared default constructor is an inline public member of its class
and in 12.4[class.dtor]/3
An implicitly-declared
destructor is an inline public member of its class.
|
6,273,968 | 6,273,989 | Why can't the operator=() function be inherited by the derive class |
Possible Duplicate:
Trouble with inheritance of operator= in C++
I updated the code
#include <QtCore/QCoreApplication>
class Base
{
int num;
public:
Base& operator=(int rhs)
{
this->num = rhs;
return *this;
}
};
class Derive : public Base
{
public:
int deriveNum;
using Base:... | It is inherited by the derived class. However, the derived class has it own operator = (implictly declared by the compiler), which hides the operator = inherited from the parent class (search and read about "name hiding" in C++).
If you want the inherited operator = to become visible, you have to explicitly unhide it
c... |
6,274,008 | 6,274,062 | Why would someone use #define to define constants? | It's simple question but why would someone use #define to define constants?
What's the difference between
#define sum 1 and const int sum = 1;
| #define has many different applications, but your question seems to be about one specific application: defining named constants.
In C++ there's rarely a reason to use #define to define named constants.
#define is normally widely used in C code, since C language is significantly different from C++ when it comes to defi... |
6,274,116 | 6,274,139 | If I return an STL container from a function by value will GCC copying all of the elements individually? | If I have the following function declaration that returns a std::list<Triangle*> by value:
std::list<Triangle*> getAllAbove(Triangle* t);
when I return the std::list<Triangle*> (which is created on the stack in getAllAbove) at the end of getAllAbove, will GCC be able to optimize out the call to std::list<Triangle*>'s ... | Well, the alternative way to bypass copying is to use the "return parameter" idiom instead of using the return value of the function
void getAllAbove(Triangle* t, std::list<Triangle*>& result);
Instead of forming the result "on the stack" as you do now, form it directly in result parameter (i.e. in the recipient list ... |
6,274,136 | 6,274,152 | Objects of different classes in a single vector? | In my code, I have a set of objects:
class Sphere { ...
class Plane { ...
...
And I need to use a collection of them (they will all have different types) in a vector. How would I add objects of different classes to a vector?
| Sphere and Plane would need a common base type, or your vector would need to be composed of void*'s.
Common base type (better):
class Shape { ... };
class Sphere : public Shape { ... };
class Plane : public Shape { ... };
std::vector<Shape*> shapes;
or void*'s (not great):
std::vector<void*> shapes;
|
6,274,226 | 6,274,430 | Overloading [] in C++ to return lvalue | I'm writing a simple hash map class:
template <class K, class V> class HashMap;
The implementation is very orthodox: I have a heap array which doubles in size when it grows large. The array holds small vectors of key/value pairs.
Vector<Pair<K, V> > *buckets;
I would like to overload the subscript operator in such a ... | It sounds like what you want is a "smart reference", which you cannot generically implement in C++ because you cannot overload the dot operator (among other reasons).
In other words, instead of returning a reference to a V, you would return a "smart reference" to a V, which would contain a pointer to V. That smart ref... |
6,274,390 | 6,274,520 | Array C[]=A[]*B[] in high-performance calculation | I believe it is usual to have such code in C++
for(size_t i=0;i<ARRAY_SIZE;++i)
A[i]=B[i]*C[i];
One commonly advocated alternation is:
double* pA=A,pB=B,pC=C;
for(size_t i=0;i<ARRAY_SIZE;++i)
*pA++=(*pB++)*(*pC++);
What I am wondering is, the best way of improving this code, as IMO following things needed to ... | The rule for performance are
not yet
get a target
measure
get an idea of how much improvement is possible and verify it is worthwhile to spend time to get it.
This is even more true for modern processors. About your questions:
simple index to pointer mapping is often done by the compilers, and when they don't do it... |
6,274,510 | 6,274,528 | Incomplete type using typedef function pointer | I've got an abstract base class that defines an interface to data sinks. Concrete implementations of data sinks are acquired via factories. In an effort to tidy up code, I created a typedef for the factory method that returns new DataSink objects from within the DataSink abstract base class.
#include <memory>
#includ... | get_new_data_sink_function_type is not a function type, but the type of a pointer to a function. boost::function requires a function type (or signature).
In addition, an abstract class need not be an incomplete type (and it's not at the site of your typedef). The 'incomplete type' part of the warning likely stems from ... |
6,274,598 | 6,274,621 | How do I set file permissions when opening a file in C++? | In C++, I want to open a file and set its permission, but I failed. Below is my program:
string filename="test.cnf";
ofstream ofile;
ofile.open(filename.c_str(),O_RDONLY);
ofile.close()
But I get the following error:
error: invalid conversion from 'int' to 'std::_Ios_Openmode'
error: initializing argument 2 of 'voi... | There is not O_RDONLY mode for fstream. You should use one of:
ios::app
ios::binary
ios::ate
ios::in
ios::out
ios::trunc
Or their combinations (say ios::app | ios::binary). For your case you should use ios::in (maybe with ios::binary). Look at this for more details.
|
6,274,822 | 6,794,523 | Boost Python No to_python converter found for std::string | So, I am trying to create a to_python converter that will allow me to return a boost::optional from an exposed function and have it treated as T if the optional is set and None if not. Based on a post I found on C++Sig, I wrote the following code.
template<typename T>
struct optional_ : private boost::noncopyable {
... | Ok here is the entire to and from optional converter based on the original C++ sig post but rewritten to use the high level boost.python API (sorry about the weird spacing).
template<typename T>
struct optional_ : private boost::noncopyable
{
struct conversion :
public boost::python::converter::expected_from_pyth... |
6,275,383 | 6,275,532 | Which function will it call? | Here is the code, I wrote the comments.
The question is I don't know which function will be called after the function unhide in the Derive class.
#include <CONIO.H>
#include <IOSTREAM>
#include <string>
using namespace std;
class Base
{
string strName;
public:
Base& operat... | Standard 7.3.3-4 (from an old draft, but in this regard still valid):
If an assignment operator brought from a base class into a derived class scope has the signature of a copy-assignment operator for the derived class (class.copy), the using-declaration does not by itself suppress the implicit declaration of the de... |
6,275,412 | 6,275,561 | Is there an easy way to assign a struct array | I have a struct array like this:
struct VERTEX_FMT
{
float x, y, z, u, v;
const static DWORD FVF = (D3DFVF_XYZ | D3DFVF_TEX1);
};
VERTEX_FMT vertices[] = {
{-1.0f, -1.0f, 0.0f, 0.0f, 0.0f},
{-1.0f, 1.0f, 0.0f, 0.0f, 1.0f},
{ 1.0f, -1.0f, 0.0f, 1.0f, 0.0f},
{ 1.0f, 1.0f, 0.0f, 1.0f, ... | Only if you wrap the array in another struct. Arrays are pretty broken in C, and C++ decided that std::vector was sufficient, and that any attempt to fix C style arrays either wouldn't go far enough to make a difference, or would break compatibility to a point where you couldn't talk of C style arrays any more.
For PO... |
6,275,584 | 6,276,008 | SH_DENY* equivalent in Solaris | Solaris equivalent to fcntl.h and share.h
I am porting a big C++ project from Windows/VS to Solaris/Eclipse/gcc. The Windows code uses _SH_DENYNO etc which are in a Microsoft file share.h. The same file on the Sun at /usr/include/sys does not contain these, nor does any other I can find.
I suppose they have another nam... | I think solaris, like other unix, is always _SH_DENYNO. You need explicit locking of files, try lockf or fcntl.
|
6,276,040 | 6,276,189 | Strange use of strlen | I tried to compile the follow sample code:
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
int main ()
{
if (strlen <= 0) {
cout << "trace1" << endl;
return 0;
}
cout << "trace2" << endl;
return 0;
}
The strange thing is that it compiles successfully. Do you have any ide... | If you do the same with other functions than strlen, this sample code will print trace2 because strlen is a pointer to function size_t strlen ( const char * str ) and it's value should be a positive number.
cout << (size_t *) strlen << endl;
cout << (size_t *) strcat << endl;
for example the code above prints:
0x7fff8... |
6,276,068 | 6,276,253 | Are the indices in an OpenMP loop processed in ascending order? | Consider the following OpenMP for loop:
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < n; ++i)
{
//do something with i
}
Is it guaranteed that each OpenMP thread sees its i values in ascending order?
| The order in which threads run is not guaranteed; the order in which a thread processes its own chunk is guaranteed.
|
6,276,332 | 6,276,710 | Create A COM object inside another COM object | I have the following interface. The interface returns ISystemCmds interface as part of GetSystemCommandInterface method. We are using ATL for creating the COM.
interface IDevice : IDispatch{
[id(1), helpstring("method Connect")] HRESULT Connect([in] VARIANT varPortNo);
[id(2), helpstring("method GetSystemCom... | Use the ATL wizard to create the implementation of ISystemCmds. Then create the object through normal CoCreateInstance, or use the CComObject<> template (see method CreateInstance) if you need to initialize the object in a way that ISystemCmds does not support. Be aware that CComObject<>::CreateInstance() does not AddR... |
6,276,576 | 6,276,652 | How to Convert integer to char array | int x = 1231212;
memcpy(pDVal, &x, 4);
int iDSize = sizeof(double);
int i = 0;
for (; i<iDSize; i++)
{
char c;
memcpy(&c, &(pDVal[i]), 1);
printf("%d|\n", c);
printf("%x|\n", c);
}
I used above code segment to print the hex value of each byte of a Integer. But that is not working properly. What is iss... | Try something like this:
void Int32ToUInt8Arr( int32 val, uint8 *pBytes )
{
pBytes[0] = (uint8)val;
pBytes[1] = (uint8)(val >> 8);
pBytes[2] = (uint8)(val >> 16);
pBytes[3] = (uint8)(val >> 24);
}
or perhaps:
UInt32 arg = 18;
array<Byte>^byteArray = BitConverter::GetBytes( arg);
// {0x12, 0x00, 0x00, 0x00 }
b... |
6,276,618 | 6,278,037 | Autotools: Switching part of project to a different compiler | I'm working on a big, old, project that is using autotools. I would like to switch one part of the project to C++ (from C).
How can I switch the compiler used for a part of the project? I don't like the idea of completely splitting the project into two parts. The directory has only Makefile.am and I suppose I should re... | You must define output variable CXX in configure.ac (the simplest way is by using AC_PROG_CXX macro), then all files with appropriate suffixes (.cc, .cpp) will be compiled by C++ compiler.
|
6,276,893 | 6,276,921 | Templates befriending each other | I have a ResourcePtr<T> class template and a ResouceManager<T> template. I want the two to befriend one another. If I do the following I get a compilation error; how can I fix this?
template<class T>
class ResourcePtr
{
friend class ResourceManager<T>;
};
template<class T>
class ResourceManager
{
friend class ... | As usual for mutual things: declare one before the definition of the other.
template<class T>
class ResourceManager;
template<class T>
class ResourcePtr
{
friend class ResourceManager<T>;
};
template<class T>
class ResourceManager
{
friend class ResourcePtr<T>;
};
|
6,276,958 | 6,278,633 | Graph edit framework | I was looking at MeVisLab and I wondered if anyone knows a good framework for making a user interface similar to the one they use. I like the designing flow with boxes and arrows thing.
What I would really like is to able to integrate with C++ using Qt, and perhaps export the graph to xml of something like that.
Ther... | Qt's Graphics View is a "framework" which does a good bit of the handling for the kind of scenario you describe. It doesn't take much code to get off the ground and within striking range of what you're looking for:
http://doc.qt.nokia.com/latest/graphicsview-diagramscene.html
http://doc.qt.nokia.com/latest/graphicsvie... |
6,276,968 | 6,306,648 | How to catch a CListCtrl column width change event? | How can I catch CListCtrl column width change event in MFC? I believe there should be an OnNotify() event but I am note sure about various values and the parameters to use for message map and the event itself.
Please note that a CListCtrl column width can change by dragging the column divider or by double clicking on t... | I think the key is to understand that there is a difference in the listcontrol itself, and the header control. By using the GetHeaderCtrl() member function of the listcontrol you can get to the header control. For working with the header control, see this article: http://www.codeproject.com/KB/list/headerctrl.aspx?disp... |
6,277,070 | 6,277,398 | How in c++ builder export registry to *.reg file? | I'm use reg->SaveKey("Software", "D:\1.reg"). But getting empty file, without data.
void __fastcall TForm1::Button2Click(TObject *Sender)
{
TRegistry *reg=new TRegistry(KEY_READ);
reg->RootKey=HKEY_LOCAL_MACHINE;
reg->OpenKey("Software",0);;
reg->SaveKey("Software","D:\\1.reg");
delete re... | SaveKey is a loose wrapper around RegSaveKey(), the documentation of which states:
The calling process must have the SE_BACKUP_NAME privilege enabled. For more information, see Running with Special Privileges.
User tokens do not normally have the SE_BACKUP_NAME privilege enabled. In order to meet this requirement you... |
6,277,159 | 6,301,238 | Bad Ptr when passing string reference as argument | I've been trying to understand why the following code gives me a bad pointer on the string 'filename':
Mat imread(const string& filename, int flags) {
// some code returning a Mat object
}
int main() {
string s = "test.jpg";
imread(s, 0);
}
I've debugged step-by-step and all I've got was that before ent... | I solved this issue by separating in different files all OpenCV code from the code that involved the CUDA extension. Therefore, imread was now being called from a .cpp file and everything that involved CUDA was on different .cu and .h files.
Correct me if I'm wrong, but I don't think this is supposed to be that way, ma... |
6,277,468 | 6,278,098 | Create a Setup and Deployment Project in windows without .net support | I have got a vc++ project and for that I have created .exe and .lib.
Now, I am trying to create a set up project for this.
I am following the instructions given on this link:
http://msdn.microsoft.com/en-us/library/ms235317(v=vs.90).aspx
under the heading: Procedures for deploying Visual C++ library DLLs as private ass... | A .NET Framework installer is launched during install only if you added it as a prerequisite. You can change prerequisites by clicking the "Prerequisites..." button in your setup project Properties pane.
For your project you should make sure that no .NET Framework prerequisite is checked.
|
6,277,517 | 6,277,658 | Qt and X11 fullscreen application , which blocks Window Manager simultaneously | i think i need to use a XEvent with QMainWindow together to make my application unable to close even by Window Manager , could any one provide an example ?
It's like a fullscreen video game , which blocks all keyboards , mouse buttons.
P.S: QWidget::grabKeyboard() && QWidget::grabMouse() doesn't work when i try to swit... | To completely block all inputs from other apps, you need to use XGrabServer and not XGrabKeyboard/XGrabPointer combination. Dunno whether Qt has an API for that but you can always call the Xlib function directly.
I however recommend against it. If the application is for some reason doesn't release the grab, you're stuc... |
6,277,646 | 6,277,674 | In C++ check if std::vector<string> contains a certain value | Is there any built in function which tells me that my vector contains a certain element or not
e.g.
std::vector<string> v;
v.push_back("abc");
v.push_back("xyz");
if (v.contains("abc")) // I am looking for one such feature, is there any
// such function or i need to loop through whole vector?
| You can use std::find as follows:
if (std::find(v.begin(), v.end(), "abc") != v.end())
{
// Element in vector.
}
To be able to use std::find: include <algorithm>.
|
6,277,649 | 6,277,838 | Implicit type unknown when passing pointer to function | I'm looking at some code at the moment which has been ported and is failing to compile. The code has been written in a rather 'C' like way and is passing function pointers in order to set particular mutators on an object. The object being populated is declared as follows:
class Person
{
std::string n_;
int a_;
... | First change the declaration:
typedef void (Person::*FnSetStr)(const std::string& s);
typedef void (Person::*FnSetInt)(const int& i);
Then change the call:
setMem("Name", person, &Person::name ); // (1)
setMem("Age", person, &Person::age ); // (2)
Builds clean at warning level 4 in VS 2010.
|
6,277,678 | 6,277,726 | stream output and implicit void* cast operator function invocation | a code like
cin>> grade;
where grade is a standard data type returns a reference to cin(istream object) which enables cascaded inputs....
but i read that if
cin >>grade;
is used as a condition say in a while statement...the stream's void* cast operator function is called implicitly...and it converts reference to ... |
1.what is the void * cast operator function and how does it work here
It looks something like this:
operator void* () const {
return fail() ? 0 : this;
}
The question is: why isn’t an operator bool used here? The answer is: because that allows invalid conversions which may hide bugs. The above is an example of t... |
6,278,302 | 6,278,964 | Qt and vsync/tearing | Does anyone know of an easy way to enforce vsync in Qt, when displaying an image onto a QLabel? Basically, I'm rendering a stream of images from a processed video clip (hence not using Phonon multimedia), and the framerate is very high. Unfortunately, this is giving a lot of tearing.
Any help much appreciated.
| Try using QtOpenGL. You can implement your widget over QGLWidget. It will render using opengl, that will sinc to vblank if you set this option in your os.
|
6,278,321 | 6,304,446 | Modifying another user registry | Here is the problem.
I need to run a Windows Service which is being configured through registry.
Is there any way to modify another user HKCU without enumeration all the users on the machine?
| I have found good way to do it through WMI interface.
I've opened connectioin to WMI (see there: http://msdn.microsoft.com/en-us/library/aa390423%28v=vs.85%29.aspx).
Next, I've enumerated all the items in Win32_Account database.
Each item in win32_Account have Domain, Name and SID fields.
That's the way to get correct ... |
6,278,327 | 6,278,597 | Draw loading circle on windows form | How can I draw a loading circle(animated) on windows forms? Is it possible to make it big and transparent, so that underlying text on form is still visible.
Displaying a gif is not a kind of solution i'm looking for.
Thx.
| Yes - you can do this using Graphics.DrawEllipse (for one or multiple circles, depending on the exact UI effect you're trying to achieve), using a pen with a non-opaque alpha value.
|
6,278,335 | 6,278,741 | Running Dll Contains MFC Class in other computer C++ | I've made a normal dll (not a MFC dll) and I use there CImage Class (MFC) and it works great.
First of all I dont have lot of experience in dlls, so I wonder how my dll works if i didn't used the "MFC Dll" option, and whats the difference between the two options.
My second question is if the fact that I am using the CI... | MFC DLL is more a DLL wizard that sets some boilerplate code for you if you are going to follow the MFC framework usage guidelines. It is not absolutely necessary to be able to use MFC. You may still create your own code and use it as you wish.
As it comes to MFC cross-machine portability, it is transparent when you li... |
6,278,580 | 6,278,655 | STL Container that preserves order of insertion but allows no duplicates |
Possible Duplicate:
A std::map that keep track of the order of insertion?
I am looking for an STL container that preserves order of insertion ( no sorting ) but does not allow duplicates. Is there one? if not any tricks I can use to customize one?
| There is no such a container at the moment, but you can create your own one in a cheap way by holding a std::vector and a std::set in a class together.
|
6,278,677 | 6,278,764 | Which toolkit should I use to make an easily editable and modern looking GUI for existing c++ code? | I am starting a new small project where the graphic interface and a bit of juggling data too and fro is missing, but the complex and time-critial parts of the code exist and are written in c/c++. Previously I've used the win32 api, MFC to do the graphics, but I want something a bit more modern looking and newer and som... | You could try QT or wxWidgets that are both good C++ GUI toolkits.
If you don't have much entry point in the c++ code yuo could wrap them in few C# classes and use WPF or windows form (.NET 4 or 2). Anyway this requires to "mix managed and unmanaged code".
|
6,278,761 | 6,279,046 | using c++ in xcode / objective c | So I'm trying to use C++ inside my ios project.
After I make a new project (all default settings, fresh install of xcode), I create a Question.h and a Question.mm file, like this:
Question.h
#include <iostream>
#include <string>
using std::string;
class Question {
public:
string text;
};
Question.mm
#include "Q... | The most likely cause of this is that you're including Question.h in a non-C++ file, for instance perhaps your AppDelegate is a .m file and you're trying to include Question.h there.
There are two solutions. First, you can make everything Objective-C++ (renaming all .m files to .mm). Historically I've found that to be ... |
6,279,089 | 6,279,291 | Running a console command which is stored in `std::wstring` | I have a console command, something like:
std::wstring ConsoleCommand;
ConsoleCommand = L"c:\\somepath\\anotherpath\\program.exe -opt1 /opt2 --opt3";
I want to execute this command.
How do I do it?
(It may be a Win32 API function, or a standard C/C++ library.)
| Try ShellExecute(). You probably want the open verb. You could also use CreateProcess().
|
6,279,287 | 6,279,874 | A point from n3290 :Argument-dependent name lookup | A point from n3290 Draft ISO Standard:Section : 3.4.2 ,Point 2nd
For each argument type T in the function call, there is a set of zero or
more associated namespaces and aset of zero or more associated classes to
be considered. The sets of namespaces and classes is determined entirely
by the types of the function argum... | It explains how you look for a function based on its parameters.
1) Fundamental types are not members of a namespace or class, so they don't contribute.
2b) non-type template parameters are values and don't contribute.
4) If the type is T* or T[], treat that like it was just T.
5) If the parameter is another function, ... |
6,279,356 | 6,281,247 | CUTE unit test not recognizing thrown exception | Using the CUTE unit test framework I have the following classes:
const std::size_t COARSE_MODEL_COUNT = 4;
class ModelType
{
public:
explicit ModelType(std::size_t aModelNumber) : theModelNumber(aModelNumber){}
virtual operator size_t(){ return theModelNumber; }
protected:
std::size_t theMo... | (Ahem) I think the ASSERT_THROWS macro is doing something you're not aware of. Instead of
CoarseModelType(COARSE_MODEL_COUNT)
try
CoarseModelType dummy(COARSE_MODEL_COUNT)
and see what happens. The first is an odd way to invoke the constructor, and a clumsy macro might turn it into something that the compiler inter... |
6,279,410 | 6,279,443 | How to statically check that two ratios are equal? | I have 4 int constants :
const int a1 = 1024;
const int a2 = 768;
const int b1 = 640;
const int b2 = 480;
and I want to statically check that they have the same ratio. To statically check, I am using BOOST_STATIC_ASSERT, but it doesn't support expressions.
I tried this :
BOOST_STATIC_ASSERT( 1e-5 > std::abs( (double)a... | BOOST_STATIC_ASSERT(a1 * b2 == a2 * b1);
|
6,279,779 | 6,279,944 | Aggregate initialization with private copy/move constructors | I came across this while testing some stuff for another question on initializing aggregates. I'm using GCC 4.6.
When I initialize an aggregate with a list, all the members are constructed in place, without copying or moving. To wit:
int main()
{
std::array<std::array<Goo,2>,2>
a { std::array<Goo,2>{Goo{ 1, 2}, Go... | Not calling the copy or move constructor is an optimization specifically allowed by the standard (but not required).
To be consistent across compilers, an implementation must check that the constructor could have been called, if it didn't care to optimize it out.
|
6,279,796 | 6,280,127 | Create C# structure for CvMat.data union or any way to access it in C# | I need to access 'data' property EmguCV MCvMat structure. But that property is a pointer(IntPtr). I found that structure for this property(data) is an union. It's like this:
union Data
{
char* ptr; // Data pointer for an unsigned char matrix
short* s; // Data pointer for a short matrix
int* i; ... | I've published a Visual Studio 2010 solution on SkyDrive. It dmonstrates un-marshalling such a structure.
I'll try the MarshalAs attribute when I have more time. Usually, in such situations, I would implement an adapter layer in C++ to make it easier to transfer data between unmanaged and managed code.
|
6,280,402 | 6,280,472 | Enforce compiler settings via macros | I am developing a framework which requires very strict compiler settings. Every time a new project is started and uses the framework, it must adhere to the settings (for example, warning level 4). Is there any way I can do that via macros and pragma statements? This will also allow me to do something like:
#ifndef NOT_... | You can get the list of predefined macros from MSDN: http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx
These macros also allow checking for compiler directives.
Example:
#define USING_STRICT_SETTINGS defined(_MT) && defined(_OPENMP)
|
6,280,974 | 6,281,071 | Why does std::map behave strangely when passed by value into a lambda? | I've been using c++ 0x for a while now and have been very much enjoying the new lamba function facilities. I've become accustomed to specifying [=] in my lambda declarations to indicate that I want to pass externally scoped variables into my lambda by value.
However, today I came accross a very strange lambda issue. ... | FYI [=] captures by value, IIRC [&] captures by reference.
http://software.intel.com/sites/products/documentation/hpc/composerxe/en-us/cpp/lin/cref_cls/common/cppref_lambda_lambdacapt.htm#cppref_lambda_lambdacapt
See: C++0x lambda capture by value always const?
|
6,281,083 | 6,281,888 | c++ order of defs in the class, surprise | Stroustrup states in C++ Language book that order of definitions in the class does not matter.
Indeed:
class C1 {
int foo() { return bar(); } // where is bar() ?
int bar() { return m_count; } // oh, here is bar(). but where is m_count ?
int m_count; // here is m_count. Better... | An identifier that denotes a type must be declared prior to use. This has to do with the complicated structure of C++ grammar. The compiler simply cannot parse certain code if it does not know beforehand which identifiers are types.
|
6,281,176 | 6,282,323 | How to deal with failure to destroy mutex in destructor | Say you have the following destructor in a mutex class wrapping up pthread mutex calls:
~mutex()
{
pthread_mutex_destroy(&m_mutex);
}
If this fails (returns non-zero) we can't throw an exception obviously. How best do we deal with this?
| Write an error message and call abort(). Hard, visible failure is often preferable to continuing blithely on when the impossible appears to have happened.
|
6,281,191 | 6,281,627 | Function to parse string with tokens | I know how to program in C# and VB but not have idea about how to use C++ and have to program a little exe to a barcode scanner that use C++ :(
In this moment I try to parse a scanned barcode that have multiple data sepparated with a "/", I find that exist a strtok function, tested it "manually" and worked ok but I not... | Here is a C++ solution that doesn't use boost.
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string barcode = "710015733801Z/1/35";
std::stringstream ss(barcode);
std::string elem;
while(std::getline(ss, elem, '/'))
{
//do something else meaningful with elem
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.