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
|
|---|---|---|---|---|
255,081
| 255,159
|
Is it possible to make a vs2008 c++ project import source file names from another file?
|
I have a situation where another developer is including source files from a project that I maintain in a project that he maintains. The nature of the files is such that each source file registers a "command" in an interpretive environment so all you have to do is link in a new source file to register a new "command". We can't put these files in a static library because, unless the project makes explicit reference to the symbols in the file, the linker will optimise the file away.
It seems like a potential solution is to have a file external to both projects that "includes" a list of source file names in both projects. The problem is that I have no idea whether or how this could be done. Suggestions, anyone?
|
There is no reason a source file can't be in multiple projects. Just add it as an 'existing item' in VS.
If you are using precompiled headers then both projects will need equivalent set ups for this to work.
You can also use a #pragma in a lib to force a symbol to be included when the linker would otherwise discard it.
#pragma comment(linker, "/include:__mySymbol")
See the MSDN document for #pragma comment and the include option
|
255,198
| 7,519,697
|
Non-GPL JSON-RPC library for C++
|
What non-GPL libraries are available for writing JSON-RPC servers and clients in native C++?
According to http://json-rpc.org/wiki/implementations, there seems to only exist one implementation of JSON-RPC for C++, namely JsonRpc-Cpp, but that only available under GPL. Unfortunately we cannot use GPL code in our software.
The JSON RPC C Library from big-llc.com, could be an alternative. They call it "a free lightweight implementation C library to handle JSON-RPC requests easier", but they do not mention the licensing.
Anyone who knows of other options?
|
JsonRpc-Cpp is available as LGPLv3 since version 0.3 release 2011-05-06.
|
255,645
| 256,025
|
How can I count operations in C++?
|
How can I count operations in C++? I'd like to analyze code in a better way than just timing it since the time is often rounded to 0 millisec.
|
You can do precise measurements by reading the time-stamp-counter (tsc) of the CPU, which is incremented by one at each cpu-clock.
Unfortunately the read is done inlining some assembler instructions in the code. Depending on the underlying architecture the cost of the read varies between ~11(AMD) and ~33(Intel) tsc. With 1 Ghz CPU you can virtually have the nano-second precision.
In order to perform a reliable and non-invasive measure of a section of code you can:
prevent the cpu scaling frequency by disabling the cpu features such as AMD cool'n quite or Intel SpeedStep.
repeat the test several times, collecting the measures in an array and then saving data to file for an off-line analysis.
choose a real-time scheduling policy for the process under test such as SHED_RR or SHED_FIFO. Realtime policies reduce the number of context-switch between the process under test and other normal processes/kernel threads, that are blocked.
lock all the process's virtual address space in RAM by means of mlockall() system call.
Here you can find a quasi-portable C++ class I wrote for Linux, derived from the Linux kernel and designed to read tsc for the architectures i386, x86_64 and ia64.
|
255,741
| 255,765
|
Can you call Ada functions from C++?
|
I'm a complete Ada newbie, though I've used Pascal for 2-3 years during HS.
IIRC, it is possible to call Pascal compiled functions from C/C++. Is it possible to call procedures & functions written in Ada from C++?
|
According to this old tutorial, it should be possible.
However, as illustrated by this thread, you must be careful with the c++ extern "C" definitions of your Ada functions.
|
255,773
| 255,780
|
What C/C++ compilers are available for VxWorks?
|
I'm new to the VxWorks environment, I'm wondering what C and C++ compilers are available for use with VxWorks?
|
As far as i know Tornado VxWorks IDE using gcc toolchain.
Any way i suggest to use the compiler provided by WindRiver (which i believe their version
of gcc) to avoid compatibility problems.
It's probably worth to menation the VxWorks version you having in mind.
I guess gcc version will be depend on VxWorks version and probably on target platform.
|
255,852
| 255,937
|
Parallel Programming and C++
|
I've been writing a lot recently about Parallel computing and programming and I do notice that there are a lot of patterns that come up when it comes to parallel computing. Noting that Microsoft already has released a library along with the Microsoft Visual C++ 2010 Community Technical Preview (named Parallel Patterns Library) I'm wondering what are the common parallel programming patterns you have been using and encountering that may be worth remembering? Do you have any idioms you follow and patterns that you seem to keep popping up as you write parallel programs with C++?
|
Patterns:
Produce/Consumer
One Thread produces data
One Thread consumes the data
Loop parallelism
If you can show that each loop is independent
each iteration can be done in a sperate thread
Re-Draw Thread
Other threads do work and update data structures but one thread re-draws screen.
Main-Event Thread
Multiple threads can be generating events
One thread has to processes the events (as order is important)
Should try separate the Event Thread/Re-Draw Thread
This (helps) prevents the UI from freezing
But may cause excessive re-draws if not done carefully.
Work Group
A set of threads waits for jobs on a que.
Thread extract one work item from queue (waiting if none is available).
Thread works on one work item until complete
Once completed thread returns to queue.
|
256,033
| 256,309
|
Is std::string size() a O(1) operation?
|
Is std::string size() a O(1) operation?
The implementation of STL I'm using is the one built into VC++
|
If you're asking if MSVC's implementation of string::size() has constant complexity, then the answer is yes. But Don Wakefield mentioned Table 65 in 23.1 of the C++ Standard where it says that the complexity of size() should follow what's said in 'Note A'. Note A says:
Those entries marked ‘‘(Note A)’’
should have constant complexity.
However, that does not mean that those entries shall have constant complexity. Standards use very specific terminology, and "should" means that it is not mandatory.
'Note A' was added to the standard specifically to appease those who believed that size() should be allowed to have linear complexity so it would not be necessary to keep the size when the containers were modified.
So you can't rely on size() having constant complexity, but I'm honestly not sure if there are any implementations that do not have a constant string::size().
|
256,038
| 256,243
|
How can I increase the performance in a map lookup with key type std::string?
|
I'm using a std::map (VC++ implementation) and it's a little slow for lookups via the map's find method.
The key type is std::string.
Can I increase the performance of this std::map lookup via a custom key compare override for the map? For example, maybe std::string < compare doesn't take into consideration a simple string::size() compare before comparing its data?
Any other ideas to speed up the compare?
In my situation the map will always contain < 15 elements, but it is being queried non stop and performance is critical. Maybe there is a better data structure that I can use that would be faster?
Update: The map contains file paths.
Update2: The map's elements are changing often.
|
First, turn off all the profiling and DEBUG switches. These can slow down STL immensely.
If that's not it, part of the problem may be that your strings are identical for the first 80-90% of the string. This isn't bad for map, necessarily, but it is for string comparisons. If this is the case, your search can take much longer.
For example, in this code find() will likely result in a couple of string compares, but each will return after comparing the first character until "david", and then the first three characters will be checked. So at most, 5 characters will be checked per call.
map<string,int> names;
names["larry"] = 1;
names["david"] = 2;
names["juanita"] = 3;
map<string,int>::iterator iter = names.find("daniel");
On the other hand, in the following code, find() will likely check 135+ characters:
map<string,int> names;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/wilma"] = 1;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/fred"] = 2;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/barney"] = 3;
map<string,int>::iterator iter = names.find("/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/betty");
That's because the string comparisons have to search deeper to find a match since the beginning of each string is the same.
Using size() in your comparison for equality won't help you much here since your data set is so small. A std::map is kept sorted so its elements can be searched with a binary search. Each call to find should result in less than 5 string comparisons for a miss, and an average of 2 comparisons for a hit. But it does depend on your data. If most of your path strings are of different lengths, then a size check like Motti describes could help a lot.
Something to consider when thinking of alternative algorithms is how many many "hits" you get. Are most of your find() calls returning end() or a hit? If most of your find()s return end() (misses) then you are searching the entire map every time (2logn string compares).
Hash_map is a good idea; it should cut your search time in about half for hits; more for misses.
A custom algorithm may be called for because of the nature of path strings, especially if your data set has common ancestry like in the above code.
Another thing to consider is how you get your search strings. If you are reusing them, it may help to encode them into something that is easier to compare. If you use them once and discard them, then this encoding step is probably too expensive.
I used something like a Huffman coding tree once (a long time ago) to optimize string searches. A binary string search tree like that may be more efficient in some cases, but its pretty expensive for small sets like yours.
Finally, look into alternative std::map implementations. I've heard bad things about some of VC's stl code performance. The DEBUG library in particular is bad about checking you on every call. StlPort used to be a good alternative, but I haven't tried it in a few years. I've always loved Boost too.
|
256,109
| 256,114
|
how to install boost to the VS 2008?
|
I've almost completely installed Boost, but I have a problem with how to set my path to Boost in Tools->options->projects->VC++ Directories.
I've written the path to include files and libraries (my folder contains two subfolders, lib and include), but when I try to use Boost with
#include boost/regex.hpp, I got this linking error:
LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc90-mt-gd-1_36.lib
Could you please tell me how to install Boost correctly for Visual Studio 2008?
|
Use the Boost Installer by the Boost consulting group.
|
256,188
| 256,242
|
How much memory does a thread consume when first created?
|
I understand that creating too many threads in an application isn't being what you might call a "good neighbour" to other running processes, since cpu and memory resources are consumed even if these threads are in an efficient sleeping state.
What I'm interested in is this: How much memory (win32 platform) is being consumed by a sleeping thread?
Theoretically, I'd assume somewhere in the region of 1mb (since this is the default stack size), but I'm pretty sure it's less than this, but I'm not sure why.
Any help on this will be appreciated.
(The reason I'm asking is that I'm considering introducing a thread-pool, and I'd like to understand how much memory I can save by creating a pool of 5 threads, compared to 20 manually created threads)
|
I have a server application which is heavy in thread usage, it uses a configurable thread pool which is set up by the customer, and in at least one site it has 1000+ threads, and when started up it uses only 50 MB. The reason is that Windows reserves 1MB for the stack (it maps its address space), but it is not necessarily allocated in the physical memory, only a smaller part of it. If the stack grows more than that a page fault is generated and more physical memory is allocated. I don't know what the initial allocation is, but I would assume it's equal to the page granularity of the system (usually 64 KB). Of course, the thread would also use a little more memory for other things when created (TLS, TSS, etc), but my guess for the total would be about 200 KB. And bear in mind that any memory that is not frequently used would be unloaded by the virtual memory manager.
|
256,220
| 256,262
|
Register allocation rules in code generated by major C/C++ compilers
|
I remember some rules from a time ago (pre-32bit Intel processors), when was quite frequent (at least for me) having to analyze the assembly output generated by C/C++ compilers (in my case, Borland/Turbo at that time) to find performance bottlenecks, and to safely mix assembly routines with C/C++ code. Things like using the SI register for the this pointer, AX being used for return values, which registers should be preserved when an assembly routine returns, etc.
Now I was wondering if there's some reference for the more popular C/C++ compilers (Visual C++, GCC, Intel...) and processors (Intel, ARM, ...), and if not, where to find the pieces to create one. Ideas?
|
You are asking about "application binary interface" (ABI) and calling conventions. These are typically set by operating systems and libraries, and enforced by compilers and linkers. Google for "ABI" or "calling convention." Some starting points from Wikipedia and Debian for ARM.
|
256,297
| 256,305
|
Best way to represent a 2-D array in C++ with size determined at run time
|
In C++ I'd like to do something like:
int n = get_int_from_user();
char* matrix = new char[n][n];
matrix[0][0] = 'c';
//...
matrix[n][n] = 'a';
delete [][] matrix;
but of course this doesn't work. What is the best way to do something similar? I've seen some solutions to this but they seem pretty messy.
|
The manual dynamic way:
Let's say you want an array of width*height, the most efficient way is to just use a single dimensional array:
char *matrix = new char[width*height];
To delete it:
delete[] matrix;
To access it:
char getArrayValue(char *matrix, int row, int col)
{
return matrix[row + col*width];
}
To modify it:
void setArrayValue(char *matrix, int row, int col, char val)
{
matrix[row + col*width] = val;
}
Boost Matrix:
Consider using boost::matrix if you can have the dependency.
You could then tie into the boost linear algebra libraries.
Here is some sample code of boost::matrix:
#include <boost/numeric/ublas/matrix.hpp>
using namespace boost::numeric::ublas;
matrix<char> m (3, 3);
for (unsigned i = 0; i < m.size1 (); ++ i)
for (unsigned j = 0; j < m.size2 (); ++ j)
m (i, j) = 3 * i + j;
On the stack for some compilers:
Some compilers actually allow you to create arrays on the stack with runtime determined sizes. g++ is an example of such a compiler. You cannot do this by default VC++ though.
So in g++ this is valid code:
int width = 10;
int height = 10;
int matrix[width][height];
Drew Hall mentioned that this C99 feature is called Variable Length Arrays (VLAs) and it can probably be turned on in any modern compiler.
|
256,557
| 257,326
|
Approaching STL algorithms, lambda, local classes and other approaches
|
One of the things that seems to be necessary with use of STL is a way to specify local functions.
Many of the functions that I would normally provide cannot be created using STL function object creation tools ( eg bind ), I have to hand roll my function object.
Since the C++ standard forbids local types to be used as arguments in template instantiations the best I was able to use was to create a small library, ( just showing relevant parts )
// library header
class MyFunctionBase<R,T>
{
public:
virtual ~MyFunctionBase();
virtual R operator()(const T &) const=0;
};
class MyFunction<R,T>
{
MyFunctionBase<R,T> *b;
public:
~MyFunction()
{
delete b;
}
virtual R operator()(const T &) const
{
return (*b)(T);
}
};
// source file
....
class func: public MyFunctionBase ...
std::stl_alg(.... MyFunction(new funct));
This has always seemed unwieldly to me. I guess to the people on the ISO committee believe so too and added a lambda to C++.
In the meantime how have compilers addressed this problem? ( Especially Windows compilers. )
A correction which might clarify a bit.
Changelog:
Nov 2
replaced to clarify
Since the C++ standard forbids local classes as function objects
|
Boost.Bind, Boost.Function, and Boost.Lambda are your friends.
|
256,719
| 256,777
|
How to programmatically activate the menu in Windows mobile
|
In most versions of windows, you can get to the menu by pressing the F10 key, thus avoiding having to use the mouse. This behaviour does not appear to be present in Windows Mobile 5.0, but is desirable as the device I am using will be more keyboard than touch screen driven.
Is there a way of programmatically activating and using the menu on Windows Mobile 5.0, under C++ using either MFC or Windows API calls. I have tried setting the focus of the CFrameWnd and CCeCommandBar classes to no avail.
|
After a number of attempts, the following appears to work;
void CMyFrame::OnFocusMenu()
{
PostMessage(WM_SYSCOMMAND,SC_KEYMENU,0);
}
FWIW, none of the following did, where m_wndCommandBar is the CCeCommandBar toolbar containing the menu;
::SetActiveWindow(m_wndCommandBar.m_hWnd);
m_wndCommandBar.PostMessage(WM_ACTIVATE,WA_ACTIVE,0);
m_wndCommandBar.PostMessage(WM_LBUTTONDOWN,0,0);
m_wndCommandBar.PostMessage(WM_LBUTTONUP,0,0);
m_wndCommandBar.OnActivate(WA_ACTIVE, NULL, FALSE);
m_wndCommandBar.SetFocus();
|
256,724
| 256,744
|
In C++, is it safe to extend scope via a reference?
|
In C++, is it safe to extend scope via a reference?
In code, what I mean is:
MyCLass& function badIdea()
{
MyClass obj1;
...
return obj1;
}
|
It is NOT safe to extend the scope via reference. Objects in C++ are not reference counted when obj1 goes out of scope it will be deleted, refering to the result of badIdea() will only get you into trouble
|
256,807
| 256,825
|
Check if array index exists
|
Is there any way to check if a given index of an array exists?
I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter.
I normally work with php but I am trying to do this in c++, so basically I am trying to ask if there is an isset() way to use with c++
PS: Would this be easier with vectors? If so, can anyone point me to a good vector tutorial? Thanks
|
In C++, the size of an array is fixed when it is declared, and while you can access off the end of the declared array size, this is very dangerous and the source of hard-to-track-down bugs:
int i[10];
i[10] = 2; // Legal but very dangerous! Writing on memory you don't know about
It seems that you want array-like behavior, but without all elements being filled. Traditionally, this is in the realms of hash-tables. Vectors are not such a good solution here as you will have empty elements taking up space, much better is something like a map, where you can test if an element exists by searching for it and interpreting the result:
#include <map>
#include <string>
// Declare the map - integer keys, string values
std::map<int, std::string> a;
// Add an item at an arbitrary location
a[2] = std::string("A string");
// Find a key that isn't present
if(a.find(1) == a.end())
{
// This code will be run in this example
std::cout << "Not found" << std::endl;
}
else
{
std::cout << "Found" << std::endl;
}
One word of warning: Use the above method to find if a key exists, rather than something like testing for a default value
if(a[2] == 0)
{
a[2] = myValueToPutIn;
}
as the behavior of a map is to insert a default constructed object on the first access of that key value, if nothing is currently present.
|
257,030
| 257,064
|
How do I create an nullary Functor in C++ (using the loki library)
|
Writing something like this using the loki library,
typedef Functor<void> BitButtonPushHandler;
throws a compiler error, but this works
typedef Functor<void,TYPELIST_1(Matrix3D*)> Perspective;
Functor.h:530: error: '((Loki::FunctorHandler, int>*)this)->Loki::FunctorHandler, int>::f_' cannot be used as a function
Functor.h:530: error: return-statement with a value, in function returning 'void'
Anyone familiar with this library know how to get the first line working?
|
Looking at the source code, the Functor template definition is as follows:
template <typename R = void, class TList = NullType,
template<class, class> class ThreadingModel = LOKI_DEFAULT_THREADING_NO_OBJ_LEVEL>
class Functor{...};
As commented below, there are no template typedefs allowed, so all types (or accept all defaults) need to be specified.
You can just define as follows and let the defaults do the work:
typedef Functor<> BitButtonPushHandler;
This compiles for me with a small test Functor class (not the actual Loki one), and I can use the typedef successfully.
|
257,091
| 257,098
|
How do I flush the cin buffer?
|
How do I clear the cin buffer in C++?
|
Possibly:
std::cin.ignore(INT_MAX);
This would read in and ignore everything until EOF. (you can also supply a second argument which is the character to read until (ex: '\n' to ignore a single line).
Also: You probably want to do a: std::cin.clear(); before this too to reset the stream state.
|
257,134
| 257,197
|
Weird compile error dealing with Winnt.h
|
When trying to compile a file that include winnt.h via windows.h, I get the following error:
MyGl.cpp
..\microsoft sdks\windows\v6.0a\include\winnt.h(964) : error C2988: unrecognizable template declaration/definition
..\microsoft sdks\windows\v6.0a\include\winnt.h(964) : error C2059: syntax error : '&'
They point to the following lines in Winnt.h
extern "C++" // templates cannot be declared to have 'C' linkage
template <typename T, size_t N>
char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N];
#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A)))
Any ideas for what's going on?
My compiler:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
|
There are at least two ways to do this. The first is to simply include windows.h at the top of all your files. Then include winnt.h only if you need it. However, I find this a bit too much - I don't see the need of including all this goo in every single file.
What I do is this at the very top (first thing) in my C/C++ header files.
#ifndef __wtypes_h__
#include <wtypes.h>
#endif
#ifndef __WINDEF_
#include <windef.h>
#endif
This will get you you the data types, defines, and fundamental Windows API's. You may also need to add the following:
#ifndef _WINUSER_
#include <winuser.h>
#endif
#ifndef __RPC_H__
#include <rpc.h>
#endif
WinNT is a bit of a special animal - don't include it if including the above files works for you. If you do need it, include it after wtypes.h and `windef.h'
If this doesn't work, then check your include paths and predefined macros to see if those might be breaking your build.
Regards, Foredecker
|
257,259
| 257,264
|
New approach for adding a new Node to a Linked List
|
void addNewNode (struct node *head, int n)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp -> data = n;
temp -> link = head;
head = temp;
}
The code give above is the popularly wrong version of a function for adding a new node at the head of a linked list.
Generally the correct versions are like,
void addNewNode (struct node **head, int n);
void addNewNode (struct node * &head, int n);
I worked out another but simple function for the purpose which worked fine.
struct node* addNewNode (struct node *head, int n)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp -> data = n;
temp -> link = head;
return temp;
}
But I haven't seen this being used or discussed in code and tutorials and thus I am curious to know if this approach has some flaw.
|
The flaw is that you're relying on the caller to perform the last step of updating the head pointer to the list.
If the caller neglects to do this, the compiler will not complain, and for all intents and purposes the list will appear to not have changed (and you'll have leaked the memory for a node).
|
257,275
| 257,305
|
No SDL Keypress events being detected
|
I am completely stumped as to why this code does not get any SDL keypress events. The other SDL events (removed for clarity) work fine. It does not work on my XP or Vista machines. No compile/link errors, just never recieve a keydown event.
#include "SDL/SDL.h"
// Yes SDL.lib and SDLmain.lib are linked
Uint32 TimeLeft(void)
{
static Uint32 next_time = 0;
Uint32 now;
now = SDL_GetTicks();
if ( next_time <= now ) {
next_time = now + tickInterval;
return 0;
}
return(next_time-now);
}
int main( int argc, char **argv )
{
if( -1 == SDL_Init( SDL_INIT_EVERYTHING ) )
{
cerr << "Error: SDL_Init failed" << endl;
return -1;
}
SDL_Event event;
bool quit = false;
while( !quit )
{
while( SDL_PollEvent( &event ) )
{
switch( event.type )
{
case SDL_KEYDOWN:
switch( event.key.keysym.sym )
{
case SDLK_ESCAPE:
case SDLK_q:
quit = true;
break;
default:
break;
}
break;
case SDL_JOYAXISMOTION:
// stuff removed
break;
case SDL_QUIT:
quit = true;
break;
default:
break;
}
}
SDL_Delay( TimeLeft() );
}
SDL_Quit();
return 0;
}
|
You'll need to create a window with SDL_SetVideoMode to get mouse and keyboard events.
I don't think you'll have luck trying to SDL_WM_GrabInput the mouse and keyboard without a window. It may also raise security alerts the first time on moderm Windows machines.
|
257,288
| 257,382
|
Templated check for the existence of a class member function?
|
Is it possible to write a template that changes behavior depending on if a certain member function is defined on a class?
Here's a simple example of what I would want to write:
template<class T>
std::string optionalToString(T* obj)
{
if (FUNCTION_EXISTS(T->toString))
return obj->toString();
else
return "toString not defined";
}
So, if class T has toString() defined, then it uses it; otherwise, it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.
|
Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code:
#include <iostream>
struct Hello
{
int helloworld() { return 0; }
};
struct Generic {};
// SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
struct two { char x[2]; };
template <typename C> static one test( decltype(&C::helloworld) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
int main(int argc, char *argv[])
{
std::cout << has_helloworld<Hello>::value << std::endl;
std::cout << has_helloworld<Generic>::value << std::endl;
return 0;
}
I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.
|
257,353
| 257,359
|
What's bigger than a double?
|
Is there a native c++ variable type that's "bigger" than a double?
float is 7
double is 15 (of course depending on the compiler)
Is there anything bigger that's native, or even non-native?
|
C++ has long double, but there is no guarantee that it's any more precise than a plain double. On an x86 platform, usually double is 64 bits, and long double is either 64 or 80 bits (which gives you 19 significant figures, if I remember right).
Your mileage may vary, especially if you're not on x86.
|
257,797
| 257,799
|
How to use sgi hash_table in VS2005?
|
I wrote a C++ project in VS2005, and used lots of STL container with its plus-in STL. However, I found STL in VS2005 does not have a hash_map in it, I want to use SGI hash_map. How can I change my project to use SGI STL?
Thanks for Brian's method, it works! And it's simple.
|
VS2005 does have a hash_map:
#include <hash_map>
stdext::hash_map
If you still want to though you can download the sgi stl here. You should be able to just set the include directory to the sgi location. It will take precedence over the VC++ global include directories.
|
258,050
| 258,052
|
How do you convert CString and std::string std::wstring to each other?
|
CString is quite handy, while std::string is more compatible with STL container. I am using hash_map. However, hash_map does not support CStrings as keys, so I want to convert the CString into a std::string.
Writing a CString hash function seems to take a lot of time.
CString -----> std::string
How can I do this?
std::string -----> CString:
inline CString toCString(std::string const& str)
{
return CString(str.c_str());
}
Am I right?
EDIT:
Here are more questions:
How can I convert from wstring to CString and vice versa?
// wstring -> CString
std::wstring src;
CString result(src.c_str());
// CString -> wstring
CString src;
std::wstring des(src.GetString());
Is there any problem with this?
Additionally, how can I convert from std::wstring to std::string and vice versa?
|
According to CodeGuru:
CString to std::string:
CString cs("Hello");
std::string s((LPCTSTR)cs);
BUT: std::string cannot always construct from a LPCTSTR. i.e. the code will fail for UNICODE builds.
As std::string can construct only from LPSTR / LPCSTR, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary.
CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
std::string to CString: (From Visual Studio's CString FAQs...)
std::string s("Hello");
CString cs(s.c_str());
CStringT can construct from both character or wide-character strings. i.e. It can convert from char* (i.e. LPSTR) or from wchar_t* (LPWSTR).
In other words, char-specialization (of CStringT) i.e. CStringA, wchar_t-specilization CStringW, and TCHAR-specialization CString can be constructed from either char or wide-character, null terminated (null-termination is very important here) string sources.
Althoug IInspectable amends the "null-termination" part in the comments:
NUL-termination is not required.
CStringT has conversion constructors that take an explicit length argument. This also means that you can construct CStringT objects from std::string objects with embedded NUL characters.
|
258,425
| 258,453
|
Building and running C++ unit tests in Visual Studio (TDD)
|
I have a large project for which I am attempting to use TDD.
I am using Tut as my test framework, which has its flaws but is sufficient for what I need.
I need to exploit link time test seams, each test must be in its own executable. The project for this executable then launches itself as a post build step.
Unfortunately, this means that my Visual Studio Sln is filling up with tests, which is not scalable and also hides the actual important projects.
Does anyone know of a better way of running these tests?
Is it possible to hide projects from a build and yet still have them build?
|
"Is it possible to hide projects from a build and yet still have them build?"
You can make separate solution for test cases.
Then you can set up post build step of your main projects. This post-build should build tests-projects via separate solution and run them. Building test-projects should be done via command line (see e.g. here for details).
If you need to link your unit tests with some lib-s from main projects, you can use
#pragma comment(lib, "libname")
See this MSDN page for details.
|
258,438
| 258,467
|
Why can't I find a Control ID in my Resource file in ATL?
|
Since I need to do some checks depending on which control is on focus in my app, I am getting the focused control ID like this:
HWND controlOnFocus = ::GetFocus();
int controlID = ::GetDlgCtrlID(controlOnFocus);
I am getting consistent IDs, but I can't find them in the resource file!
Can I rely on the IDs I am getting or what?
Any help would be highly appreciated.
|
Your snippet of code gets the control identifier from whichever window has the current focus. Your application is likely to include lots of windows that you haven't created yourself, such as common dialogue boxes, and the IDs for those won't be in your resource file. Also, not all windows have useful control IDs; For instance, static text controls usually have ID_STATIC (-1?).
|
258,871
| 258,913
|
How to use find algorithm with a vector of pointers to objects in c++?
|
I want to find in a vector of Object pointers for a matching object. Here's a sample code to illustrate my problem:
class A {
public:
A(string a):_a(a) {}
bool operator==(const A& p) {
return p._a == _a;
}
private:
string _a;
};
vector<A*> va;
va.push_back(new A("one"));
va.push_back(new A("two"));
va.push_back(new A("three"));
find(va.begin(), va.end(), new A("two"));
I want to find the second item pushed into the vector. But since vector is defined as a pointers collection, C++ does not use my overloaded operator, but uses implicit pointer comparison. What is the preferred C++-way of solutiono in this situation?
|
Use find_if with a functor:
template <typename T>
struct pointer_values_equal
{
const T* to_find;
bool operator()(const T* other) const
{
return *to_find == *other;
}
};
// usage:
void test(const vector<A*>& va)
{
A* to_find = new A("two");
pointer_values_equal<A> eq = { to_find };
find_if(va.begin(), va.end(), eq);
// don't forget to delete A!
}
Note: your operator== for A ought to be const, or, better still, write it as a non-member friend function.
|
259,166
| 259,864
|
Good free FTP Client Library (for Windows C++ commercial apps)?
|
I'm looking for a good open source Windows FTP client library with a public domain or BSD-type license. Something that I have access to the source code and I can use it from C++ for Windows applications in a commercial app.
We have used Wininet for years and it's buggy and horrible. The last straw is the IE8 beta 2 contains a new bug in InternetGetLastResponseInfo(). I can no longer justify using Wininet when our users can install the latest version of IE and break our app.
I have looked at libcurl but it is way too heavy for our needs. The only thing I need is FTP support. I could spend a day stripping out all the code in libcurl I don't need, but I'd rather just start with a nice simple FTP client library, if possible.
I looked at ftplib (http://nbpfaus.net/~pfau/ftplib/) but it's GPL and I need this for a closed-source commercial app.
I've written FTP client code before, it's not that hard (unfortunately it was 15 years ago and I don't have the source code anymore). There must be a nice simple free client library that does nothing but FTP and has a license that can be used in closed-source commercial apps.
(If you are curious, the bug is that if you attempt to FtpFindFirstFile() with an FTP site where you can't make a passive-mode connection, InternetGetLastResponseInfo() doesn't return the full response. This is just one of many bugs I've found over the years. Another is that Wininet's FTP support ignores all timeout values. That particular bug has existed for years.)
|
You need Ultimate TCP/IP which is now free!
http://www.codeproject.com/KB/MFC/UltimateTCPIP.aspx
You get FTP. HTTP, SMTP, POP and more.
You won't regret it.
|
259,240
| 259,377
|
iterator adapter to iterate just the values in a map?
|
I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C.
One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this facility with its Keys and Values properties of its Dictionary class. Objective-C's NSDictionary, similarly, has allKeys and allValues.
Since I've been "away", Boost has acquired the Range and ForEach libraries, which I am now using extensively. I wondered if between the two there was some facility to do the same, but I haven't been able to find anything.
I'm thinking of knocking something up using Boost's iterator adapters, but before I go down that route I thought I'd ask here if anyone knows of such a facility in Boost, or somewhere else ready made?
|
I don't think there's anything out of the box. You can use boost::make_transform.
template<typename T1, typename T2> T2& take_second(const std::pair<T1, T2> &a_pair)
{
return a_pair.second;
}
void run_map_value()
{
map<int,string> a_map;
a_map[0] = "zero";
a_map[1] = "one";
a_map[2] = "two";
copy( boost::make_transform_iterator(a_map.begin(), take_second<int, string>),
boost::make_transform_iterator(a_map.end(), take_second<int, string>),
ostream_iterator<string>(cout, "\n")
);
}
|
259,248
| 259,279
|
How to test the current version of GCC at compile time?
|
I would like to include a different file depending on the version of GCC. More precisely I want to write:
#if GCC_VERSION >= 4.2
# include <unordered_map>
# define EXT std
#elif GCC_VERSION >= 4
# include <tr1/unordered_map>
# define EXT std
#else
# include <ext/hash_map>
# define unordered_map __gnu_cxx::hash_map
# define EXT __gnu_cxx
#endif
I don't care about gcc before 3.2.
I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.
|
Ok, after more searches, it one possible way of doing it is using __GNUC_PREREQ defined in features.h.
#ifdef __GNUC__
# include <features.h>
# if __GNUC_PREREQ(4,0)
// If gcc_version >= 4.0
# elif __GNUC_PREREQ(3,2)
// If gcc_version >= 3.2
# else
// Else
# endif
#else
// If not gcc
#endif
|
259,269
| 259,286
|
std::getline() returns
|
I have a loop that reads each line in a file using getline():
istream is;
string line;
while (!getline(is, line).eof())
{
// ...
}
I noticed that calling getline() like this also seems to work:
while (getline(is, line))
What's going on here? getline() returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?
|
The istream returned by getline() is having its operator void*() method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to eof().
|
259,297
| 259,379
|
How do you copy the contents of an array to a std::vector in C++ without looping?
|
I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a std::vector. I don't want to have to do the standard loop to push_back all the values individually, it would be nice if I could just copy it all using something similar to memcpy.
|
If you can construct the vector after you've gotten the array and array size, you can just say:
std::vector<ValueType> vec(a, a + n);
...assuming a is your array and n is the number of elements it contains. Otherwise, std::copy() w/resize() will do the trick.
I'd stay away from memcpy() unless you can be sure that the values are plain-old data (POD) types.
Also, worth noting that none of these really avoids the for loop--it's just a question of whether you have to see it in your code or not. O(n) runtime performance is unavoidable for copying the values.
Finally, note that C-style arrays are perfectly valid containers for most STL algorithms--the raw pointer is equivalent to begin(), and (ptr + n) is equivalent to end().
|
259,853
| 259,946
|
What's the best signature for clone() in C++?
|
As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared:
class Base
{
virtual Base* clone() const = 0;
};
class Derived : public Base
{
virtual Derived* clone() const
};
The compiler detects that clone() returns an pointer to the type of the object, and allows Derived to override it to return a pointer to derived.
It would desirable to have clone() return a smart pointer that implies transfer of ownership semantics, like the following:
class Base
{
virtual std::auto_ptr<Base> clone() const = 0;
};
class Derived : public Base
{
virtual std::auto_ptr<Derived> clone() const;
};
Unfortunately, the relaxation of the conventions does not apply to templated smart pointers, and the compiler will not allow the override.
So, it seems I am left with two options:
Have clone() return a "dumb" pointer, and document that clients are responsible for disposing of it.
Have clone() return a smart base pointer, and have clients use dynamic_cast to save them to a Derived pointer if they need it.
Is one of these approaches preferred? Or is there a way for me to eat my transfer of ownership semantics and have my strong type safety too?
|
It depends on your use case. If you ever think you will need to call clone on a derived object whose dynamic type you know (remember, the whole point of clone is to allow copying without knowing the dynamic type), then you should probably return a dumb pointer and load that into a smart pointer in the calling code. If not, then you only need to return a smart_ptr and so you can feel free to return it in all overrides.
|
259,890
| 261,776
|
OpenGL glDrawPixels on dynamic 3D arrays
|
How do you draw the following dynamic 3D array with OpenGL glDrawPixels()?
You can find the documentation here: http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html
float ***array3d;
void InitScreenArray()
{
int i, j;
int screenX = scene.camera.vres;
int screenY = scene.camera.hres;
array3d = (float ***)malloc(sizeof(float **) * screenX);
for (i = 0 ; i < screenX; i++) {
array3d[i] = (float **)malloc(sizeof(float *) * screenY);
for (j = 0; j < screenY; j++)
array3d[i][j] = (float *)malloc(sizeof(float) * /*Z_SIZE*/ 3);
}
}
I can use only the following header files:
#include <math.h>
#include <stdlib.h>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
|
Uh ... Since you're allocating each single pixel with a separate malloc(), you will have to draw each pixel with a separate call to glDrawPixels(), too. This is (obviously) insane; the idea of bitmapped graphics is that the pixels are stored in an adjacent, compact, format, so that it is quick and fast (O(1)) to move from one pixel to another. This looks very confused to me.
A more sensible approach would be to allocate the "3D array" (which is often referred to as a 2D array of pixels, where each pixel happens to consist of a red, green and blue component) with a single call to malloc(), like so (in C):
float *array3d;
array3d = malloc(scene.camera.hres * scene.camera.vres * 3 * sizeof *array3d);
|
260,040
| 269,817
|
How to make the group-box text background transparent
|
I want to make a transparent dialog. I capture the OnCtlColor message in a CDialog derived class...this is the code:
HBRUSH CMyDialog::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if(bSetBkTransparent_)
{
pDC->SetBkMode(TRANSPARENT);
hbr = (HBRUSH)GetStockObject(NULL_BRUSH);
}
return hbr;
}
It works fine for all the controls but the group-box (CStatic). All the labels (CStatic) are been painted with a transparent text background but the text of the group box it is not transparent.
I already googled for this but I didn't find a solutions. Does anybody know how to make a real transparent group-box?
By the way, I am working in Windows XP. And I don't want to fully draw the control to avoid having to change the code if the application is migrated to another OS.
Thanks,
Javier
Note: I finally changed the dialog so that I don't need to make it transparent. Anyway, I add this information because maybe someone is still trying to do it. The groupbox isn't a CStatic but a CButton (I know this is not new). I changed the Windows XP theme to Windows classic and then the groupbox backgraund was transparent. The bad new is that in this case the frame line gets visible beneath the text...so if someone is following this approach I think maybe he/she would better follow the Adzm's advice.
|
You have two options.
You can not use Common Controls v6 (the XP-Styled controls), which will make your app lose the fanciness of newer windows versions. However IIRC the groupbox will respect the CTLCOLOR issue. If you are not using that anyway, and it is still not respecting your color, then you only have one option...
Which is to draw it yourself. I know you said you don't want to, but sometimes you have to. Thankfully a group box is a very simple control to draw. This page has an example for drawing a classic-style group box: http://www.codeguru.com/cpp/controls/controls/groupbox/article.php/c2273/ You can also draw it very simply using the UxTheme libraries that come with XP+.
If the application will be migrated to another OS, you will have plenty to deal with migrating over an MFC application in general. If that is your goal, then you should really look into developing with a cross-platform UI toolkit.
|
260,125
| 260,138
|
How to use wide string literals in c++ without putting L in front of each one
|
You'll have to forgive my ignorance, but I'm not used to using wide character sets in c++, but is there a way that I can use wide string literals in c++ without putting an L in front of each literal?
If so, how?
|
No, there isn't. You have to use the L prefix (or a macro such as _T() with VC++ that expands to L anyway when compiled for Unicode).
|
260,169
| 260,181
|
Where to find a quick review of Java and/or C++?
|
I have a short preliminary interview with Microsoft in less than 2 hours.
I've been told that they might ask questions in Java and/or C++.
Where can I find a quick overview of both languages?
I don't need to full tutorial, just something that goes over the language-specific features and a refresher of the semantics.
I also only have 1.5 hours to study so...
Any ideas?
Thx!
|
Teach yourself programming in ... 80 minutes?
I would bet on the quick reference cards:
C ref card,
A Java ref card,
A C++ ref card,
Google for reference cards.
Good luck!
|
260,254
| 260,262
|
Encode URLs into safe filename string
|
I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web. As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename.
Is there a simple way to do this without re-writing the function myself? I searched around for a simple library, but couldn't find anything. Surely this is a common problem.
|
A simpler approach is to replace everything which is not a character or a number with an underscore.
EDIT: Here's a naive implementation in C:
#include <cctype>
char *safe_url(const char *str) {
char *safe = strdup(str);
for (int i = 0; i < strlen(str); i++) {
if (isalpha(str[i]))
safe[i] = str[i];
else
safe[i] = '_';
}
}
|
260,380
| 260,412
|
Are non-pure virtual functions with parameters bad practice?
|
I have a base class with an optional virtual function
class Base {
virtual void OnlyImplementThisSometimes(int x) {}
};
When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this:
class Base {
virtual void OnlyImplementThisSometimes(int x)
{
x = 0;
}
};
I also have the problem that if I'm not careful, the subclass I make can implement the wrong function and then I don't notice because of overloading: e.g.
class Derived : public Base {
void OnlyImplementThisSometimes(int x, int y) { // some code }
};
Derived d;
Base *b = dynamic_cast<Base *>(&d);
b->OnlyImplementThisSometimes(x); // calls the method in the base class
The base class method was called because I implemented the derived function with an "int y" param but there is no warning about this. Are these just common pitfalls in C++ or have I misunderstood virtual functions?
|
Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example:
virtual void OnlyImplementThisSometimes(int ) { }
Mistakenly implementing the wrong method signature when trying to override the virtual function is just something you need to be careful about in C++. Languages like C# get around this with the 'override' keyword.
|
260,464
| 260,496
|
Debugging a memory error with GDB and C++
|
I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:
warning: HEAP[test.exe]:
warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1
How can I track down where this is happening at? Viewing the memory doesn't give me any clues.
Thanks!
|
So you're busting your heap. Here's a nice GDB tutorial to keep in mind.
My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way.
Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).
|
261,152
| 263,923
|
Looking for a script to colorize C++ code
|
Does anyone know of a script to colorize C++ code the same as the default MSVC IDE does?
|
Try the open source project Highlight.
It's not a script-per-se -- but it is scriptable. The nice thing is that it parses code and the style-sheet is very easy to customize colors, bold and italics, etc....
|
261,336
| 261,352
|
Is it wrong to use auto_ptr with new char[n]
|
If I declare a temporary auto deleted character buffer using
std::auto_ptr<char> buffer(new char[n]);
then the buffer is automatically deleted when the buffer goes out of scope. I would assume that the buffer is deleted using delete.
However the buffer was created using new[], and so strictly speaking the buffer should be deleted using delete[].
What possibility is there that this mismatch might cause a memory leak?
|
The behaviour of calling delete on a pointer allocated with new[] is undefined. As you assumed, auto_ptr does call delete when the smart pointer goes out of scope. It's not just memory leaks you have to worry about -- crashes and other odd behaviours are possible.
If you don't need to transfer the ownership of the pointer, Boost's scoped_array class might be what you're looking for.
|
261,357
| 261,365
|
COM, VARIANT containing BSTR. Who allocates?
|
OK, so I couldn't really think of an apropos title that summarizes this.
The IPrintPipelinePropertyBag interface has the method AddProperty which aptly enough "adds a property to a property bag."
http://msdn.microsoft.com/en-us/library/aa506384.aspx
AddProperty( [in, string] const
wchar_t *pszName, [in] const
VARIANT *pVar );
We use the following code to add a string to the property bag.
CComVariant varProperty = CComBSTR(someString);
pPrintPropertyBag->AddProperty(L"SOME_PROPERTY", &varFilename);
It's pretty obvious, though, that the CComBSTR and CComVariant that is created goes out of scope after a while. I'm not sure if the PropertyBag handles the string and makes its own copy. Since we can store all kinds of stuff inside a VARIANT, this shouldn't be the case.
Assuming the string isn't handled, my question is, what is the pattern for doing this in COM? How should I pass a VARIANT that contains an allocated string, make that string available for other threads even if the thread that called AddProperty died first, and de-allocate the string properly?
|
When you call a COM function with strings or VARIANTs in most cases the only garantuee needed is that those objects are available throughout the call itself. After the call, the object itself is responsible for making copies of the data. For example VARIANT's will most likely use the VariantCopy function that will copy strings, copy COM objects (increases reference count).
The only thing you should worry about is when you pass an actual interface in the VARIANT: in that case the interface should be properly reference counted, and QueryInterface, AddRef, and Release should all be implemented accordingly. And don't ever deallocate that object before the reference count reaches 0 ;)
EDIT: Oh, and if you want to learn more about COM programming, be sure to get "Essential COM" by "Don Box". Don Box is the COM guru, and that book will teach you almost anything you would ever want to know about COM and more ;)
|
261,377
| 399,288
|
LNK2001 error when compiling apps referencing STLport-5.1.4 with VC++ 2008
|
I apologize in advance for the long post...
I used to be able to build our VC++ solutions (we're on VS 2008) when we listed the STLPort include and library directories under VS Menu > Tools > Options > VC++ Directories > Directories for Include and Library files. However, we wanted to transition to a build process that totally relies on .vcproj and .sln files. These can be checked into source control unlike VS Options which have to be configured on each development PC separately. We handled the transition for most libraries by adding the Include directories to each Project's Property Pages > Configuration Properties > C/C++ > General > Additional Include Directories, and Library directories to Linker > General > Additional Library Directories.
Unfortunately, this approach doesn't work for STLPort. We get LNK2019 and LNK2001 errors during linking:
Error 1 error LNK2019: unresolved external symbol "public: virtual bool __thiscall MyClass::myFunction(class stlp_std::basic_istream<char,class stlp_std::char_traits<char> > &,class MyOtherClass &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > &)const " (?myFunction@MyClass@@UBE_NAAV?$basic_istream@DV?$char_traits@D@stlp_std@@@stlp_std@@AAVSbprobScenarioData@@AAV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@3@@Z) referenced in function _main MyLibrary.obj
Error 5 error LNK2001: unresolved external symbol "public: static void __cdecl MyClass::myFunction(class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &,long,enum MyClass::MessageType,int,class stlp_std::basic_string<char,class stlp_std::char_traits<char>,class stlp_std::allocator<char> > const &)" (?myFunction@MyClass@@SAXABV?$basic_string@DV?$char_traits@D@stlp_std@@V?$allocator@D@2@@stlp_std@@000JW4MessageType@1@H0@Z) MyLibrary.lib
This happens while linking and executable project to dependencies which are library projects. Curiously, this does not happen while linking the library projects themselves. Any ideas?
|
Raymond Chen recently talked about this at The Old New Thing-- one cause of these problems is that the library was compiled with one set of switches, but your app is using a different set. What you have to do is:
Get the exact symbol that the linker is looking for. It will be a horrible mangled name.
Use a hex editor (IIRC, Visual Studio will do this) to look at the .lib file you're linking to.
Find the symbol that's almost the thing the linker is looking for, but not quite.
Given the differences in the symbols, try to figure out what command line switches will help.
Good luck -- for people who aren't used to this sort of problem, the solution can take days to figure out (!)
|
261,500
| 261,839
|
How to build Python C extension modules with autotools
|
Most of the documentation available for building Python extension modules
uses distutils, but I would like to achieve this by using the appropriate
python autoconf & automake macros instead.
I'd like to know if there is an open source project out there that does
exactly this. Most of the ones I've found end up relying on a setup.py file.
Using that approach works, but unfortunately ends up rebuilding the entire
source tree any time I make a modification to the module source files.
|
All PyGTK extensions use autotools, so if the PyGTK aspects don't kill the whole thing for you, it might be worth having a look at the PyGTK source code. Additionally, here is one I wrote which is more simple.
|
261,518
| 261,579
|
Reusing object files in Visual Studio 2005
|
Here's the situation:
I have one VS2005 solution with two projects: MyDll (DLL), MyDllUnitTest (console EXE).
In MyDll I have a class called MyClass which is internal to the DLL and should not be exported. I want to test it in MyDllUnitTest, so I added a test suite class called MyClassTest, where I create instances of MyClass and test them.
My question: how can I link the object file of MyClass, created by building MyDll, to the MyDllUnitTest EXE? I don't want to build MyClass in MyDllUnitTest and I don't want to export the class.
I tried using the same Intermediate Directory for both projects (so object files are in the same directory) and using the References feature of VS2005 (right click project --> References --> Add New Reference...), but it didn't work - I still get a linking error (LNK2001).
Edit: I don't want to have the same source file in two projects - consider the face that I have many MyClass/MyClassTest, which means I have to duplicate each MyClass to a different project.
I know it is possible to use the same object file in two projects, I've seen it done before but forgot how.
Edit: I've decided to put the files in both projects, so they are compiled twice. It turns out the "Reference" feature works automatically - but only for static lib projects.
|
I don't understand why you don't want to build it in your dll project. As long as both projects are using the same source file, they will both generate the same object file (assuming compiler options are set the same way).
If you want to test the dll without exporting the class itself (I presume this is because exporting classes in a dll is usually a bad idea), consider exporting a "factory" function from the dll. It would have a signature like:
extern "C" MyClass *CreateMyClass();
This function would create an object of MyClass and return a pointer to it. Your unit test can then do whatever it needs with the returned class object.
|
261,548
| 270,412
|
Share .obj files between different configurations
|
My goal is to integrate testing into my development environment (as post-build step). I don't want to interfere with the DLLs that are generated in debug and release, so i plan to create new configurations for the project. But i don't want to compile every source file i have twice - once for the DLL, once for the test unit - I want to share the generated object files. How can I achieve this ?
I am developping in c++ using Visual Studio 2005.
|
Compile the objs into a new lib project that is shared between the dll and your test project.
|
261,559
| 261,589
|
Higher color depth for MFC toolbar icons?
|
I was wondering how to make a toolbar in MFC that used 24bit or 256 colour bitmaps rather than the horrible 16 colour ones.
Can anyone point me in the direction of some simple code?
Thanks
|
The reason this happens is that the MFC CToolbar class uses an image list internally that is initialised to use 16 colours only. The solution is to create our own image list and tell the toolbar to use that instead. I know this will work for 256-colours, but I haven't tested it with higher bit-depths:
First, load a 256-colour bitmap from a resource:
HBITMAP hBitmap = (HBITMAP) ::LoadImage(AfxGetInstanceHandle(),
MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_BITMAP,
0,0, LR_CREATEDIBSECTION | LR_LOADMAP3DCOLORS);
CBitmap bm;
bm.Attach(hBitmap);
Next, create a 256-colour image list and add our bitmap to it:
CImageList m_imagelist.Create(20, 20, ILC_COLOR8, 4, 4);
m_imagelist.Add(&bm, (CBitmap*) NULL);
Finally, we need to tell the toolbar to use the new image list:
m_toolbar.GetToolBarCtrl().SetImageList(&m_imagelist);
It's also possible that the new MFC version in VS2008 may have solved this problem as I know that many of the UI elements have been updated. I haven't actually tried using it yet so I can't be certain.
|
261,591
| 493,374
|
Should I rewrite my DSP routines in C/C++ or I'm good with C# unsafe pointers?
|
I'm currently writing a C# application that does a lot of digital signal processing, which involves a lot of small fine-tuned memory xfer operations. I wrote these routines using unsafe pointers and they seem to perform much better than I first thought. However, I want the app to be as fast as possible.
Would I get any performance benefit from rewriting these routines in C or C++ or should I stick to unsafe pointers? I'd like to know what unsafe pointers brings to the table in terms of performance, compared to C/C++.
EDIT: I'm not doing anything special inside these routines, just the normal DSP stuff: cache friendly data transfers from one array to the other with a lot of multiplications, additions, bit shiftings etc. in the way. I'd expect the C/C++ routines to look pretty much the same (if not identical) as their C# counterparts.
EDIT: Thanks a lot to everyone for all the clever answers. What I've learned is that I won't get any significant boost in performance just by doing a direct port, unless some sort of SSE optimization takes place. Assuming that all modern C/C++ compilers can take advantage of it I'm looking forward to give it a try. If someone is interested in the results just let me know and I'll post them somewhere. (May take a while though).
|
I've actually done pretty much exactly what you're asking, only in an image processing area. I started off with C# unsafe pointers, then moved into C++/CLI and now I code everything in C++. And in fact, from there I changed from pointers in C++ to SSE processor instructions, so I've gone all the way. Haven't reached assembler yet, although I don't know if I need to, I saw an article on CodeProject that showed SSE can be as fast as inline assembler, I can find it if you want me to.
What happened as I went along was my algorithm went from around 1.5-2 frames per second in C# with unsafe pointers, to 40 frames per second now. C# and C++/CLI were definitely slower than C++, even with pointers, I haven't been able to get above 10 frames per second with those languages. As soon as I switched to C++, I got something like 15-20 frames per second instantly. A few more clever changes and SSE got me up to 40 frames per second. So yes, it is worth going down if you want speed in my experience. There is a clear performance gain.
|
261,629
| 261,653
|
How do I obtain File Version info from a C++ exe in C#?
|
I need to get the File version information from an exe file originally written in C++ from a C# program.
Using Assembly.LoadFile(fullpath).GetName().Version results in a BadImageFormatException.
Can anyone help?
Cheers,
Dan
|
Add a using System.Diagnostics, and then:
FileVersionInfo info = FileVersionInfo.GetVersionInfo(path);
Then look at the various properties of info:
Console.WriteLine(info.CompanyName);
Console.WriteLine(info.ProductName);
Console.WriteLine(info.LegalCopyright);
Console.WriteLine(info.ProductVersion);
etc
|
261,648
| 261,674
|
What's the best way to manage a lot of text in code (and also support translations)?
|
I'm developing an application which has a lot of text and also different modules which can be included or not in every build.
For each saved project we generate automatically a report with all the details (i.e. description of algorithms used in that project and so on). Currently we embed all text as strings in the source code and we also support different languages through po and mo files.
The good points of the system is that it is very easy to dynamically generate documentation and report files.
The bad point is that having a lot of text in source code is ugly and the formatting (i.e. with html) is not comfortable, editing of the text is difficult, no easy spell check and terrible to translate.
So, the final question is: whould you rather embed documentation in code or write external documentation files (for example html) for different languages and parse them on runtime? Obviously the core text of the software, such us message boxes will stay in code anyway.
If it matters, I'm working in C++ with wxWidgets.
|
I think all text which may change between different versions of the code should be kept in separate property files. You can build a mechanism which maps message ids to the proper string from a property file, say map id 15 to "search" or to "busca" in the English and Spanish property files respectively. So a property file may be an XML or a CSV with id-message pairs.
When running your program, you supply it with the property file(s) as parameters.
When it starts, it first loads the property strings into a map, and then you will use
property[15] instead of the string "search". Of course, you can use a textual label instead of a numerical id.
I would also consider generating the documentation from the property files automatically, maybe using CSS. This makes it a lot easier to edit and translate the messages.
|
261,958
| 261,972
|
(C++) Game Server, (Flash) Client
|
I'm interested in putting together my first online game using Flash as the client and writing a back-end application in C++ where the actual game state is kept.
I've done lots of games in C++ before using SDL, SFML, Allegro, etc etc but never gotten around to using the network libraries. I was just interested in some helpful direction for which libraries are best suited to game servers where the actual server doesn't have any graphical display (or doesn't need to but could have). In all honesty I think the answer will be any and once I get the hang of sockets it'll become a breeze sending data back and forth... but it can't help to ask first.
I have very little experience in flash or as3 but like the idea of being able to access the game through a browser - learning flash is obvisouly going to be an obstical that I'll have to overcome but my main interest again is any tips on libraries, or sources, or tutorials that are good for sending/recieving data via sockets or whichever method works best.
I've read about the arguments between TCP/UDP so I don't want to start a war like that here; just general helpful advice please - I'm only looking for something simple to get me up and running :-p
As a side note, the reason I'm choosing C++ is because the players are actually robots with minature virtual-machines and everything will run on the server so as the player count rises so will the need to emulate each and every vm :-p
Update:
The game world is intended to be real-time, but the interaction of the player doesn't have to be. The basis of the game is that you program little robots that interact in a persistent world and have goals and challenges to meet on a daily/weekly basis to earn points.
I was thinking that buffering the display data would be possible as the player doesn't need real-time visual as they have no direct control of their robots. The server would buffer up 10 seconds or so of data for each connection and then ship it out in one go - this way while the data is being played back in the client the server is busy buffering some more.
The general interactions the player will have with the server will be uploading new code and getting statistics, there may also be other one off commands to move your robot around or reset it to a starting position. Any remote control is done through a communications channel and thus is delayed by the buffer. This could easily be explained by the fact that the persistent world is somewhere like Mars (the planet) and the signal takes a while to go back and forth.
I was planning on having a "lab" whereby you could set up the robots and test them in realtime on the client, this has nothing to do with the actual game world and thus shouldn't require any networking - although I don't fancy writing a VM in both languages :(
I'm completely comfortable in C++ and have some working prototypes of the persistent world in place already - I'm just a complete newbie when it comes to networking so figured it'd be best to get advice first.
|
Although it's primarily written for C, it's still great for C++:
Beej's guide to networ programming.k
It covers all the basics, and has a section on changes needed for Win32 :)
Also I seem to recall that Flash needed terminating null-bytes on each packet, so instead of send(socket,szData,strlen(szData),0); use send(socket,szData,strlen(szData)+1,0); to send a string :)
|
261,963
| 261,986
|
How can I iterate over an enum?
|
I just noticed that you can not use standard math operators on an enum such as ++ or +=.
So what is the best way to iterate through all of the values in a C++ enum?
|
The typical way is as follows:
enum Foo {
One,
Two,
Three,
Last
};
for ( int fooInt = One; fooInt != Last; fooInt++ )
{
Foo foo = static_cast<Foo>(fooInt);
// ...
}
Please note, the enum Last is meant to be skipped by the iteration. Utilizing this "fake" Last enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum.
If you want to add more enums later, just add them before Last. The loop in this example will still work.
Of course, this breaks down if the enum values are specified:
enum Foo {
One = 1,
Two = 9,
Three = 4,
Last
};
This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.
switch ( foo )
{
case One:
// ..
break;
case Two: // intentional fall-through
case Three:
// ..
break;
case Four:
// ..
break;
default:
assert( ! "Invalid Foo enum value" );
break;
}
If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.
|
262,000
| 262,486
|
Best algorithm to check whether a vector is sorted
|
What would be the best way to check that a std::vector is sorted? Is there something faster than a loop checking that v[i]<=v[i+1]? Is it faster/cleaner with iterators? Or is it actually better to just call sort every time (though the "v is already sorted" case is quite common)?
We can safely assume the vector only contains PODs, usually floats and sometimes doubles and ints.
The size of the vector is non-trivial (usually a few thousands items) but not extreme (not gigabyte-sized).
in some instances we'll sort the vector immediately afterwards, however there are other instances where we don't (it's an error case of our algorithm).
we already use a flag "IsSorted" whenever possible.
|
Consider Multiple Cpu Cores
It depends on your platform and number of items in the vector. You'd have to benchmark to find what's best.
It's not possible to answer: Is there something faster than a loop checking that v[i]<=v[i+1] ?
With: No.
Because... computers now a days have multiple cpus/cores/hyperthreading. So, it may well be a lot quicker to exploit the parallism in the computer by spliting the work of checking to a number of threads, so each cpu can be checking a small range in parallel.
It's probably best to do this via a library function rather than implementing it yourself. New versions of libraries will exploit parallism. So, if you go for a std::sort you'll probably find when you build against newer implementations of STL, they'll do the operation in parallel for you without you having to worry about it. I don't know if there are readily available versions of STL that do this already, but it's worth sticking to the library functions so that when you upgrade to a version that does, this optimization is there for you without you needing to make any changes.
|
262,036
| 262,260
|
MFC: Capturing Resizes
|
Just wondering where is best to put functionality in an MFC application that is triggered when the whole window is resized. I was thinking mainfrm but I couldn't seem to capture any OnSize messages...
Can someone tell me what I am doing wrong?
|
Can someone tell me what I am doing wrong?
You didn't include any interesting details, so here are a few guesses (because of course the mainframe normally gets sent WM_SIZE messages...):
You didn't set up your message handler properly. Perhaps you forgot the message map entry?
You have an existing handler in place for WM_WINDOWPOSCHANGED that fails to call the default window procedure, thereby preventing WM_SIZE messages from being sent.
|
262,201
| 262,809
|
How can I write a C++ function returning true if a real number is exactly representable with a double?
|
How can I write a C++ function returning true if a real number is exactly representable with a double?
bool isRepresentable( const char* realNumber )
{
bool answer = false;
// what goes here?
return answer;
}
Simple tests:
assert( true==isRepresentable( "0.5" ) );
assert( false==isRepresentable( "0.1" ) );
|
Parse the number into the form a + N / (10^k), where a and N are integers, and k is the number of decimal places you have.
Example: 12.0345 -> 12 + 345 / 10^4, a = 12, N = 345, k = 4
Now, 10^k = (2 * 5) ^ k = 2^k * 5^k
You can represent your number as exact binary fraction if and only if you get rid of the 5^k term in the denominator.
The result would check (N mod 5^k) == 0
|
262,211
| 262,884
|
Are std::streams already movable?
|
GNU gcc 4.3 partially supports the upcoming c++0x standard: among the implemented features the rvalue reference. By means of the rvalue reference it should be possible to move a non-copyable object or return it from a function.
Are std::streams already movable by means of rvalue reference or does the current library implementation lack something?
|
In the current g++ svn, rvalue reference support has not yet been added to streams. I suspect adding it will not be too difficult and as ever with open source software, patches are, I'm sure, welcome!
|
262,232
| 262,667
|
Concurrent data structure design
|
I am trying to come up with the best data structure for use in a high throughput C++ server. The data structure will be used to store anything from a few to several million objects, and no sorting is required (though a unique sort key can be provided very cheaply).
The requirements are that it can support efficient insert, ideally O(1), moderately efficient removal, and efficient traversal. It doesn't need to support a find operation (other than might be needed for removal).
The twist is that it must be thread safe with respect to modifications while other threads are enumerating the data structure. This means that a simple red-black tree doesn't work, since one thread can't insert an element (and perform the necessary tree rotations) without messing up any cursors held by other threads.
It is not acceptable to use a read/write lock and defer the write operations until all readers have finished, since read operations may be long lived. It doesn't matter if inserts that happen while there is a reader are visible to that reader or not.
Memory footprint is also very important, and small is obviously better!
What suggestions are there?
Response to comments:
Thanks for the answers.
No, inserts cannot invalidate existing iterators. Iterators may or may not see the new insert, but they must see everything that they would have seen if the insert hadn't occurred.
Deletion is required, however due to higher level rules I can guarantee that a iterator will never be stopped on an item that is available for deletion.
Locking per node for a cursor would have too great an impact on performance. There may be a number of threads reading at once, and any kind of memory hot spot that multiple threads are using in a lock kills memory bandwidth (as we discovered the hard way!). Even a simple count of readers with multiple threads calling InterlockedIncrement fails to scale cleanly.
I agree a linked list is likely the best approach. Deletes are rare, so paying the memory penalty for the back pointers to support O(1) delete is costly and we may compute those separately on demand and since deletes tend to be batch operations.
Fortunately insertion into a linked list doesn't require any locking for readers, as long as the pointers are updated in the inserted node before the head pointer is changed.
The lock-copy-unlock idea is interesting. The amount of data involved is too large for this to work as the default for readers, but it could be used for writers when they collide with readers. A read/write lock would protect the whole structure, and the write would clone the data structure if it collides with a reader. Writes are much rarer than reads.
|
Personally, I'm quite fond of persistent immutable data structures in highly-concurrent situations. I don't know of any specifically for C++, but Rich Hickey has created some excellent (and blisteringly fast) immutable data structures in Java for Clojure. Specifically: vector, hashtable and hashset. They aren't too hard to port, so you may want to consider one of those.
To elaborate a bit more, persistent immutable data structures really solve a lot of problems associated with concurrency. Because the data structure itself is immutable, there isn't a problem with multiple threads reading/iterating concurrently (so long as it is a const iterator). "Writing" can also be asynchronous because it's not really writing to the existing structure but rather creating a new version of that structure which includes the new element. This operation is made efficient (O(1) in all of Hickey's structures) by the fact that you aren't actually copying everything. Each new version shares most of its structure with the old version. This makes things more memory efficient, as well as dramatically improving performance over the simple copy-on-write technique.
With immutable data structures, the only time where you actually need to synchronize is in actually writing to a reference cell. Since memory access is atomic, even this can usually be lock-free. The only caveat here is you might lose data between threads (race conditions). The data structure will never be corrupted due to concurrency, but that doesn't mean that inconsistent results are impossible in situations where two threads create a new version of the structure based on a single old and attempt to write their results (one of them will "win" and the other's changes will be lost). To solve this problem, you either need to have a lock for "writing operations", or use some sort of STM. I like the second approach for ease-of-use and throughput in low-collision systems (writes are ideally non-blocking and reads never block), but either one will work.
You've asked a tough question, one for which there isn't really a good answer. Concurrency-safe data structures are hard to write, particularly when they need to be mutable. Completely lock-free architectures are provably impossible in the presence of shared state, so you may want to give up on that requirement. The best you can do is minimize the locking required, hence the immutable data structures.
|
262,451
| 264,725
|
How do I programmatically send an email in the same way that I can "Send To Mail Recipient" in Windows Explorer?
|
ShellExecute() allows me to perform simple shell tasks, allowing the system to take care of opening or printing files. I want to take a similar approach to sending an email attachment programmatically.
I don't want to manipulate Outlook directly, since I don't want to assume which email client the user uses by default. I don't want to send the email directly, as I want the user to have the opportunity to write the email body using their preferred client. Thus, I really want to accomplish exactly what Windows Explorer does when I right click a file and select Send To -> Mail Recipient.
I'm looking for a C++ solution.
|
This is my MAPI solution:
#include <tchar.h>
#include <windows.h>
#include <mapi.h>
#include <mapix.h>
int _tmain( int argc, wchar_t *argv[] )
{
HMODULE hMapiModule = LoadLibrary( _T( "mapi32.dll" ) );
if ( hMapiModule != NULL )
{
LPMAPIINITIALIZE lpfnMAPIInitialize = NULL;
LPMAPIUNINITIALIZE lpfnMAPIUninitialize = NULL;
LPMAPILOGONEX lpfnMAPILogonEx = NULL;
LPMAPISENDDOCUMENTS lpfnMAPISendDocuments = NULL;
LPMAPISESSION lplhSession = NULL;
lpfnMAPIInitialize = (LPMAPIINITIALIZE)GetProcAddress( hMapiModule, "MAPIInitialize" );
lpfnMAPIUninitialize = (LPMAPIUNINITIALIZE)GetProcAddress( hMapiModule, "MAPIUninitialize" );
lpfnMAPILogonEx = (LPMAPILOGONEX)GetProcAddress( hMapiModule, "MAPILogonEx" );
lpfnMAPISendDocuments = (LPMAPISENDDOCUMENTS)GetProcAddress( hMapiModule, "MAPISendDocuments" );
if ( lpfnMAPIInitialize && lpfnMAPIUninitialize && lpfnMAPILogonEx && lpfnMAPISendDocuments )
{
HRESULT hr = (*lpfnMAPIInitialize)( NULL );
if ( SUCCEEDED( hr ) )
{
hr = (*lpfnMAPILogonEx)( 0, NULL, NULL, MAPI_EXTENDED | MAPI_USE_DEFAULT, &lplhSession );
if ( SUCCEEDED( hr ) )
{
// this opens the email client with "C:\attachment.txt" as an attachment
hr = (*lpfnMAPISendDocuments)( 0, ";", "C:\\attachment.txt", NULL, NULL );
if ( SUCCEEDED( hr ) )
{
hr = lplhSession->Logoff( 0, 0, 0 );
hr = lplhSession->Release();
lplhSession = NULL;
}
}
}
(*lpfnMAPIUninitialize)();
}
FreeLibrary( hMapiModule );
}
return 0;
}
|
262,714
| 262,908
|
Anyone have a good shared memory container for C++?
|
I've long had a desire for an STLish container that I could place into a shared memory segment or a memory mapped file.
I've considered the use of a custom allocator and placement new to place a regular STL container into a shared memory segment. (like this ddj article). The problem is that STL containers will internally have pointers to the memory they own. Therefore, if the shared memory segment or memory mapped file loads at a different base address (perhaps on a subsequent run, or in a second process), then the internal pointers are suddenly invalid. As far as I can figure out, the custom allocator approach only works if you can always map the memory segment into your process at the same address. At least with memory mapped files, I have lots of experience of that NOT being the case if you just let the system map it where ever it feels like.
I've had some thoughts on how to do this, but I'd like to avoid it if someone else has already done the work (that's me, being lazy).
I'm currently leaving locking out of the discussion, as the best locking strategy is highly application dependent.
|
The best starting point for this is probably the boost Interprocess libraries. They have a good example of a map in shared memory here:
interprocess map
You will probably also want to read the section on offset smart pointers, which solves the internal pointer problem you were referring to.
Offset Pointer
|
262,853
| 262,872
|
C++ map access discards qualifiers (const)
|
The following code says that passing the map as const into the operator[] method discards qualifiers:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class MapWrapper {
public:
const int &get_value(const int &key) const {
return _map[key];
}
private:
map<int, int> _map;
};
int main() {
MapWrapper mw;
cout << mw.get_value(42) << endl;
return 0;
}
Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const?
MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>,
std::allocator<std::pair<const int, int> > > as this argument of
_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
[with _Key = int, _Tp = int, _Compare = std::less<int>,
_Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers
|
std::map's operator [] is not declared as const, and cannot be due to its behavior:
T& operator[] (const Key& key)
Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist.
As a result, your function cannot be declared const, and use the map's operator[].
std::map's find() function allows you to look up a key without modifying the map.
find() returns an iterator, or const_iterator to an std::pair containing both the key (.first) and the value (.second).
In C++11, you could also use at() for std::map. If element doesn't exist the function throws a std::out_of_range exception, in contrast to operator [].
|
262,932
| 263,003
|
(int) ch vs. int(ch): Are they different syntaxes for the same thing?
|
In C++, is (int) ch equivalent to int(ch).
If not, what's the difference?
|
They are the same thing, and also the same as (int)(ch). In C++, it's generally preferred to use a named cast to clarify your intentions:
Use static_cast to cast between primitive types of different sizes or signednesses, e.g. static_cast<char>(anInteger).
Use dynamic_cast to downcast a base class to a derived class (polymorphic types only), e.g. dynamic_cast<Derived *>(aBasePtr).
Use reinterpret_cast to cast between pointers of different types or between a pointer and an integer, e.g. reinterpret_cast<uintptr_t>(somePtr).
Use const_cast to remove the const or volatile qualifiers from variables (VERY DANGEROUS), e.g. const_cast<char *>(aConstantPointer).
|
263,227
| 263,313
|
Why do Boost libraries return things "convertible to `bool`" rather than just returning `bool`s?
|
Several times, while perusing the Boost library's documentation, I've run across return values that are marked "convertible to bool" (search that page for the phrase "convertible to bool", it's about a third of the way down). I once stumbled across an oblique reference to a paper explaining the reason for that, but have never been able to find said paper (and I can no longer find the page I saw the reference on either).
Can anyone explain why (and when) you should return something that's "convertible to bool" rather than simply returning a bool?
|
“convertible to bool” simply means anything which can meaningfully be used in a boolean context (e.g. in an if condition). This makes sense in implicit conversions. Imagine an object which you want to use in a boolean context, e.g. std::fstream:
ifstream ifs("filename");
while (ifs >> token)
cout "token " << token << " read." << endl;
Here, ifs is convertible to boolean. Well, actually, it isn't. Rather, it is convertible to something that, in turn, is convertible to bool. This is to prevent such statements:
int b = ifs;
The reasoning is that such a statement is most probably not intended and the compiler should therefore prevent it. By returning a “convertible to bool” rather than a bool, this is achieved because two user-defined implicit conversions can't be chained in one expression.
In this context, you might want to look up the safe bool idiom. Chris has already alluded to one possible implementation, using void* as a return type. Usually, the this pointer is then used to represent true. This is what gets used by the STL. However, this is unfortunately still flawed. Several alternatives have been proposed (neatly wrapped up in the article I've linked above) and as far as I know, have also been included into C++0x for consideration. I'm not aware of the current status of these proposals, though.
|
263,339
| 263,431
|
Evaluating expressions inside C++ strings: "Hi ${user} from ${host}"
|
I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions.
Example: "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc.
The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions?
Note: boost:: is most welcome! :-)
Update Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)
|
#include <iostream>
#include <conio.h>
#include <string>
#include <map>
using namespace std;
struct Token
{
enum E
{
Replace,
Literal,
Eos
};
};
class ParseExp
{
private:
enum State
{
State_Begin,
State_Literal,
State_StartRep,
State_RepWord,
State_EndRep
};
string m_str;
int m_char;
unsigned int m_length;
string m_lexme;
Token::E m_token;
State m_state;
public:
void Parse(const string& str)
{
m_char = 0;
m_str = str;
m_length = str.size();
}
Token::E NextToken()
{
if (m_char >= m_length)
m_token = Token::Eos;
m_lexme = "";
m_state = State_Begin;
bool stop = false;
while (m_char <= m_length && !stop)
{
char ch = m_str[m_char++];
switch (m_state)
{
case State_Begin:
if (ch == '$')
{
m_state = State_StartRep;
m_token = Token::Replace;
continue;
}
else
{
m_state = State_Literal;
m_token = Token::Literal;
}
break;
case State_StartRep:
if (ch == '{')
{
m_state = State_RepWord;
continue;
}
else
continue;
break;
case State_RepWord:
if (ch == '}')
{
stop = true;
continue;
}
break;
case State_Literal:
if (ch == '$')
{
stop = true;
m_char--;
continue;
}
}
m_lexme += ch;
}
return m_token;
}
const string& Lexme() const
{
return m_lexme;
}
Token::E Token() const
{
return m_token;
}
};
string DoReplace(const string& str, const map<string, string>& dict)
{
ParseExp exp;
exp.Parse(str);
string ret = "";
while (exp.NextToken() != Token::Eos)
{
if (exp.Token() == Token::Literal)
ret += exp.Lexme();
else
{
map<string, string>::const_iterator iter = dict.find(exp.Lexme());
if (iter != dict.end())
ret += (*iter).second;
else
ret += "undefined(" + exp.Lexme() + ")";
}
}
return ret;
}
int main()
{
map<string, string> words;
words["hello"] = "hey";
words["test"] = "bla";
cout << DoReplace("${hello} world ${test} ${undef}", words);
_getch();
}
I will be happy to explain anything about this code :)
|
263,370
| 263,399
|
Does the range for integer values of a char depend on implementation?
|
I'm reading The C++ Programming Language and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127. If not, why are their only 255 possible values in the second implementation possibility, not 256.
|
You're stuck in two's complement thinking - The C++ standard does not define the representation used for negative numbers!
If your computer (god forbid) uses ones's complement to represent negative numbers, you have a range of -127 to + 127 in an 8-bit byte. On the upside, you have two different possible representations for zero...
However, in the real world, you're unlikely to meet a one's complement computer.
|
263,735
| 265,414
|
How do I decide if a selection of text in CRichEditCtrl has multiple font sizes?
|
Problem:
How can I tell if a selection of text in the CRichEditCtrl has multiple font sizes in it?
Goal:
I am sort of making my own RichEdit toolbar (bold, italic, font type, font size, etc). I want to emulate what MS Word does when a selection of text has more than a single font size spanning the selection.
Ex - You have a line of text with the first 10 characters 9 pt font and the next 15 characters 14 pt font. If you highlight the first 5 characters, the "Font Pt Selection" drop down displays "9". If you then select the first 20 characters, the same drop down should have a empty/blank display.
What I have going so far:
I am getting the necessary notification when the selection changes inside of the CRichEditCtrl. Also, if there is only a single font size in the selection I am able to figure that out
CHARFORMAT cf;
cf.cbSize = sizeof(CHARFORMAT);
CRichEditCtrl ctrl;
ctrl.GetSelectionCharFormat( cf );
int nFontPtSize = cf.yHeight / 20;
This will give me the needed info for the first case of my example above. Unfortunately, what I seem to get for the second part of my example only gives me back the info for where the selection ends (instead of the entire selection).
In conclusion, is there some info I am missing in the CHARFORMAT or some other struct I can get from the CRichEditCtrl or some kind of interesting calculation I can do to make the decision that there are multiple sizes in the selection? So far my only idea is to chug through the selection a character at a time and see if the current font size of that character is different than any of the previous characters. I am mostly just hoping the info I need is there, and I just don't see it (In a similar way that from the CHARFORMAT's dwMask member tells me that any or all of Bold, Italic, Underline, etc are turned on).
|
As the above answer notes, the easiest way I can think of to do this is to use the Text Object Model (TOM), which is accessed through the ITextDocument COM interface. To get at this from your rich edit control (note code not tested, but should work):
CComPtr<IRichEditOle> richOle;
richOle.Attach(edit.GetIRichEditOle());
CComQIPtr<ITextDocument> textDoc(richOle);
Then get a range. Here this is for the selected text, but one of the advantages of TOM is that you can operate on any range, not just what's selected.
CComPtr<ITextSelection> range;
textDoc->GetSelection(&range);
Then get the font for the range, and see what its characteristics are, e.g.
CComPtr<ITextFont> font;
range->GetFont(&font);
long size;
font->GetSize(&size);
If the range is formatted with a single font size, you'll get that back in "size". If there's multiple font sizes, you'll get the value "tomUndefined" instead.
|
263,906
| 263,914
|
C++ construction weird uninitialized pointer
|
AlertEvent::AlertEvent(const std::string& text) :
IMEvent(kIMEventAlert, alertText.c_str()),
alertText(text)
{
//inspection at time of crash shows alertText is a valid string
}
IMEvent::IMEvent(long eventID, const char* details)
{
//during construction, details==0xcccccccc
}
on a related note, the monospace font looks really terrible in chrome, whats up with that?
|
alertText may be shown as a string in a debugger, but it has not been constructed yet (and therefore alertText.c_str() will return an indeterminate pointer).
To avoid this, one could initialize use text.c_str() as an argument to the IMEvent ctor.
AlertEvent::AlertEvent(const std::string& text) :
IMEvent(kIMEventAlert, text.c_str()),
alertText(text)
{
//inspection at time of crash shows alertText is a valid string
}
IMEvent::IMEvent(long eventID, const char* details)
{
//during construction, details==0xcccccccc
}
|
263,945
| 263,958
|
What happens if you call erase() on a map element while iterating from begin to end?
|
In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
if (pm_it->second == delete_this_id) {
port_map.erase(pm_it->first);
}
}
UPDATE: Of course, I then read this question which I didn't think would be related but answers my question.
|
C++11
This has been fixed in C++11 (or erase has been improved/made consistent across all container types).
The erase method now returns the next iterator.
auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
if (pm_it->second == delete_this_id)
{
pm_it = port_map.erase(pm_it);
}
else
{
++pm_it;
}
}
C++03
Erasing elements in a map does not invalidate any iterators.
(apart from iterators on the element that was deleted)
Actually inserting or deleting does not invalidate any of the iterators:
Also see this answer:
Mark Ransom Technique
But you do need to update your code:
In your code you increment pm_it after calling erase. At this point it is too late and is already invalidated.
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
if (pm_it->second == delete_this_id)
{
port_map.erase(pm_it++); // Use iterator.
// Note the post increment.
// Increments the iterator but returns the
// original value for use by erase
}
else
{
++pm_it; // Can use pre-increment in this case
// To make sure you have the efficient version
}
}
|
264,057
| 264,084
|
iostream linker error
|
I have some old C code that I would like to combine with some C++ code.
The C code used to have has the following includes:
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "mysql.h"
Now I'm trying to make it use C++ with iostream like this:
#include <windows.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "mysql.h"
But I keep getting the following linker errors when I compile:
[Linker error] undefined reference to `std::string::size() const'
[Linker error] undefined reference to `std::string::operator[](unsigned int) const'
[Linker error] undefined reference to `std::string::operator[](unsigned int) const'
[Linker error] undefined reference to `std::string::operator[](unsigned int) const'
[Linker error] undefined reference to `std::ios_base::Init::Init()'
[Linker error] undefined reference to `std::ios_base::Init::~Init()'
ld returned 1 exit status
How do I resolve this?
Edit: My compiler is Dev-C++ 4.9.9.2
|
The C string.h header and the C++ string header are not interchangeable.
Overall, though, your problem is that the file is getting properly compiled, but the wrong runtime library is getting linked in.
Dev-C++ uses GCC. GCC can correctly determine the language in a file based on file extension, but won't link the right runtime library in unless you specifically ask it to (-lstdc++ at the command line). Calling GCC as "g++" (or, in your case, "mingwin32-g++") will also get the right language and will link the needed library.
|
264,217
| 264,261
|
Multiple menu items in bold face
|
I've been investigating the effort needed in getting menu items displayed in bold face - without having to draw the menu myself - and discovered MFS_DEFAULT menu item state after some googling. The MSDN documentation mentions
MFS_DEFAULT
Specifies that the menu
item is the default. A menu can
contain only one default menu item,
which is displayed in bold.
I experimented and it appears that contrary to the documentation, it seems like I'm able to use this flag to display multiple (or possibly all!) menu items in bold face. Does anyone have any experience with this i.e. if there are any pitfalls in having multiple bolded menu items? It does feel like a bit of a hack to get to what I'm trying to achieve and I'm a little worried about unknown side-effects (i.e. having multiple 'default' menu items in a single menu).
EDIT: I should also add that this article claims that the MFS_DEFAULT flag does nothing but displaying the menu item in bold face; still, I'm a little wary of going against the 'official' documentation...
EDIT2: The purpose of this was to tell the user that the menu item in question (i.e. that one that is bolded) can also be invoked by double clicking the control in question (the menu item is part of context menu). When I thought about this problem I didn't consider the fact that - usually - only one command can be associated with the double click event (d'oh!). As such I have accepted zaphod's answer (it doesn't answer this question directly but it did solve my 'problem')
|
What are you trying to achieve?
I suspect that the biggest objection to using MFS_DEFAULT for a purpose other than the one for which it was intended is that you're violating a visual convention Microsoft is trying to promulgate about what bolded menu items mean, and how a user (or an assistive program such as a screen reader) should react upon encountering one.
If all you're trying to do is call the user's attention to a few menu items that are of particular interest -- well, that seems a bit strange, but it also seems fairly innocent, and I'd be surprised if it caused you enormous problems down the road. Anything's possible, of course! Still, I'd wonder about what exactly you were up to.
If you're trying to expose part of your program's state by bolding and unbolding menu items -- that seems a little bit unexpected to me, but I'd hate to pass judgement before hearing the specifics.
If you have some other goal in mind -- like maybe you think the default font for menus is ugly and you like it better when everything is bolded -- then the method you've discovered might be expedient, but there might also be a better way to get exactly what you want, which we could discuss in more detail (perhaps in a separate question) if you were willing. I doubt this is the case, but who knows?
|
264,552
| 264,670
|
C/C++ Code to treat a character array as a bitstream
|
I have a big lump of binary data in a char[] array which I need to interpret as an array of packed 6-bit values.
I could sit down and write some code to do this but I'm thinking there has to be a good extant class or function somebody has written already.
What I need is something like:
int get_bits(char* data, unsigned bitOffset, unsigned numBits);
so I could get the 7th 6-bit character in the data by calling:
const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
|
This may not work for sizes greater than 8, depending on endian system. It's basically what Marco posted, though I'm not entirely sure why he'd gather one bit at a time.
int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) {
numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, of course
data += bitOffset/8;
bitOffset %= 8;
return (*((int*)data) >> bitOffset) & numBits; //little endian
//return (flip(data[0]) >> bitOffset) & numBits; //big endian
}
//flips from big to little or vice versa
int flip(int x) {
char temp, *t = (char*)&x;
temp = t[0];
t[0] = t[3];
t[3] = temp;
temp = t[1];
t[1] = t[2];
t[2] = temp;
return x;
}
|
264,763
| 489,354
|
Suppressing C++ 'Post-Build Event' when using msbuild
|
I am using msbuild to build a C++ project and I want to suppress the 'Post-Build Event'. I have tried the following properties with no success:
/property:PostBuildEvent=
/property:VCPostBuildEventTool=
Neither will make any difference and the post build events are still executed.
Does anyone know how to suppress these (and potentially other) events using msbuild?
|
I just figured out how to do this. There's 2 steps involved:
First, if you're not starting the msbuild process using a batch file already, create a batch file that calls the msbuild process. Then add a variable in the batch file before you call the msbuild process. Something like this:
set ISFULLBUILD=True
msbuild TFSBuild.proj >> BuildOutput.txt
Then, you need to modify your post build event to only do something if the variable is not set, or has the wrong value:
IF NOT '%ISFULLBUILD%'=='True' copy /y $(TargetFileName) "..\..\..\..\..\..\Binaries\$(ConfigurationName)\"
In this case - the TargetFileName (Whatever.dll) will only get copied when you're building from Visual Studio. But, when you build using your new batch file - it will NOT execute the command after the IF statement.
|
265,228
| 265,307
|
How can I negate a functor in C++ (STL)?
|
I have some function to find a value:
struct FindPredicate
{
FindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t == _t;
}
private:
const SomeType& _t;
};
bool ContainsValue(std::vector<SomeType>& v, SomeType& valueToFind) {
return find_if(v.begin(), v.end(), FindPredicate(valueToFind)) != v.end();
}
Now I would like to write a function that checks if all members of a vector satisfy that predicate:
bool AllSatisfy(std::vector<SomeType>& v) {
/* ... */
}
One solution is to use the std::count_if algorithm.
Does anyone know a solution that involves negating the predicate?
|
The best solution is to use the STL functional library. By deriving your predicate from unary_function<SomeType, bool> , you'll then be able to use the not1 function, which does precisely what you need (i.e. negating a unary predicate).
Here is how you could do that :
struct FindPredicate : public unary_function<SomeType, bool>
{
FindPredicate(const SomeType& t) : _t(t) {}
bool operator()(const SomeType& t) const {
return t == _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
return find_if(v.begin(),
v.end(),
not1(FindPredicate(valueToFind))) == v.end();
}
If you want to roll your own solution (which is, IMHO, not the best option...), well, you could write another predicate that is the negation of the first one :
struct NotFindPredicate
{
NotFindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t != _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v) {
return find_if(v.begin(),
v.end(),
NotFindPredicate(valueToFind)) == v.end();
}
Or you could do better and write a template functor negator, like :
template <class Functor>
struct Not
{
Not(Functor & f) : func(f) {}
template <typename ArgType>
bool operator()(ArgType & arg) { return ! func(arg); }
private:
Functor & func;
};
that you could use as follow :
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
FindPredicate f(valueToFind);
return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}
Of course, the latter solution is better because you can reuse the Not struct with every functor you want.
|
265,258
| 265,365
|
How do I avoid scientific notation for large numbers?
|
I am doing 2^1000 and I am getting this:
1.07151e+301
Is there any way to actually turn this into a proper number without the e+301, or at least can anyone show me where I can see how to turn this in to a real number, by some way working with the e+301 part?
|
So, I'm thinking that what you really want is just the ability to print it without scientific notation. If you're using printf, what you want is:
printf( "%f1000.0", value );
// note that 1000 is way larger than need be,
// I'm just too lazy to count the digits
With cout, try something like:
cout.setf(ios::fixed);
cout << setprecision(0) << value;
If you want to print it as a power of two (2^1000 vs 10715...), you're on your own.
|
265,518
| 265,556
|
Fastest way to create large file in c++?
|
Create a flat text file in c++ around 50 - 100 MB
with the content 'Added first line' should be inserted in to the file for 4 million times
|
using old style file io
fopen the file for write.
fseek to the desired file size - 1.
fwrite a single byte
fclose the file
|
265,563
| 265,580
|
Creating a lib from other libs : is it possible?
|
I'm using Windows CE Platform Builder and my code is written in C++ . For each of the folders in the project I'm creating a lib ( the code is statically linked ) . However , there are about 20 libs so far . Is there a way to reduce their number ? I was thinking of creating a lib from other libs , but I don't know if that's even possible . Is it ?
EDIT: how could I do it ?
|
I haven't tried it in a while, but traditionally you could use the librarian tool (LIB.EXE) to do this sort of thing.
$ lib /?
Microsoft (R) Library Manager Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
usage: LIB [options] [files]
options:
/DEF[:filename]
/ERRORREPORT:{NONE|PROMPT|QUEUE|SEND}
/EXPORT:symbol
/EXTRACT:membername
/INCLUDE:symbol
/LIBPATH:dir
/LIST[:filename]
/LTCG
/MACHINE:{ARM|EBC|IA64|MIPS|MIPS16|MIPSFPU|MIPSFPU16|
SH4|THUMB|X64|X86}
/NAME:filename
/NODEFAULTLIB[:library]
/NOLOGO
/OUT:filename
/REMOVE:membername
/SUBSYSTEM:{BOOT_APPLICATION|CONSOLE|EFI_APPLICATION|
EFI_BOOT_SERVICE_DRIVER|EFI_ROM|EFI_RUNTIME_DRIVER|
NATIVE|POSIX|WINDOWS|WINDOWSCE}[,#[.##]]
/VERBOSE
/WX[:NO]
Normally the librarian takes .OBJ files and combines them into a .LIB, but I think it will also read .LIB files as input.
|
266,168
| 11,229,853
|
Simple example of threading in C++
|
Can someone post a simple example of starting two (Object Oriented) threads in C++.
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
|
Create a function that you want the thread to execute, for example:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
Now create the thread object that will ultimately invoke the function above like so:
std::thread t1(task1, "Hello");
(You need to #include <thread> to access the std::thread class.)
The constructor's first argument is the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
If later on you want to wait for the thread to be done executing the function, call:
t1.join();
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution.)
The Code
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
More information about std::thread here
On GCC, compile with -std=c++0x -pthread.
This should work for any operating-system, granted your compiler supports this (C++11) feature.
|
266,206
| 266,233
|
Simple hashmap implementation in C++
|
I'm relatively new to C++. In Java, it's easy for me to instantiate and use a hashmap. I'd like to know how to do it in a simple way in C++, since I saw many different implementations and none of them looked simple to me.
|
Most compilers should define std::hash_map for you; in the coming C++0x standard, it will be part of the standard library as std::unordered_map. The STL Page on it is fairly standard. If you use Visual Studio, Microsoft has a page on it.
If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like int, char, bool and even char *) should "just work" as keys in a hash_map. However, for anything else you will have to define your own hashing and equality functions and then write "functors" that wrap them in a class.
Assuming your class is called MyClass and you have already defined:
size_t MyClass::HashValue() const { /* something */ }
bool MyClass::Equals(const MyClass& other) const { /* something */ }
You will need to define two functors to wrap those methods in objects.
struct MyClassHash {
size_t operator()(const MyClass& p) const {
return p.HashValue();
}
};
struct MyClassEqual {
bool operator()(const MyClass& c1, const MyClass& c2) const {
return c1.Equals(c2);
}
};
And instantiate your hash_map/hash_set as:
hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map;
hash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set;
Everything should work as expected after that.
|
266,326
| 266,338
|
How do I cast a bool to a BOOL?
|
Am I safe in casting a C++ bool to a Windows API BOOL via this construct
bool mybool = true;
BOOL apiboolean = mybool ? TRUE : FALSE;
I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears.
Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.
|
Do you mean
bool b;
...
BOOL apiboolean = b ? TRUE : FALSE;
If so, then yes, this will work.
|
266,328
| 266,514
|
Embed non-managed directX into C# form
|
I got a quick question about running a directX application (C++) in a managed environment. I'm attempting to write a MDI tool (in C#) where the background of the parent window would be an embedded render window of directX (C++).
I've read ways that involved writing the C++ into a native dll, however it would be prefered to be able to have the C++ projects included within the solution (I dont even know if that's possible though). Eitherway, if you know of some helpful steps, hints, or if this is a bad idea in general, please let me know. Thanks!
|
The easiest way to do this would be to add a C++/CLI project to your solution. This would then enable you to use the DirectX COM interfaces directly and create a managed wrapper that's easy to call from your C# code. I've taken this approach a few times and it's by far the easiest way of mixing DirectX and .Net that I've ever tried. Managed DirectX used to be an option, but it's no longer supported and it was a fairly small subset of the full COM API anyway.
|
266,665
| 266,703
|
infinite loop in c++
|
I'm learning C++ and writing little programs as I go along. The following is one such program:
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.
What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)
|
Basically your cin stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
cin >> n will return a reference to cin, which you can test for "good-ness" in a conditional. So basically the the "while(std::cin >> n)" is saying "while i could still read from standard input successfully, do the following"
EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n
EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:
#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}
|
266,694
| 266,743
|
pass DataTable to unmanaged environment (visual c# 2005)
|
What will the best way to pass a datatable data to unmanaged environments? (c++)
Ofer
|
I don't think there is a single best answer here.
One option is to export the database as XML and let your unmanaged code consume that. The main benefit of this approach is it is cheaper (development-wise) on the managed side and provides flexibility on the unmanaged side.
Otherwise you will need to provide your own marshaling of the data. This would be best down with C++/CLI code that could work with the dataset and convert it to a data structure that your unmanaged code understands.
We've done something similar in the past and it works, but is a fair amount of code to cover the general case.
|
266,854
| 266,868
|
Why are C++ methods sometimes defined inside classes?
|
I frequently run into large, non-template classes in C++ where simple methods are defined directly in the class body in the header file instead of separately in the implementation file. For example:
class Foo {
int getBar() const { return bar; }
...
};
Why do this? It seems like there are disadvantages. The implementation is not as hidden as it should be, the code is less readable, and there would also be an increased burden on the compiler if the class's header file is included in many different places.
My guess is that people intend for these functions to be inlined in other modules, which could improve performance significantly. However, I've heard newer compilers can do inlining (and other interprocedural optimizations) at link-time across modules. How broad is the support for this kind of link-time optimization, and does it actually make these kind of definitions unnecessary? Are there any other good reasons for these definitions?
|
The C++ standard says that methods defined inside the class definition are inline by default. This results in obvious performance gains for simplistic functions such as getters and setters. Link-time cross-module optimization is harder, although some compilers can do it.
|
266,870
| 266,894
|
Why is a char and a bool the same size in c++?
|
I'm reading The C++ Programming Language. In it Stroustrup states that sizeof(char) == 1 and 1 <= sizeof(bool). The specifics depend on the implementation. Why would such a simple value as a boolean take the same space as a char?
|
In modern computer architectures, a byte is the smallest addressable unit of memory. To pack multiple bits into a byte requires applying extra bit-shift operations. At the compiler level, it's a trade off of memory vs. speed requirements (and in high-performance software, those extra bit-shift operations can add up and slow down the application needlessly).
|
267,026
| 267,032
|
Simple C++ code not working
|
This very simple code gives me tons of errors:
#include <iostream>
#include <string>
int main() {
std::string test = " ";
std::cout << test;
}
I tried to compile it on linux by typing gcc -o simpletest simpletest.cpp on the console. I can't see why it isn't working. What is happening?
|
Try using 'g++' instead of 'gcc'.
|
267,248
| 267,415
|
Getting rid of gcc shift by negative warning
|
I have some code that looks like:
template<unsigned int A, unsigned int B>
int foo() {
int v = 1;
const int x = A - B;
if (x > 0) {
v = v << x;
}
bar(v);
}
gcc will complain about x being negative for certain instantiations of A, B; however, I do perform a check to make sure it is non-negative. What's the best way around this? I know I can cast x to be unsigned int but that will cause warnings about x being larger than the width of v (since it is casting a negative number to be positive). I know there is a work-around that involves creating a new templatized shift function, but I'd like to avoid that if possible.
|
Since A and B are known at compile time, not only can you get rid of your warning, but you can also get rid of a runtime if, without any casts, like this:
#include <iostream>
using namespace std;
template< unsigned int A, unsigned int B >
struct my
{
template< bool P >
static void shift_if( int & );
template<>
static void shift_if< false >( int & ) {}
template<>
static void shift_if< true >( int & v ) { v <<= A - B; }
static void op( int & v ) { shift_if< (A > B) >( v ); }
};
template< unsigned int A, unsigned int B >
int foo()
{
int v = 1;
my< A, B >::op( v );
return v;
}
int main() {
cout << foo< 1, 3 >() << endl;
cout << foo< 3, 1 >() << endl;
cout << foo< 300, 1 >() << endl;
cout << foo< 25, 31 >() << endl;
return 0;
}
|
267,259
| 267,319
|
C++ project structure under Visual Studio 2008
|
So, I've been doing Java for a number of years now, but now I'm starting a C++ project. I'm trying to determine best practices for setting up said project.
Within the project, how do you generally structure their code? Do you do it Java style with namespace folders and break up your source that way? Do you keep your public headers in an include directory for easy referencing?
I've seen both and other ways mentioned, but what's a good method for a large project?
Also, how do you deal with resources/folders in your application structure? It's all well and good for the final project to install with a log folder for storing logs, maybe a lib folder for library files, maybe a data folder for data, but how do you manage those bits within the project? Is there a way to define that so when you build the solution it constructs the structure for you? Or, do you simply have to go into your built configuration folders (Debug, Release, etc.), and construct the file structure manually, thus ensuring paths your EXE file is expecting to find are properly positioned?
|
We tend to make each component a solution, containing one or more projects (or sub-components) and a test project. The test project contains all of the unit tests.
We then arrange the solutions into a tree based on modules and components, for example:
//depot/MyProject/ASubSystem/AComponentOfTheSubSystem/ASubComponentWithAVSSolution
The solution will then contain several Visual Studio projects:
//depot/MyProject/ASubSystem/AComponentOfTheSubSystem/ASubComponentWithAVSSolution/Something
//depot/MyProject/ASubSystem/AComponentOfTheSubSystem/ASubComponentWithAVSSolution/SomethingElse
//depot/MyProject/ASubSystem/AComponentOfTheSubSystem/ASubComponentWithAVSSolution/TestTheSolution
There might be more depth to the tree, or less, depending on the number of components/sub-components there are. We also tend to have a "General" solution at the sub system and sub component level with general re-useable stuff.
We then have a sub system-level solution which ties everything together to build the sub system.
We do not use or export to an "include" directory. We let Visual Studio build and link within our sandboxes. We have a separate "Release" sandbox to ensure we don't accidentally link the wrong library.
|
267,367
| 268,262
|
In C++: Is it possible to have a named enum be continued in a different file?
|
For example:
Base class header file has:
enum FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_USERSTART
};
Then the derived class has:
enum FOO
{
FOO_USERA=FOO_USERSTART
FOO_USERB,
FOO_USERC
};
Just to be clear on my usage it is for having an event handler where the base class has events and then derived classes can add events. The derived classes event handler would check for it's events and if the event was not for it, then it would pass the event down to the base class.
class Base
{
public:
virtual void HandleFoo(FOO event);
};
class Derived: public Base
{
public:
void HandleFoo(FOO event);
};
void Base::HandleFoo(FOO event)
{
switch(event)
{
case FOO_A:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
}
}
void Derived::HandleFoo(FOO event)
{
switch(event)
{
case FOO_USERA:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
default:
/* not my event, must be for someone else */
Base::HandleFoo(event);
break;
}
}
|
No. The compiler needs to be able to decide whether the enum fits in a char, short, int or long once it sees the }.
So if the base class header has
enum Foo {
A,
B,
MAX = 1<<15
};
a compiler may decide the enum fits in 16 bits. It can then use that, e.g. when laying out the base class. If you were later able to add 1<<31 to the enum, the base class enum member would not be able to hold one of the enum values.
|
267,418
| 267,514
|
Elegant template specialization
|
Is there an elegant way to specialize a template based on one of its template parameters?
Ie.
template<int N> struct Junk {
static int foo() {
// stuff
return Junk<N - 1>::foo();
}
};
// compile error: template argument '(size * 5)' involves template parameter(s)
template<int N> struct Junk<N*5> {
static int foo() {
// stuff
return N;
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
Ie. I am trying to specialize a template based on the parameter being divisible by 5. The only way I can seem to do it is like below:
template<int N> struct JunkDivisibleBy5 {
static int foo() {
// stuff
return N;
}
};
template<int N> struct Junk {
static int foo() {
// stuff
if ((N - 1) % 5 == 0 && N != 1)
return JunkDivisibleBy5<N - 1>::foo();
else
return Junk<N - 1>::foo();
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
But this is significantly less elegant, and also necessitates instantiation of all templates even if the template argument shouldn't require it.
|
How's this:
#include <iostream>
using namespace std;
template < typename T, T N, T D >
struct fraction {
typedef T value_type;
static const value_type num = N;
static const value_type denom = D;
static const bool is_div = (num % denom == 0);
};
template< typename T, T N, T D, bool P >
struct do_if {
static void op() { cout << N << " NOT divisible by " << D << endl; }
};
template< typename T, T N, T D >
struct do_if< T, N, D, true > {
static void op() { cout << N << " divisible by " << D << endl; }
};
template < int N >
void foo() {
typedef fraction< int, N, 5 > f;
do_if< typename f::value_type, f::num, f::denom, f::is_div >::op();
}
int main() {
foo< -5 >();
foo< -1 >();
foo< 0 >();
foo< 1 >();
foo< 5 >();
foo< 10000005 >();
return 0;
}
|
267,427
| 267,936
|
c++ file io & splitting by separator
|
I have a file with data listed as follows:
0, 2, 10
10, 8, 10
10, 10, 10
10, 16, 10
15, 10, 16
17, 10, 16
I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers.
For some reason I can't find an easy way to do this in c++. The only success I've had is by inputting each line into an array, and then regexing out all the spaces and then splitting it up. This entire process took me a good 20-30 lines of code and its a pain to modify for say another separator(eg. space), etc.
This is the python equivalent of what I would like to have in C++:
f = open('input_hard.dat')
lines = f.readlines()
f.close()
#declarations
inint, inbase, outbase = [], [], []
#input parsing
for line in lines:
bits = string.split(line, ',')
inint.append(int(bits[0].strip()))
inbase.append(int(bits[1].strip()))
outbase.append(int(bits[2].strip()))
The ease of use of doing this in python is one of the reasons why I moved to it in the first place. However, I require to do this in C++ now and I would hate to have to use my ugly 20-30 line code.
Any help would be appreciated, thanks!
|
There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it's as short and readable as the python code:
FILE *fp = fopen("file.dat", "r");
int x, y, z;
std::vector<int> vx, vy, vz;
while (fscanf(fp, "%d, %d, %d", &x, &y, &z) == 3) {
vx.push_back(x);
vy.push_back(y);
vz.push_back(z);
}
fclose(fp);
|
267,477
| 267,561
|
C++ class member functions that use dummy parameters
|
I know that you can use a dummy "int" parameter on operator++ and operator-- to override the postfix versions of those operators, but I vaguely recall something about a dummy parameter that you could declare on a destructor. Does anyone know anything about that, and if so, what that dummy parameter did?
This was in my old Turbo C++ tutorial books, which I read when I was a teenager (i.e. a long time ago), so I might be completely misremembering it. That was also very early C++, before it was standardized, so it's possible that it was something Turbo C++-specific.
|
You're possibly thinking of the placement and nothrow forms of operator delete, which have the signatures:
void operator delete(void *, void *) throw();
void operator delete(void *, const std::nothrow_t&) throw();
void operator delete[](void *, void *) throw();
void operator delete[](void *, const std::nothrow_t&) throw();
These are never called during normal operation, but would be used in the case where the constructor for an object being constructed with placement new throws an exception. Generally you don't have to define them, since the compiler already called the destructor(s) on the dead object's bases and members, and for placement new there's no memory to be freed. But can exist if you are overloading placement new and need a corresponding operator.
The second argument is not really used, and just distinguishes the signature for the ordinary:
void operator delete(void *)
These aren't special dummy arguments the way the operator++ ones are, though. They're just an instance of the general rule that call to new with extra arguments, such as:
obj = new(x,y,z) Object(a,b,c)
will generate implicit code to clean up from constructor errors that passes those same additional arguments to the operator delete, which will function (approximately) like:
void *raw = operator new(sizeof(Object), x,y,z)
try {
obj = new(raw) Object(a,b,c);
} catch(...) {
operator delete(raw,x,y,z);
throw;
}
|
267,507
| 267,515
|
Tools to view/diagram function-call hierarchies for C or C++ source files in OSX
|
Are there any good source-code analyses tools for OSX. I am particularly interested in tools that are capable of diagramming function-call hierarchies for C and C++ source files.
|
You might take a look at doxygen
|
267,752
| 269,148
|
Boost Asio serial_port - need help with io
|
So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232. The documementation is sparse and the examples are non-existent. Can't figure out exactly how to communicate with the device. The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated. What code I have so far follows.
#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;
int main()
{
io_service io;
serial_port port( io, "COM3" );
port.set_option( serial_port_base::baud_rate( 19200 ) );
unsigned char commands[4] = { 1, 128, 240, 0 };
// write the commands to the device
return 0;
}
In short: need help with the io part of the serial_port.
|
In addition to the baud rate, you may also need to set other options like: character_size, flow_control, parity and stop_bits. To write your data to the serial port you can do the following:
boost::asio::write(port, boost::asio::buffer(commands, 4));
The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here: Buffers.
|
267,825
| 267,854
|
How do I find the file handles that my process has opened in Linux?
|
When we perform a fork in Unix, open file handles are inherited, and if we don't need to use them we should close them. However, when we use libraries, file handles may be opened for which we do not have access to the handle. How do we check for these open file handles?
|
If the libraries are opening files you don't know about, how do you know they don't need them after a fork? Unexported handles are an internal library detail, if the library wants them closed it will register an atfork() handler to close them. Walking around behind some piece of code closing its file handles behind its back will lead to subtle hard to debug problems since the library will error unexpectedly when it attempts to work with a handle it knows it opened correctly, but did not close.
|
267,838
| 267,866
|
How can a Windows service execute a GUI application?
|
I have written a Windows service that allows me to remotely run and stop applications. These applications are run using CreateProcess, and this works for me because most of them only perform backend processing. Recently, I need to run applications that present GUI to the current log in user. How do I code in C++ to allow my service to locate the currently active desktop and run the GUI on it?
|
Roger Lipscombe's answer, to use WTSEnumerateSessions to find the right desktop, then CreateProcessAsUser to start the application on that desktop (you pass it the handle of the desktop as part of the STARTUPINFO structure) is correct.
However, I would strongly recommend against doing this. In some environments, such as Terminal Server hosts with many active users, determining which desktop is the 'active' one isn't easy, and may not even be possible.
But most importantly, if an application will suddenly appear on a user's desktop, this may very well occur at a bad time (either because the user simply isn't expecting it, or because you're trying to launch the app when the session isn't quite initialized yet, in the process of shutting down, or whatever).
A more conventional approach would be to put a shortcut to a small client app for your service in the global startup group. This app will then launch along with every user session, and can be used start other apps (if so desired) without any juggling of user credentials, sessions and/or desktops.
Also, this shortcut can be moved/disabled by administrators as desired, which will make deployment of your application much easier, since it doesn't deviate from the standards used by other Windows apps...
|
267,908
| 267,914
|
Polluting the global namespace
|
I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored?
For example, I have a type that I need to use all over a particular application - should I define it thus:
mytypes.h
typedef int MY_TYPE;
foo.cpp
MY_TYPE myType;
Or use a namespace:
mytypes.h
namespace ns {
typedef int MY_TYPE;
}
foo.cpp
ns::MY_TYPE myType;
...
using namespace ns;
MY_TYPE myType;
Which do you prefer? Are there times when it is acceptable to use the first method?
|
I use namespaces for partitioning library code from application-specific code, and in a big project to partition the various modules that make up the project.
The global namespace is thus useful for application-specific types and functions that are used across multiple modules in the application.
So, if your MY_TYPE is used throughout your application, put it in the global namespace, otherwise put it in a named namespace.
|
267,998
| 312,047
|
Qt QGraphicsScene copy
|
I have a QGraphicsScene that I want to copy and append to the start of a list. What is the best method of doing this?
QGraphicsScene* m_scene = new QGraphicsScene();
QGraphicsScene* m_DuplicateScene;
QList<QGraphicsScene *>m_list;
|
Doing this would be very complicated because you don't know anything about the children of m_scene. Even if you dynamic_cast and create a clone() function for each type of QGraphicsItem, you still need to remember that other people can subclass QGraphicsItem and create their own type of graphics item, making them unclonable by you.
Basically, no, you can't duplicate a QGraphicsScene (cloning all items in the process). You can't even make references to the children of the original scene's children because a QGraphicsItem can only have one scene.
Unless I'm missing a method call, of course. Searches for "clone," "copy," and "duplicate" produced no results, though.
On your second question, use QList<T *>::push_front. Thus, m_list.push_front(m_DuplicateScene);
(Side note: you prepend to the start of a list, and append to the end of a list.)
|
268,011
| 268,689
|
On QCoreApplication and QProcess
|
I'm on the path to write a QCoreApplication supposed to create an external process via Qprocess.
I've just noticed that even if the waitForStarted() is called and the process state is Running before the event handler is executing, the external process does not start until the exec() method is invoked on the QCoreApplication.
That said, is it possible to postpone the execution of a routine to the event handling start (in which to instantiate a QProcess), or the only viable way is to create a one shot QTimer?
|
After a short investigation it comes out the method QCoreApplication::processEvents() that processes all pending events for the calling thread. In the following code
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QProcess abc(....);
abc.start(...);
app.processEvents();
//////////////////////////////////////////////////////
// is the process really running ? //
//////////////////////////////////////////////////////
return app.exec();
}
such method is required for the section is-the-process-really-running to let it find the abc process up and running. Otherwise abc will be started when the event loop processes the start event.
|
268,023
| 268,047
|
What’s the best way to check if a file exists in C++? (cross platform)
|
I have read the answers for What's the best way to check if a file exists in C? (cross platform), but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all.
Both stat and access are pretty much ungoogleable. What should I #include to use these?
|
Use boost::filesystem:
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.