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 |
|---|---|---|---|---|
4,086,580 | 4,095,126 | My C++ application cannot connect to Informix DB server | I've an application (can't provide code, as it's very long), that uses unixODBC. Also, I have installed isql. Everything seems to be configured correctly - drivers, servers and so on, as using isql, I connect to the Informix DB with no problems. But my application cannot connect, even when I'm using the same settings. ... | @Jonathan Leffler - Yep, I have everything installed properly, the problem was definitely somewhere else. I'm answering here, as I found the solution (actually, a colleague of mine did). It was very, very stupid thing .. He just added /usr/local/lib in /etc/ld.so.conf and everything started normal.....
Anyway, really t... |
4,086,701 | 4,086,789 | Reading a partial file stream into a string using iterators | This is what I have tried so far but with no success:
std::string ReadPartial( std::ifstream& _file, int _size )
{
std::istreambuf_iterator<char> first( _file );
std::istreambuf_iterator<char> last( _file );
std::advance( last, _size );
return std::string( first, last );
}
I know how to read the whole... | Is there some particular reason you want to use iterators? You could just read the bytes in one go:
std::string s(_size, '\0');
_file.read(&s[0], _size);
If you really want to read using iterators, you could do this:
std::string ReadPartial( std::ifstream& _file, int _size )
{
std::istreambuf_iterator<char> first(... |
4,086,800 | 4,086,826 | Move constructor on derived object | When you have a derived object with a move constructor, and the base object also has move semantics, what is the proper way to call the base object move constructor from the derived object move constructor?
I tried the most obvious thing first:
Derived(Derived&& rval) : Base(rval)
{ }
However, this seems to end up c... | rval is not a Rvalue. It is an Lvalue inside the body of the move constructor. That's why we have to explicitly invoke std::move.
Refer this. The important note is
Note above that the argument x is
treated as an lvalue internal to the
move functions, even though it is
declared as an rvalue reference
parameter.... |
4,086,817 | 4,086,838 | L prefix for strings in C++ | I have a static library. This library have the following function defined
int WriteData(LPTSTR s)
The sample to call the function is
LPTSTR s = (LPTSTR) L"Test Data";
int n = WriteData(s);
WriteData return 0 on success and -1 on failure.
I am writing a dynamic DLL to export this function.
int TestFun(LPTSTR lpDat... | The L prefix makes the string a wchar_t string.
You can use the Windows API function MultiByteToWideChar to convert an ANSI string to a wchar_t string.
|
4,086,828 | 4,087,942 | Should we delete a pointer that is not new/malloc by us? | class ClassA
{
public:
ClassA(ClassB *p) b(p){}
~ClassA(){delete b;}
ClassB *b;
};
Is this kind of design a good one?
| In general this is a bad idea. Quite often you just don't know how the object of ClassB was created. It could be a pointer to element of an array created with the new[] operator, or it could be handed to you from separate dll which uses custom memory allocator. In those cases using operator delete to delete this pointe... |
4,086,868 | 4,086,996 | How to enforce implementor to do something | Suppose I have the following classes:
class X;
class Y;
class Collection
{
public:
virtual void AddItemX(X*) = 0;
virtual void AddItemY(Y*) = 0;
//So on...
};
class Collector
{
public:
virtual void Fill(Collection&) = 0;
};
Is there any way to ensure that an implementation of Collector ... | One method, given a known number of AddItemX() calls is to move those AddItem() functions to protected and have the Collection class keep track of the additions and the number, e.g:
(I actually don't like this solution, lol, but given your design it would suffice:)
class X;
class Y;
class Collection
{
private:
int... |
4,086,901 | 4,087,167 | c++: address to string constant | Can I get the address of an object as a string constant in g++? Example:
struct s { } x;
If &x == 1234, then I need "1234" in my code.
EDIT:
By string constant I meant that I need that constant string at compile- or link-time. I need to embed it in inline assembly code like this:
template < typename U >
struct T {
s... | template<class U>
struct T {
static int x;
void f () {
asm (".word %0" : "m" (&x));
}
};
This works for me in g++.
|
4,087,263 | 4,087,416 | Serialize and send objects by TCP using boost | I am trying to send C++ ojbects through a tcp connection:
My objects are all serializable, using boost serialization.
The TCP server/client is made with boost asio.
Basically I would like to send message like that would contain the message type (the type of the object being sent) and the data itself (the serialized ... | Here you can find a good example on how to use boost::serialization together with boost::asio.
Something like this is the core of what you need:
std::ostringstream archive_stream;
boost::archive::text_oarchive archive(archive_stream);
archive << YOUR_DATA;
outbound_data_ = archive_stream.str();
boost::asio::async_write... |
4,087,403 | 4,087,604 | Deep copy of std::stack< boost::shared_ptr<T> > | I would like to implement a copy of std::stack< boost::shared_ptr<T> >. Is there any way to do it without 3 copies? Here is the code:
template<typename T>
void copyStackContent(std::stack< boost::shared_ptr<T> > & dst,
std::stack< boost::shared_ptr<T> > const & src){
//// Copy stack to tempor... | If you want to maintain the ordering, you're kind of stuck since stack doesn't provide any iterators. If you don't want to use a deque, you can at least make the code clearer (and more efficient under certain circumstances) by passing the source stack by value:
template<typename T>
void copyStackContent(std::stack< boo... |
4,087,435 | 4,087,949 | Is there design patterns I can use to implement an RPC (client-server) in C++ | I'm working on a personal project which is an RPC (client-server) in C++. The RPC will communicate over TCP/IP or HTTP. The spec of the RPC is here :
http://groups.google.com/group/json-rpc/web/json-rpc-2-0
I'm wondering if there is an existing design pattern (or a combination of pattern) that could help me to produc... | You are probably going to need a Proxy on the client to represent and make callable locally any server-side methods that you will be calling.
Under the covers, Abstract Factory could be useful to encapsulate provision of a concrete network connection that is selected using a configured or requested protocol (TCP, HTTP)... |
4,087,650 | 4,087,853 | C++ MFC How to Draw Alpha transparent Rectangle | in a C++ MFC application. using the dc of ( CPaintDC dc(this); )
How do i draw a rectangle ( LPRECT ) with an alpha transparency that i can adjust.?
Following is an example c# code which i need to convert into C++
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Col... | You need to look into GDI+. Its a bit of a faff but you can create a "Graphics" object as follows:
Gdiplus::Graphics g( dc.GetSafeHdc() );
Gdiplus::Color color( 192, 255, 0, 0 );
Gdiplus::Rect rectangle( 100, 100, 400, 400 );
Gdiplus::SolidBrush solidBrush( color );
g.FillRectangle( &solidBrush, rectangle );
Don't f... |
4,088,193 | 4,091,388 | unable to call c++ functions in qt | I have a shared library of the C++ application and I am able to call it using the test app. I want to write a Qt UI for this. I am not able to call the C++ functions directly. Only if I give name mangled function name it works.
Also if I create an object of the C++ class and call a function of the class I am getting "... | You must include the path to the headers files. To do this in Qt Creator, modify your .pro file to include the following line:
INCLUDEPATH += path/to/header/files
you will notice that you MUST use the slash above... If you try using '\', it will not work.
|
4,088,387 | 4,088,438 | how to store pointers in map | I am working on one of the project which requires
class MyObj;
map<string, MyObj*> myMap;
Here logic is here to map file name to MyObj class.
If I try to insert following
string strFilename = "MyFile";
MyObj* pObj = new MyObj();
myMap.insert(strFileName, pObj); // This line throwing following error.
no matching... | I've typedef'd this stuff to make it more readable...
typedef std::map<std::string, MyObj*> MyMap;
typedef std::pair<std::string, MyObj*> MyPair;
MyMap myMap;
string strFilename = "MyFile";
MyObj* pObj = new MyObj();
myMap.insert(MyPair(strFilename, pObj));
|
4,088,411 | 4,146,627 | implementing a copy constructor | I have the following class definition and it needs a copy constructor so deep copies are made to copy the raw pointers. Can anybody advice on how to best do this?
Using xerces-c++ for XML
class XMLDocument
{
private:
typedef std::vector<XML::XMLNode> v_nodes;
public:
XMLDocument::XMLDocument();
XMLDocument::... | This page might certainly help:
http://icu-project.org/docs/papers/cpp_report/the_anatomy_of_the_assignment_operator.html
Note their is a difference between writing a copy-constructor and an assignment operator but this point is also discussed in the paper.
|
4,088,429 | 4,088,459 | Invoking command line programs by double clicking on files in windows | I've written a command line program using c++ in the netbeans IDE, then compiled it using mingw. The program takes as its only argument the name of a file (with the fairly unique extension .mmf) , then it plays a movie based on the file.
What I would like is to be able to set the default application for the .mmf exten... | When you open a file in windows like this, does it just call your application with the filename as an argument?
Yes.
|
4,088,455 | 4,088,600 | Why such OpenAL code gives such Erros in Visual studio 2008? | So in general my code is super simple - I am triing to write Microphone Echo programm and this is its start (as it seems to me - I am wary new to OpenAL)
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <al.h>
#includ... | You need to link the OpenAL library to your application.
Go into project properties->Linker->Input and add openal32.lib to the list.
|
4,088,519 | 4,088,658 | Migrating from C# to native windows C++ | I want to develop native c++ windows application using windows API.
but i find it being difficult because i am unable to render the window and drag and drop components, change the location etc..
How can i view, drag and drop components like i can do in C# ?
May be there is no way to do. if so, what is the fastest proc... | If you like so much the drag and drop of components (and of course for good reason) why would you need to develop it using C++? You can use PInvoke if you need to call some C++ functions from C# code that are not in the .net framework.
But if you really insist, maybe you could try QT.
|
4,088,892 | 4,088,933 | Impact of hundreds of idle threads | I am considering the use of potentially hundreds of threads to implement tasks that manage devices over a network.
This is a C++ application running on a powerpc processor with a linux kernel.
After an initial phase when each task does synchronization to copy data from the device into the task, the task becomes idle, ... | Each thread has overhead - most importantly each one has its own stack and TLS. Performance is not that much of a problem since they will not get any time slices unless they actually do anything. You may still want to consider using thread pools.
|
4,088,999 | 4,089,128 | What the heque is going on with the memory overhead of std::deque? | I am working on an external sorting algorithm that uses std::queue and must carefully constrain its memory usage. I have noticed that during the merge phase (which uses several std::queues of fixed length), my memory usage increases to about 2.5X what I expected. Since std::queue by default uses std::deque as its und... | Look at the code for _DEQUESIZ (number of elements per block):
#define _DEQUESIZ (sizeof (_Ty) <= 1 ? 16 \
: sizeof (_Ty) <= 2 ? 8 \
: sizeof (_Ty) <= 4 ? 4 \
: sizeof (_Ty) <= 8 ? 2 : 1) /* elements per block (a power of 2) */
It gets smaller if the element is larger. Only for elements larger than 8 ... |
4,089,073 | 4,089,340 | C++ Finding out what resolutions are supported by the graphics card | I am writing a small program to let me switch my resolution back and forth because my projector cannot handle the same resolution as my screen. I already know how to set the screen resolution using the windows API. As well as read the current resolution using the windows API or the QT4 toolkit. My problem is I want a m... | The following should probably work for you in the general case
DEVMODE dm = { 0 };
dm.dmSize = sizeof(dm);
for( int iModeNum = 0; EnumDisplaySettings( NULL, iModeNum, &dm ) != 0; iModeNum++ ) {
cout << "Mode #" << iModeNum << " = " << dm.dmPelsWidth << "x" << dm.dmPelsHeight << endl;
}
This should print out all th... |
4,089,196 | 4,089,883 | NetUIHWND and DirectUIHWND | Using Spy++ tool, it seems that some Microsoft apps use NetUIHWND and DirectUIHWND window classes; e.g.: Word 2010's ribbon seems to be a NetUIHWND, instead Windows Live Messenger window seems to be a DirectUIHWND.
These window classes seem to host kind of cool graphics (with shadows, gradients, etc.); is it possible t... | Yes, it has been around for a while already. But it gets especially a lots of usage in Windows7. Unfortunately, they keep this one to themselves, it is undocumented. You can try to reverse-engineer it, use a ListView as a guide to what it might do. But your code will almost certainly break in the next version of W... |
4,089,200 | 4,089,338 | Using realloc in c++ | std::realloc is dangerous in c++ if the malloc'd memory contains non-pod types. It seems the only problem is that std::realloc wont call the type destructors if it cannot grow the memory in situ.
A trivial work around would be a try_realloc function. Instead of malloc'ing new memory if it cannot be grown in situ, it ... | vector generally grows in large increments. You can't do that repeatedly without relocating, unless you carefully arrange things so that there's a large extent of free addresses just above the internal buffer of the vector (which in effect requires assigning whole pages, because obviously you can't have other allocatio... |
4,089,320 | 4,089,427 | Capturing a X11 screenshot with ImageMagick++ | How can I easily take a screenshot of an X11 screen in C++ with ImageMagick++, similar to the "import" command?
| Use the source, Luke. If you can't find it in ImageMagick++, fall back to its dependency. The code you're looking for is in ImageMagick/wand/import.c:
% ImportImageCommand() reads an image from any visible window on an X server
% and outputs it as an image file. You can capture a single window, the
% entire screen,... |
4,089,641 | 4,089,778 | Programatically determine if native .exe is 32-bit or 64-bit | I need to know whether a given .exe is 32-bit or a 64-bit, before I launch it. IsWow64Process is no use here, since there is no process yet. Is there some other API that will give me this information?
| If you really only want to do this for EXEs and not DLLs, just use GetBinaryType.
Determines whether a file is an
executable (.exe) file, and if so,
which subsystem runs the executable
file.
|
4,089,726 | 4,089,764 | How do I cast a parent class as the child class | It's been a while since I have had to write C++ code and I'm feeling kind of stupid. I've written code that is similar to, but is not exactly, the code below:
class Parent
{
...
};
class Child : public Parent
{
...
};
class Factory
{
static Parent GetThing() { Child c; return c; }
};
int main()
{
Par... | A Parent object returned by value cannot possibly contain any Child information. You have to work with pointers, preferably smart pointers, so you don't have to clean up after yourself:
#include <memory>
class Factory
{
// ...
public:
static std::unique_ptr<Parent> GetThing()
{
return std::make_u... |
4,089,975 | 4,090,100 | Efficient way to calculate average value over disjoint subranges of STL map | I'm converting an algorithm from C# to C++. A small part of the algorithm is to calculate average values for certain areas in a dictionary.
The data in the dictionary is stored in the following way:
Index Value
1 10
3 28
290 78
1110 90
I need to calculate the average value of all values ... | Key-value pairs in std::map are sorted by keys - it's easy to sum the values pointed by keys smaller or larger than some value even with a for loop (if you do not want to use or learn to use STL algorithms). For keys lower than some value:
std::map<int, int> map;
map[...] = ...;
int count = 0, sum = 0;
for (std::map<i... |
4,090,056 | 5,622,873 | How can I set environment variables PATH and LD_LIBRARY_PATH on Unix TeamCity build agent? | I use TeamCity to build c++ on Unix (Solaris). TeamCity invokes make, and within my makefile I need to call svn. For this I need to modify PATH and LD_LIBRARY_PATH.
I could set these within the makefile but the locations vary from server to server. does anyone know a way to set these for each TeamCity build agent, e... | You could create a wrapper script that exports these variables before executing the TeamCity command.
|
4,090,105 | 4,090,171 | A function declared to return int returns nothing. Is this Undefined Behavior? | This is a valid function in C++:
int f()
{
if(false)
{
return 42;
}
}
The following definition causes UB:
int x = f(); // return value used
The question:
Does the following expression statement cause UB?
f();
Quote from the standard would be very much welcome.
| C++03 §6.6.3/2:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
So this is an UB in a function itself.
BTW gcc gives you a nice warning pointing to this UB:
In function 'int f()':
Line 7: warning: control reaches end of non-voi... |
4,090,277 | 4,090,452 | Iterating, inserting and removing? | Dream output:
/* DREAM OUTPUT:
INT: 1
TESTINT: 1
TESTINT: 2
TESTINT: 23
TESTINT: 24
TESTINT: 25
TESTINT: 3
TESTINT: 4
TESTINT: 5
TESTINT: 6
INT: 23
INT: 24
INT: 25
INT: 3
INT: 4
INT: 5
INT: 6
Problem
ERROR 1: Not erasing the '2' causes a bizzare effect.
ERROR 2: Erasing the '2' causes memory corrup... | You need to understand the differences between the stl collections.
A Vector is a continuous (usually) block of memory. Whem you insert into the middle, it tries to be helpful by re-allocating enough memory for the existing data plus the new, then copying it all to the right places and letting you continue as if nothin... |
4,090,289 | 4,090,323 | C++/SDL problem of double inclusion | I'm getting this error from compilator:
1>Linking...
1>main.obj : error LNK2005: "int g_win_flags" (?g_win_flags@@3HA) already defined in init.obj
1>main.obj : error LNK2005: "struct SDL_Surface * g_screen" (?g_screen@@3PAUSDL_Surface@@A) already defined in init.obj
1>MSVCRTD.lib(cinitexe.obj) : warning LNK4098: defaul... | You define and initialize the variables in the header.
You should just declare them in the header (dec.h) without any initializers:
extern int g_win_flags;
extern SDL_Surface *g_screen;
Then define them once in one file - presumably dec.cpp - with the initializations.
As it was, you were defining them in every source ... |
4,090,307 | 4,097,516 | Problem spawning application | Gosh, this is so weird, I don't know what to say. The short version is that I have a simulator app which I spawn from my application when the user asks me to. It recently stopped working, though I can run the simulator fine from the command line or Start menu. This could be due to moving to VS2010 or Windows 7 or so... | A foolish tool I was using did a setenv on PATH, prepending a directory it wanted for dynamically loading some dlls, but which messed up my application later. I ended up using GetEnvironmentStrings as shown in the last example here, erasing the first entry in the PATH env var, and sending the new (original) environmen... |
4,090,472 | 4,090,530 | check existing shared_ptr when using enable_shared_from_this in c++? | Aside from catching the bad_weak_ptr error thrown when trying to call shared_from_this() on a pointer that is a raw pointer, is there a way of testing whether or not the object is being reference counted?
I have functions that deal with the raw pointer and shared pointer and I want to be sure that the error is obvious ... | A call to std::enable_shared_from_this<T>::shared_from_this() will never fail for an existing valid object, or pointer to it. EDIT: ... if there is at least one instance of std::shared_ptr<YourClass> where YourClass is std::enable_shared_from_this<YourClass>. This is a stricter statement than the first one and I apolog... |
4,090,549 | 4,090,692 | Scoped case statement in C++: purpose of cross-scope case labels? | I have a bug in my current code that I have been banging my head against for a couple days. I'll post the summary version of the code below (not my actual code, but it still compiles).
#include <iostream>
using namespace std;
int main()
{
int x = 7;
switch(x)
{
case 1:
{
case 2:
cout << "hi... | Duff's Device is hardly the "purpose" of cross-scope case labels as already suggested, it is merely an exploitation of it.
The truth is probably that it serves no intentionally designed purpose, but is merely an artefact of the most simple possible implementation that works. The design is such that the switch-case c... |
4,090,648 | 4,091,096 | Qt on Linux - version conflict? | Trying to move a Qt 4.6.3 project from Windows to Debian Linux (Etch). I've installed Qt by downloading the latest version, then running configure, then make install as root. Yet when I run qmake_qt4 on my project's pri file, here's what I get:
uic: File generated with too old version of Qt Designer
Running uic -v re... | By default, Qt installs to /usr/local/Trolltech/Qt-4.6.3 and doesn't add it's bin folder to your PATH variable. Also, it's just named qmake.
Either call /usr/local/Trolltech/Qt-4.6.3/bin/qmake using the complete path or add the /usr/local/Trolltech/Qt-4.6.3/bin/ path to your PATH variable and ensure that it is listed t... |
4,090,842 | 4,090,890 | list iterator + operator | // ((++currentEntry)--) is equivalent to (currentEntry + 1). Kind of.
menuEntries.insert((++currentEntry)--, newEntries.begin(), newEntries.end());
So I have the world's worst piece of code here. Is there a better way to do this?
When using '+ 1' I get this:
source/menu.cpp:146:37: error: invalid operands to binary ex... | Why not split into multiple lines:
iterator nextEntry = currentEntry;
menuEntries.insert( ++nextEntry, newEntries.begin(), newEntries.end());
where iterator is iterator type for the list. Personally, I would probably pull the ++nextEntry onto its own line for further clarity - but that is probably a subjective decisio... |
4,091,114 | 4,119,180 | OpenGL, applying texture from image to isosurface | I have a program in which I need to apply a 2-dimensional texture (simple image) to a surface generated using the marching-cubes algorithm. I have access to the geometry and can add texture coordinates with relative ease, but the best way to generate the coordinates is eluding me.
Each point in the volume represents a... | Due to the issues with texturing and some of the constraints I have, I've chosen to write a different algorithm to build the geometry and handle texturing directly in that as it produces surfaces. It's somewhat less smooth than the marching cubes, but allows me to apply the texcoords in a way that works for my project ... |
4,091,209 | 4,091,313 | A variable across the whole application | I have a C++ windows application which is composed of several DLLs.
I want to have some sort of a pool from which I'll get objects, but in a way that this pool
would be available in all the DLLs.
So I put it in a "Common" dll which everbody has access to and defined it in a header file like so:
static Pool globalPool;
... | You'll want a header file that looks something like this:
// Common.h
#pragma once
#ifdef COMMON_BUILD
// When building Common.dll, want to export the definition of Pool
#define COMMON_EXPORT __declspec(dllexport)
#else
// When using Common.dll, want to import the definition of Pool
#define COMMON_EXPORT __declspec(d... |
4,091,273 | 4,091,287 | Why isn't my or statement working, C++? | I'm trying to create a function that will replace 0's, 1's, or 2's with spaces in a string. I'm going about it by iterating through the string and comparing each individual character.
My function will work if I compare str_in[i] == '0', but if I add the or statement it returns nothing.
Snippet:
string omit_num( strin... | You need
if ( str_in[i] == '0' || str_in[i] =='1' || str_in[i] =='2')
|
4,091,380 | 4,091,557 | C++ -- STL Vector::const_iterator why not use < xx.end()? | // display vector elements using const_iterator
for ( constIterator = integers.begin();
constIterator != integers.end(); ++constIterator )
cout << *constIterator << ' ';
Can we use constIterator < integers.end()?
Thank you
| operator< is only defined for random access iterators. These are provided, for example, by std::vector and std::string, containers that, in essence, store their data in contiguous storage, where iterators are usually little more than wrapped pointers. Iterators provided by, e.g., std::list are only bidirectional iterat... |
4,091,488 | 4,091,889 | Am I Deleting my struct Properly? | This is a homework assignment. The Field container was the assignment from a week ago, and now I'm supposed to use the Field container to act as a dynamic array for a struct NumPair which holds two char * like so:
struct NumPair
{
char *pFirst, *pSecond;
int count;
NumPair( char *pfirst = "", char *psecond = "", i... | Your copy constructor (of Field<>) seems OK, but the operator= is problematic.
Not only does it leak memory (what happens to the original v_?), but after that, two instances of Field<> hold a pointer to the same block of memory, and the one that is destructed first will invalidate the others v_ - and you can't even tel... |
4,091,576 | 4,101,164 | Perform argument substitution on nested boost::bind without composition | Suppose I have a function which takes a nullary functor as an argument:
void enqueue( boost::function<void()> & functor );
I have another function which takes an int and does something internally:
void foo( int a);
I would like to nest, but not compose, these together so that I get a functor with the signature:
boost... | Interesting question...
What you basically want is a "bound call to bind". In the same manner than binding a call to foo(x, y) is written bind(&foo, x, y), binding a call to bind(&foo, x) should be like bind(&bind, &foo, x). However, taking the address of an overloaded function quickly gets ugly and, as boost::bind has... |
4,091,647 | 4,091,710 | Initialize a 2 Dimensional vector<int> in CPP | How to initialize a 2 dimensional vector<int> in C++?
For instance I have 4 arrays each of length 8 ints, like the below
int a1[] = {1,2,3,4,5,6,7,8};
int a2[] = {1,2,3,4,9,10,11,12};
int a3[] = {1,2,5,6,9,10,13,14};
int a4[] = {1,3,5,7,9,11,13,15};
and I have this
vector< vector <int> > aa (4);
aa[i] (a1,a1+8);
B... | aa[i].assign(a1,a1+8);
|
4,091,663 | 4,091,714 | 'nested' template `>>` issue is solved. What about `<::`? | C++0x addresses the issue of consecutive closing angle brackets in template-id's, like in
vector<vector<int>>. No space is required between > > any more. Does C++0x address the issue of <:: like in vector<::MyType> ? Is the space between < and :: still required?
Edit: I mean by the wording of the standard (draft). Man... | Yes, that space is still required currently. But US National Body comment 15 requested this to be removed, and it looks like the proposed resolution will be incorporated (since it's "ready").
|
4,091,826 | 4,091,895 | size guarantee for integral/arithmetic types in C and C++ | I know that the C++ standard explicitly guarantees the size of only char, signed char and unsigned char. Also it gives guarantees that, say, short is at least as big as char, int as big as short etc. But no explicit guarantees about absolute value of, say, sizeof(int). This was the info in my head and I lived happily w... | 18.2.2 guarantees that <climits> has the same contents as the C library header <limits.h>.
The ISO C90 standard is tricky to get hold of, which is a shame considering that C++ relies on it, but the section "Numerical limits" (numbered 2.2.4.2 in a random draft I tracked down on one occasion and have lying around) gives... |
4,091,868 | 4,092,016 | How do I safely format floats/doubles with C's sprintf()? | I'm porting one of my C++ libraries to a somewhat wonky compiler -- it doesn't support stringstreams, or C99 features like snprintf(). I need to format int, float, etc values as char*, and the only options available seem to be 1) use sprintf() 2) hand-roll formatting procedures.
Given this, how do I determine (at eithe... | Does the compiler support any of ecvt, fcvt or gcvt? They are a bit freakish, and hard to use, but they have their own buffer (ecvt, fcvt) and/or you may get lucky and find the system headers have, as in VC++, a definition of the maximum number of chars gcvt will produce. And you can take it from there.
Failing that, I... |
4,092,036 | 4,092,097 | Creating a cross-process function pointer | I have a Visual Studio 2008 C++ project for Windows Mobile 6 with two processes. Both of which I would like to have access to the same function which is contained in process1.
That function is Buzz:
struct TEST_STRUCT
{
int bar;
WCHAR foo[ 20 ];
};
typedef int( *pfn_Buzz )( TEST_STRUCT* );
int Buzz( TEST_STR... | If you want both processes to use the same function, put the function into a DLL and link that DLL to both processes. Each process has its own address space, so an address in one process may not work at all in another process, and even if it "works" it'll be pointing to something completely different.
Although you're t... |
4,092,270 | 4,092,334 | c++ private constructors | If I don't want to allow anyone to create an instance of my class except for my static functions (I think this is called singleton/factory?), is it enough to make the default constructor private, or do I also need to explicitly define and make private a copy constructor and assignment operator?
| Yes, I would do all 3 of those manager functions. If not, you do not want to be able to access the copy constructor. For example, this is valid:
Singleton * s;
Singleton copy( *s );
So do something like:
class Singleton
{
private:
Singleton();
Singleton(const Singleton &);
Singleton & operator = (const Singleton... |
4,092,417 | 4,092,673 | How do I invoke this native method from C# | I want to invoke one/many functions of a native library but I am unsure on the type mappings. The function in particular I am currently trying is as follows, here is the small console app which I am spiking in:
extern char *tgetstr (const char *name, char **area);
And here is my attempt at mapping this to use in a .N... | You need to pass your IntPtr by ref, so the function can overwrite it. Then you also need to free the string after you've copied it, hopefully the DLL provides a matching deallocation function. StringToCoTaskMemAnsi isn't helping you any either, it's just leaking memory.
The correct p/invoke declaration is probably
[... |
4,092,582 | 4,092,612 | Displaying an error message if a file can't be opened, C++ | I'm using fstream to open up .txt files with C++. So far it's working great. However, I'd like my console to display an error message if the input_file can't be opened. How should I go about this?
Snippet:
cin >> in_file_name ;
ifstream in_file(in_file_name.c_str());
in_file_str.assign(istreambuf_iterator<char>(in_... | ifstream in_file(in_file_name.c_str());
if( in_file.fail() ) {
cerr << "Error!" << endl;
}
|
4,092,726 | 4,092,806 | C++ building custom defines | How can I add custom commands to the cmake when invoking something like
cmake -G"Visual Studio 9 2008"
I wish to be able to handle the case when the supplied library finder / configurator works wrong and I want to override the corresponding variables like
set BOOST_DIRECTORY = C:\boobs\
to solve problems like no boost... | You can use the CMake gui programs to interactively set Cache values:
ccmake
or alternatively:
cmake-gui
|
4,092,729 | 4,092,760 | fibonacci numbers, why does this recurring function work? | I'm going through a programming book and one of the examples is about fibonacci numbers, and how a recurring function finds the fibonacci number for the nth one along.
The code looks like this:
Int fib (int n)
{
If (n<3)
Return (1);
Else
Return (fib(n-1))+(fib(n-2))
}
Now this isn't exact because I'm typing from my p... | A Fibonacci number is defined as the sum of the two preceding Fibonacci numbers. That gives the following:
1 1 2 3 5 8 13 ...
So for the 3rd number (1 1 2) you would take the result of finding the previous - i.e. 2nd (1 1 2) number and add it to the number before the previous - i.e. 1st (1 1 2) number.
You also have t... |
4,092,747 | 4,093,210 | c++ pointers to objects type checking | How do I verify that an object being pointed by a pointer is valid
relevant code
LookupTable<Product *> table;
Product temp = *table[selection];
// if *table[selection] is not a product, program crashes...
Here is what Lookup table is:
#ifndef LOOKUPTABLE_H
#define LOOKUPTABLE_H
#include <iostream>
#include <string>
... | Based on the code of LookupTable that you posted in a subsequent question, this question can finally be answered. (Really, I think you ought to just put that code here and remove the other question.)
table[selection] either returns a reference to an entry in the table (if the selection is found) or otherwise a referenc... |
4,093,024 | 4,093,104 | C++ - want virtual acting solely as redirection | Let's say I have a template:
template <class N, class I>
void add(N* element, std::list<N*> & container, I (N::*f)() const,
std::string successmsg, std::string exceptmsg) {
//...
}
And I want to call it for a list of Base Class pointers to a derivative class.
add(newAirplane, airplanes, &Airplane::getRegistrat... | You need another template parameter, because you care about two different classes - the type of the pointer (and hence the member function you're going to call with it), and the type of the container:
#include <list>
struct AirplaneType {
};
struct Airplane : AirplaneType {
int check() const { return 3; }
};
tem... |
4,093,057 | 4,093,081 | Working with ListView in C++ | I got a stupid question on ListView Control usage.
I created a Windows Form App in VS2005. No I dragged a ListView Control from the toolbox. I want to implement my code to show some content(including both columns and rows).
I know a little of MFC knowledge. I am not sure I must study the past MFC CListCtrol knowledge ... | Actually you don't need that much of your previous knowledge of MFC to implement ListView. C++ under .NET (in layman terms means WinForm applications), you can almost seamlessly translate C# code to C++. If I understood your question correctly, what you need to do is to make sure how objects and properties are accessed... |
4,093,095 | 4,093,186 | c++ set null pointers? | how would i set this to null;
LookupTable<Product *> table;
everything i try says
1 IntelliSense: no suitable constructor exists to convert from "int" to "LookupTable"
Here is what Lookup table is:
#ifndef LOOKUPTABLE_H
#define LOOKUPTABLE_H
#include <iostream>
#include <string>
using namespace std;
#define MAXRAN... | Here's how you set it to NULL - you define it as a different type:
LookupTable<Product *>* table = NULL;
If you are used to dealing with C#, then you might be able to think of classes as "value types".
This might also behave differently than you think. In C++:
LookupTable<Product *> table1;
LookupTable<Product *> tab... |
4,093,100 | 14,249,101 | How may I deploy a Wt application with the built-in web server? | I am new using Wt and I would like to know what I must do to get an example (let’s say Hello) working on a web server (Apache or free webhost for testing).
I know how to use the built-in web server ; I have to launch that command :
./hello.wt --docroot . --http-address 0.0.0.0 --http-port 8080
Then, I go to http://127... | I added FastCgiServer /dir/to/Wt/Examples/Hello/hello.wt to my fastcgi.conf and now it's working.
|
4,093,183 | 4,093,196 | Converting Java to C++ | I'm new to C++ so I'm having trouble converting this into C++. Is there examples that I could see how a C++ arraylist looks. I know java has several classes that can be made but in C++ how would that be made would it be all under one .cpp file.
public class Main {
public static void main(String[] args) {
Inventor... | vector is probably your friend. Look here: http://www.cplusplus.com/reference/stl/vector/vector/
|
4,093,190 | 4,093,242 | OpenGL Renders texture with different color than original image? | Why are these not displaying the same colors?
Original Image:
Plane with above Image as texture:
WTF is happening?
The original image is 100x100 pixels, made in paint and saved as a 24 bit bitmap.
Here is my opengl initialization code:
_hdc = GetDC(_hwnd);
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory( &pfd, sizeof( pfd... | Bitmaps are stored BGR (blue-green-red). Your loading code is loading it as RGB (red-green-blue). This is flipping your red and blue channel.
Use GL_BGR for the format parameter of glTexImage2D.
|
4,093,252 | 4,093,761 | Read another process' stdout in C++ | In Windows, is there a way to launch a process in C++ and then read what it spat out into stdout when it's done? The process must be run using elevated privileges (on Vista or later) if necessary.
I'm currently using ShellExecuteEx() to launch the process and running a while-loop until GetExitCodeProcess() no longer re... | There's no easy way to do this.
Calling ShellExecuteEx() with the runas verb sends an RPC message to the AppInfo NT Service witch then run the application from an elevated session. There's no API to easily connect the input/output of the elevated process to your application.
Thomas Hruska in his The Code Project articl... |
4,093,286 | 4,093,300 | C++ templates - basics | I'm trying to follow my college notes, and I've tried googling the error and looking on stackover flow but I can't seem to figure out whats wrong.
I've read on so many places that you need to have both implementation and specification files in one file (header) so I've done so. I've just copy and pasted from my printed... | template<class A_type> // lowercase t in A_type
A_Type calc<A_Type>::multiply(A_Type x, A_Type y) // uppercase T's in A_Type
|
4,093,353 | 4,093,401 | Cannot convert parameter from WCHAR[100] to WCHAR** | I have a method expecting WCHAR**, i need to get some data back from this method. I am declaring an array WCHAR[100] and passing it to the function. The compiler throws this error:
WCHAR result[100];
UINT i;
hr = SomeFunc(handle, &i, result);
error C2664: 'XXXX' : cannot convert parameter 3 from 'WCHAR [100]' to 'WCHA... | Generally speaking, if a function takes a pointer to a pointer (WCHAR** in this case) then it will allocate its own memory and set the pointed-to pointer to that memory. The documentation of SomeFunc should describe if this is indeed what happens.
If that is the case, then you would likely need something like:
WCHAR* r... |
4,093,407 | 4,093,421 | C++ namespaces and defining classes in separate files | I want to make a namespace that will contain several classes as part of a "package".
Do I have to declare all of the classes within the namespace?
For example, if I have a "2dEngine.h" which defines the 2dEngine namespace, do I have to declare all of the individual classes within that header file? Or can I still separa... | Yes, you can split the namespace into multiple blocks (and hence files). Your classes will belong to the same namespace as long as they are declared in the namespace block with the same name.
// Canvas.h
namespace TwoEngine
{
class Canvas
{
// Define all of Canvas here
};
}
// Primitive.h
namespace... |
4,093,466 | 4,093,479 | C++ Polymorphism with template class | template<typename Type>
class List
{
public:
List(void);
~List(void);
...
}
which inherited by
template<typename Type>
class LinkedList : public List<Type>
{
public:
LinkedList(void);
~LinkedList(void);
...
}
but when I
List<int>* list = new LinkedList<int>();
there comes
error LNK2019: unresolved e... | The error is generated by the linker because you did not define the constructor for the LinkedList class. Or it is not visible to the compiler at the point where you use the type LinkedList<int> as shown above.
|
4,093,608 | 4,169,013 | visual studio 2010 c++ load time | This is probably way too vague for any concrete answers, but this issue has been bothering me so I figured I'd give it a shot here:
Every time I hit F5 to run a project (and I'm talking something tiny 2 - 3 source files), first of all half the time it tells me that I need to rebuild the project even if the only change... | The long waiting time before VS actually starts the application when hitting F5 occurs in VS 2008 as well. The simple solution to that is to delete the .suo file. I don't know if VS 2010 uses .suo files, but at least it's something you can try.
|
4,093,919 | 4,093,968 | Is it bad practice to use co-dependent classes? | If I have a Container class which holds a bunch of Component objects (similar to Java's UI framework), would it be poor style/practice to keep track of the Container parent within each Component?
This ends up causing some strange compiler issues because the Component includes the header file for Container and vice-vers... | Actually I think it's a design problem. You really should look at the design as a whole and see if you can design it better. Ask yourself why you have the dependent classes requiring access to the container. Perhaps the container is providing functionality it should not. Can this functionality be provided in another wa... |
4,093,932 | 4,097,269 | Why Is C++ Issuing Warnings On Enums With Negative Values? | My current code resembles this:
enum Enum1 : signed __int8
{
Value1 = 1 ,
Value2 = 2 ,
Value3 = -3 // C4341
} ;
The error details state:
"warning C4341: 'Value3' : signed value is out of range for enum constant"
MSDN states that this warning only occurs when you use values outside of the range of an int:
... | Seems like a bug to me. The current 0x draft doesn't indicate that this should be the case, and neither does the MSDN documentation.
|
4,094,008 | 4,094,068 | Ambiguity Resolution | void S(){}
struct S{};
int main(){
S();
}
In the code above, the expression 'S()' in main is treated as a function call expression rather than an attempt to create a temporary of type 'S'.
Which portion of the C++ Standard talks about the resolution of such an expression in favour of a function declaration? For so... | Section 3.3.7/2
A class name (9.1) or enumeration name (7.2) can be hidden by the name of an object, function, or enumerator declared in the same scope. If a class or enumeration name and an object, function, or enumerator are
declared in the same scope (in any order) with the same name, the class or enumeration... |
4,094,028 | 4,094,703 | boost.asio - set maximum read stream size | There's example HTTP Client at http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio/example/http/client/async_client.cpp
Please help me to change maximum buffer size like explained in following code (it's from examples downloaded with library, not from site):
void handle_write_request(const boost::system::error_cod... | 1) I'm not sure where your 512 bytes limit is coming from since the constructor for the asio::basic_streambuf has the following signature (which allows it to store way more than 512 or 1024 bytes):
explicit basic_streambuf(
std::size_t max_size = (std::numeric_limits<std::size_t>::max)(),
const Allocator& alloc... |
4,094,253 | 4,094,438 | Name lookup Clarification |
$10.2/4- "[ Note: Looking up a name in
an elaborated-type-specifier (3.4.4)
or base-specifier (Clause 10), for
instance, ignores all nontype
declarations, while looking up a name
in a nested-name-specifier (3.4.3)
ignores function, variable, and
enumerator declarations."
I have found this statement to b... | Q1: I think so.
Q2: Compatibility with C. When you declare a struct in C, the tag name is just that, a tag name. To be able to use it in a standalone way, you need a typedef. In C++ you don't need the typedef, that makes live easier. But C++ rules have been complicated by the need to be able to import already exist... |
4,094,340 | 4,094,346 | Initialize a static const empty array | Is it possible to initialize a static const empty array, please see below code,
//CFoo.h
class CFoo
{
public:
CFoo();
~CFoo();
public:
static const int arr[];
};
//CFoo.cpp
const int arr[] = {0,1,2};
CFoo::CFoo(){}
CFoo::~CFoo(){}
EDIT:
It seems the code is valid, and for followup question, why I can't... | Yes; you need to qualify the name of the array:
const int CFoo::arr[] = {0,1,2};
The type of CFoo::arr is incomplete until the definition, so you are limited in how you can use it. For example, you cannot use it as the argument of sizeof. If you complete the declaration, then there's no problem:
struct CFoo {
st... |
4,094,357 | 4,094,383 | Objective-C enum error? | I've defined an enum at the top of my class header:
enum PresetSeq{kSeqClear=0, kSeqAllBeats, kSeqAllTicks};
But when I try to declare a method for that class using the enum.
-(void)quickSetSeq:(PresetSeq)pattern forChannel:(long)ch;
I get the error: expected ')' before 'PresetSeq'
If I typedef the enum instead:
ty... | These are C enums. (Remember Objective-C is just a strict superset of C).
To define an enumerated type, you must use typedef.
However, if you do not need to have a standalone type (without the enum prefix) to collectively refer to that enum, then you do not need typedef and you can just declare it like this:
enum Prese... |
4,094,414 | 4,094,442 | What does it mean when using the template in C++ | Recently, I meet something in other's source code. I don't quite understand the template in C++. Could you help me it?
struct my_grammar : public grammar<my_grammar>
{
...
};
Why my_grammar can be used as a type parameter like it?
Best Regards,
| This is an idiom called the Curiously Recurring Template Pattern - see http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern. Summarily, it provides the derived class as a policy to the base class, in similar style to Policy's used in Alexandrescu's Modern C++ Design book (highly recommended). That way, t... |
4,094,534 | 4,094,751 | How and why is it possible to change access level of a member? | I ended up coding (With some help) something like this yesterday:
#include <iostream>
using namespace std;
class A
{
public:
virtual void foo(){cout << "A::foo\n";}
};
class B : private A
{
private:
virtual void foo(){ cout << "B::foo\n";}
void DoSomething(SomeOtherClass& o){o.DoSomet... | May not answer all your questions directly, nevertheless I decided to put it up here for future reference. Also please take it with a pinch of salt as this is based on my understanding of the events that have happened in the C++ Standard world, rather than the actuals.
Read this. I don't have the ARM with me, but the a... |
4,094,604 | 4,094,757 | Boost Serialization - Serialize std::tr1::shared_ptr? | Boost::Serialization has builtin support for boost::shared_ptr<>.
Is there a way to use this support for std::tr1::shared_ptr<> too?
Is it possible to cast from std::tr1::shared_ptr<> to boost::shared_ptr<>?
| A casting will not be possible as implementations differ. Also creating an instance of the one shared_ptr type with the value returned from get() on the other shared_ptr type will not work correctly as the reference countings will go to 0 at different points in your code which leads to deletion of the object before the... |
4,094,996 | 4,095,025 | What happens to the memory allocated by `new` if the constructor throws? | Will this code cause a memory leak?
#include <stdexept>
class MyClass
{
public:
MyClass()
{
throw std::runtime_error("Test");
}
};
int main()
{
try
{
MyClass * myClass = new MyClass;
}
catch (const std::exception & exc)
{
// Memory leak?
}
return 0;
}
T... | The memory will be automatically freed before the exception propagates.
This is essential, because a) the program never receives a pointer to free, and b) even if it did, it would have no portable way to actually free it since the memory never became an object that you can delete.
|
4,095,021 | 4,095,960 | How to make Windows go to sleep from app? | Im trying to make an app that can put windows 7 to sleep,
I have been looking at WM_Messages, but cant seem to find one that does the jobb.
I can use ether C++ or Delphi to make the app if there it makes any difference.
| Use SetSuspendState function which is in powrprof.dll:
function SetSuspendState(hibernate, forcecritical, disablewakeevent: boolean): boolean;
stdcall; external 'powrprof.dll' name 'SetSuspendState';
SetSuspendState(false, false, false); // stand by
SetSuspendState(true, false, false); // hibernate
|
4,095,188 | 4,095,334 | Do something if template type is instantiable | I would like to use the SFINAE pattern to execute some code if I can instantiate a certain template class. Let's imagine this:
//Only instantiable with types T for which T.x() is ok:
template <class T>
class TemplateClass
{
T t;
public:
void foo() {
t.x();
}
}
template <class T>
class User
{
void foo()
... | You should look at the boost boost/utility/enable_if.hpp header and the associated meta/template programming code.
The easiest way here is to have two versions of the foo function, both template functions. One of the functions will use the enable_if construct and the other will use the disable_if construct.
I'm sure yo... |
4,095,218 | 4,096,323 | Trigger specific constructor for a member in the member initialisation list based on a flag | I would like to trigger a specific constructor for a member variable based on flags I pass to the containing class's constructor.
It's easiest if I start with a trivial example:
#include <boost/optional.hpp>
#include <boost/none.hpp>
#include <boost/utility/typed_in_place_factory.hpp>
struct state
{
bool flag1;
bo... | It appears that using boost::optional<> is complicating things, using it with the copy constructed approach seems to cause both the state based and copy based constructors of A & B to be called - even with full optimization.
However, if I define the members of C as simply A _a and B _b, the copy constructor is actually... |
4,095,337 | 4,095,399 | How to check for inf (and | or) NaN in a double variable | Consider the following code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
template<class T>
bool IsNaN(T t)
{
return t != t;
}
int main(int argc, char**argv)
{
double d1, d2;
sscanf(argv[1], "%f", &d1);
sscanf(argv[2], "%f", &d2);
double dRes = d1/d2;
cout <... |
When using scanf() double should be read using %lf, not %f. %f will convert the input into a 32-bit float, so the first 32 bits of your variables will be filled with some invalid data, and the last 32 bits will be left as garbage.
Yes. #include <limits>, then std::numeric_limits<double>::quiet_NaN(). Some compilers (... |
4,095,343 | 4,095,387 | No appropiate default constructor available when using template classes | I've got a template class like so:
template<class T>
class List
{
private:
struct node
{
T value;
node *next, *prev;
};
}
When creating instances of this List class with T = myClass* I have no problems, since value will be a pointer, but if it's an object, creating a node instance results ... | You could provide a constructor for node that requires an instance of T from which a copy can be constructed:
template<class T>
class List
{
private:
struct node
{
node(const T & init_value) : value(init_value) {}
T value;
node *next, *prev;
};
}
This would change the requirement o... |
4,095,637 | 4,183,178 | memory use of STL data structures, windows vs. linux | I have a program that heavily uses std::map. Under Windows, much more memory is used as under Linux. Has anyone an idea why this happens?
Linux:
Last process took 42.31 s and used not more than 909 MB (RSS 900 MB) of memory
Windows:
Last process took 75.373 s and used not more than 1394 MB (RSS 1395 MB) of memory
I use... | You'll observe that memory usage on Windows is somewhere between 1 and 2 times greater. Heap algorithms aside, Windows malloc(), and subsequently any data structures allocated on the heap via new (such as std::map's nodes with the default allocator type), are aligned to 16 bytes. On Linux, glibc defaults to 8 byte alig... |
4,095,668 | 4,095,685 | Searching a std::Map | What is the best way to search a std::Map for a specific key and value? Which basically means that I would like to find if exists a std::pair with key and value specified by me.
| Something like this ?
auto piter = m_mMap.find(iKey);
return pIter != m_mMap.end() && pIter->second == myvalue;
|
4,095,676 | 4,095,748 | Recommendations for C++ profiling tools | Can anyone recommend any tools for compile and runtime analysis of C++ code? I'm being hit day after day with requests to identify where certain overloads of functions are being used in a very large code base.
My current method involves a combination of (a) text search using grep / find and (b) spoofing the include fil... | I've used a combination of gprof and a script called gprof2dot which gives you a call graph showing how much time is spent in each method.
See this article on gprof. Also take a look at:
Optimizing C/C++ programs using the GProf profiler
Here is an example call graph showing time spent in each method ( taken from th... |
4,095,816 | 4,106,939 | Hiding C++ symbols in iOS static library? | I've made an iOS code library in pure C++, which I intend to publish to a lot of people. As far as I know, at the time of writing, the only way to share compiled code on iOS is through a static library.
Unfortunately, there are some clever bits in the code which I'd like to hide from public view. What I'd like to do is... | Solved it! I ended up with first of all including all the source in a single cpp. Secondly I put all non-external stuff in an unnamed namespace. Then to get rid of the remaining symbols I added this script to the build process:
echo MyGlobalFunctionToInstantiateMainClass > "${BUILT_PRODUCTS_DIR}/save_symbols"
strip -s ... |
4,095,970 | 4,096,058 | quote symbol parsing | i have file like this
"a",205
"b",214
"c",223
""",13
and i need to parse it
i read line by line to str and i have to convert second character from string to integer, but when it comes to quote <"> character it throws an exception string subscript out of range.
std::string STRING;
std::ifstream infile;
st... |
tokens[0][1] gets the second character of the first string, which is out of range.
The type cast is not the way to convert. use atoi().
|
4,096,275 | 4,096,306 | c++: asm clobber list | In g++, clobber lists for asm can be specified, for example:
asm ("somecode" : : "r1", "r2", "r3");
which means that the asm code changes registers r1, r2, r3.
Now, my changed registers depend on a template parameter n (the asm block is inside of a template function), and registers r1, ..., rn will be changed. How can... | How many different register constellations are you confronted with? If not too many, you could provide a specific implementation for each. (Template Specialization)
Because, I apprehend that there's no possibility to create "templated statements".
|
4,096,418 | 4,096,471 | Vector initialized with size, impossible to clear | I have this declaration of a multidimensional vector
std::vector< vector < vector < ofxImage > > > front_objects;
Then I send it to my class when creating it:
Catalog_object * temp = new Catalog_object(&front_objects, numTag);
And then I perform the following:
Catalog_object::Catalog_object(vector< vector < vector ... | Most likely in
front_objects[numTag].resize(2);
numTag holds an invalid index.
Without the relevant code is difficult to say. Effectively you're saying that every time you walk into your kitchen you hear a strange sound. The picture of the cat that's stuck in between two somethings makes it likely that it's the cat, b... |
4,096,493 | 4,096,534 | Linking error: templated friend operator overload | I am having a strange linking error. I followed instructions presented here to avoid this kind of problems, but I can't figure out how to split headers and implementation files.
Here's my test file:
#include <cargo.h>
#include <iostream>
#include <string>
using namespace std;
using namespace dom;
int main()
{
dom... | (Member) function templates are not functions; the linker doesn't see them unless you instantiate them. Source files are compiled separately, so if you put a (member) function template in one source file and don't explicitly instantiate it, the linker won't see it.
So in your case, the function template has not been t... |
4,096,622 | 4,108,894 | How to get the executable name when accessing the program's resources through HTML? | I have a HtmlView inside my MFC program where I display some data in HTML form. The HTML makes use of some resources included within the executable file, so, in general, my HTML files include some things like:
<script language="javascript" type="text/javascript" src="res://MyProgram.exe/JS/IDR_JQUERY"></script>
or
<im... | After some time meddling with IHTMLElement, I found a much easier way to do it. Since my HTML file is itself inside the program resources, I found I could just do relative references. So my examples turned to:
<script language="javascript" type="text/javascript" src="../JS/IDR_JQUERY"></script>
<img src="../JPG/PROGRA... |
4,096,655 | 4,096,859 | C++ template casting on derived classes | I have 3 class which derived from each other:
class Basic{
...
}
class Extended : public Basic{
...
}
class Full : public Extended{
...
}
I have a template class which holds 5-5 from this classes:
template <class T>
class group{
public:
...
private:
T one, two, three, four, five;
... | A solution would be to create a kind of view-class that can wrap a group, and exposes the individual objects as base-class instances:
template <class T>
class group{
public:
const T & getOne() { return one; }
private:
T one, two, three, four, five;
};
template <class T, U>
class group_view {
public:
group_... |
4,096,709 | 4,097,436 | sprint_f macro in Linux for cross-platform application | I'm porting an existing Windows application to Linux.
The most of the OS APIs\ Microsoft non-standard extension functions can be easily (more or less...) replaced by equivalent Linux\ GCC APIs, however, I don't know how to deal with sprintf_s which gets variable numbers of arguments.
Does anyone have an idea (If you ca... | First, can you just port your code to use C++ iostreams instead (for example ostringstream)? This would completely remove all the possible issues with the sprintf line of functions, and if there are a limited number of call points is probably the best option.
If that isn't an option: The sprintf_s function is basically... |
4,097,153 | 4,097,231 | How to transpose matrix using uBLAS? | I am a newbie in C++ Boost uBLAS library so I have a noob question - how to transpose a matrix using this library? I could not find question here:
http://www.boost.org/doc/libs/1_44_0/libs/numeric/ublas/doc/html/index.html
| C = boost::numeric::ublas::trans(A);
Documented (poorly) under Overview of Matrix and Vector Operations.
|
4,097,257 | 4,099,390 | Number of unset bit left of most significant set bit? | Assuming the 64bit integer 0x000000000000FFFF which would be represented as
00000000 00000000 00000000 00000000
00000000 00000000 >11111111 11111111
How do I find the amount of unset bits to the left of the most significant set bit (the one marked with >) ?
| // clear all bits except the lowest set bit
x &= -x;
// if x==0, add 0, otherwise add x - 1.
// This sets all bits below the one set above to 1.
x+= (-(x==0))&(x - 1);
return 64 - count_bits_set(x);
Where count_bits_set is the fastest version of counting bits you can find. See https://graphics.stanford.edu/~se... |
4,097,290 | 4,097,341 | Download a file from the web in C++ without using non-standard libraries on Linux | When I say non-standard libraries, I am referring to things like Boost, libCurl and anything else that may be able to do this far easier than standard C++ can. The reason for this is that I am writing an application as a piece of coursework (the class is dedicated to C++) and I am required to use only standard librarie... | Check out Beej's Guide to Network Programming for a quick but excellent introduction to sockets. If you cannot use any non-standard libraries, your only option is to manually connect on port 80 and make the request yourself.
Assuming even a beginner-level knowledge of C++, that should be all you need.
|
4,097,339 | 4,097,665 | Missing Python.h while trying to compile a C extension module | I'm following this tutorial on how to extend Python with C\C++ code.
The section named "Building the extension module with GCC for Microsoft Windows" fails for me with the following error:
fatal error: Python.h: No such file or directory
The section named "Building the extension module using Microsoft Visual C++" also... |
Do you have the python dev files so that you can find Python.h?
Do you have the location of Python.h specified to your compiler? with gcc this is usually done through a -I path to include.
Figuring out which of those is failing will solve your problem.
from the article you linked:
gcc -c hellomodule.c -I/PythonXY/in... |
4,097,533 | 4,097,558 | Chained typedef : Perf. issue? | Working with new pieces of code, I asked myself a question : Are multiple typedef's over the same basetype impacting performances ?
Example (I know it's silly but that's what I actually saw, four levels of typedef...) :
typedef float T_FLOAT
typedef T_FLOAT T_TIME
typedef T_TIME T_CURRENTTIME
tyoedef T_CURRENTTIME CLOC... | No, typedef is a compile time only option.
|
4,097,536 | 4,097,625 | Using move semantics with std::pair or std::tuple | Suppose you want to take advantage of move semantics, but one of your movable classes needs to be part of an std::pair. The purpose would be to create a function that returns an std::pair that can be treated as an rvalue, and forwarded along.
But I can't see how this can be done, unless an internal change to std::pai... | That's not the std::pair constructor that will be called, though. The std::pair move constructor will be called, and the move constructor should do exactly what you expect (N3126 20.3.5.2/6):
template<class U, class V> pair(pair<U, V>&& p);
Effects: The constructor initializes first with std::move(p.first) and secon... |
4,097,544 | 4,097,623 | Providing an IDispatch implementation for a connection point client | I've written a simple COM DLL inproc server with a single simple COM object. The COM object implements a connection point.
I know how to create an ATL client that derives from IDispEventImpl, and uses a sink map to simplify this process.
But, for the purposes of demonstration, I'd like to create a win32 console applic... | Since you already have ATL you can examine its sources and see how IDispatchImpl does all that stuff. IDispatch methods are implemented therehby reading data from the type library in the same module since it's the easiest and most reliable way when a type library is already present.
It's also worth noting that it's a r... |
4,097,587 | 4,097,627 | same class, different size...? | See the code, then you would understand what I'm confused.
Test.h
class Test {
public:
#ifndef HIDE_VARIABLE
int m_Test[10];
#endif
};
Aho.h
class Test;
int GetSizeA();
Test* GetNewTestA();
Aho.cpp
//#define HIDE_VARIABLE
#include "Test.h"
#include "Aho.h"
int GetSizeA() { return sizeof(Test); }
Test* GetNewTes... | You violated the requirements of One Definition Rule (ODR). The behavior of your program is undefined. That's the only thing that's going on here.
According to ODR, classes with external linkage have to be defined identically in all translation units.
|
4,097,632 | 4,097,969 | Linux Programming Essentials | I was just thrust into Linux programming (Red Hat) after several years of C++ on Win32. So I am not looking for the basics of programming. Rather I am looking to get up to speed with things unique to the Linux programming world, such as packages, etc. In other words, I need to know everything in https://www.redhat.com/... | Edited because I had to leave a meeting when I originally submitted this, but wanted to complete the information
Half of that material is learning about development in a Unix-like environment, and for that, I'd recommend a book since it's tougher to filter out useful information from the start.
I'd urge you to go to a ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.