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". ... | 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... |
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 softwar... | 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. Wi... |
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 ... |
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 ... | 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
Multipl... |
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... |
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 s... | 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 mu... |
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 li... | 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 con... | 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 necessar... |
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 usin... | 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 modif... |
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 a... | 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 activat... | 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_ACTIV... |
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 i... | 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 behav... |
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
F... | 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... |
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 t... | 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++... |
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 v... | 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 TimeL... | 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
... | 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]; };
... |
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:... | 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 cla... |
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.
Unfortunat... | "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 (... |
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... | 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 i... |
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(... | 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 };
... |
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 c... | 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 facil... | 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:... |
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_ma... | 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... | 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... | 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 th... |
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... | 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 ... |
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.came... | 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 f... |
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);
hb... | 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.... |
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 ... | 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? ... | 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] =... |
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 vo... | 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 care... |
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 ... |
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 shoul... | 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 poin... |
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
... | 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... |
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 tha... | 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 ... |
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 ... | 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 ... | 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 exporti... |
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 ... | 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... |
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... | 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 as... |
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... |
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 sour... | 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 fi... |
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 h... | 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(soc... |
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 terminat... |
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 con... | 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, ... |
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 f... |
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... |
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 i... | 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 ins... | 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 ... |
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.... | 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;
LPMAPIUNINITIAL... |
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 internal... | 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;
... | 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'... |
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 ... |
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 hav... | “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 ... |
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 appro... | #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... |
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, n... | 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 representation... |
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... | 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())... |
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 mo... | 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(kIMEventAle... |
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... | 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... |
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>... | 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 righ... |
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 de... | 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 ... |
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... | 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 cou... |
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 thes... | 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 T... |
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.en... | 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<SomeTy... |
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);
co... |
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 th... | 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]
/ERRORRE... |
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 cr... | 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 clas... |
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... |
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)... | 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 prefer... | 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'... |
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::... | 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 r... |
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 m... |
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 implem... | 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... |
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 ... | 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 & );
templ... |
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 pu... | 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/ASubComponentW... |
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 d... | 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 ... |
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... | 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 {
... |
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 rea... | 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.... |
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 ... | 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&) thro... |
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 ba... | 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 ma... |
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... |
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 all... | 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 a... |
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... | 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... |
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 uncl... |
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 QCoreAppli... | 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();
/////... |
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.