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 |
|---|---|---|---|---|
1,590,905 | 1,590,968 | Is it possible to change a background color of an edit control inside edit? | I am writing a GUI wrapper for windows api right now ( i can't use qt or mfc ). The library itself is extremely basic. After subclassing windows common controls ( and wrapping them into the classes ) i have faced a problem. As far as i know (and i hope i am wrong), only parent control can handle a message like WM_CTLCO... | You can do it, but it is a fair amount of work. The basic idea is that you create another window to act as the parent to the control you're subclassing. In that, you keep track of whether a notification message (e.g. WM_CTLCOLOREDIT) is being handled by the parent or the sub-classed control itself. If it's being handle... |
1,590,961 | 1,591,088 | Call class member function in VC++ debugger | A while ago I read the Debugging Windows Programs book, and one of the tricks that it talked about extensively was calling functions from the Visual C++ debugger (quick)watch window.
As luck would have it, I don't have a copy on hand and the little documentation that I could find about this is really really poor.
So ho... | It works and is hugely useful. You can evaluate expressions in the watch window or open the quick watch window (ctrl-alt-Q -- a very handy shortcut to know). It will let you call most forms of member functions. The only times it commonly tends to fail is if you've got overloaded operators, eg with smart pointers. For... |
1,591,018 | 1,591,039 | std::vector::clear() in constructor and destructor | I encounter many times with code where std::vector::clear() of class member of type std::vector is called in constructor and destructor.
I don't see why it's required:
constructor - the class member of type std::vector is empty by default, so no need to call clear().
destructor - the class member of type std::vector ... | From the sound of things, the people who wrote that code were the ones who missed something. The only time it would make sense to call clear() in a ctor or dtor would be in the middle of some other code. For example, a ctor might read in some data, process it, then read in more data. In such a case, it's probably faste... |
1,591,114 | 1,591,148 | Embedded scripting engine for DSL | I'm working on a project which needs an embedded DSL to fullfill its expected requirements.
The DSL would be user defined event based. Here goes a mockup of the desired syntax:
user-defined-event-1 {
// event body
}
user-defined-event-2 {
// event body
}
Probably, most similar language I know based on events ... | There's at least a few Qt-Lua bindings out there. Lua can somewhat do the syntax you've shown above; specifically, {} indicates a table (associative array) in Lua, and if you are only passing an anonymous table to a function, you don't need parentheses:
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> function Le... |
1,591,217 | 1,591,235 | What is the meaning of leading underscores in a C++ constructor? | OK I am not a very experienced C++ programmer, but I was wondering what is the significance of the underscores in the arguments of the following constructor?
class floatCoords
{
public:
floatCoords(float _x, float _y, float _width, float _height)
: x(_x), y(_y), width(_width), height(_height)
{
}
float ... | It's just a convenient naming convention, it means nothing to the language. Just be sure you don't follow it with an upper-case letter: What does double underscore ( __const) mean in C?
|
1,591,218 | 1,595,087 | How can i compile boost::spirit for unsigned char type? | boost::spirit asserts at
boost::spirit::char_class::ascii::isalnum()
when passing ascci characters > 127.
I changed all my private variables from std::string to a
typedef std::basic_string<unsigned char, std::char_traits<unsigned char>, std::allocator<unsigned char> >
u_string;
but still boost uses std:.string ... | The solution is quite simple:
instead of
using namespace boost::spirit::ascii;
i now use
using namespace boost::spirit::iso8859_1;
This recognizes all charcters in the iso8859 character set.
|
1,591,269 | 1,591,283 | Using an abstract class to implement a stack of elements of the derived class | I have to do this for a basic C++ lecture at my university, so just to be clear: i would have used the STL if i was allowed to.
The Problem: I have a class named "shape3d" from which i derived the classes "cube" and "sphere". Now i have to implement "shape3d_stack", which is meant be able of holding objects of the type... | You can't create objects from abstract classes.
You'll probably want to create an array of pointers to the abstract class, which is allowed, and fill them with derived instances:
// declaration somewhere:
shape3d** array_;
// initalization later:
array_ = new shape3d*[size];
// fill later, triangle is derived from sh... |
1,591,444 | 1,591,761 | Creating a Windows Forms Control (C++) | trying to run this basic form control example on msdn.
At step 1 of the portion "To add a custom property to a control" we place the ClickAnywhere code in the public section of the class.
First error: "error C2144: syntax error : 'bool' should be preceded by ';'"
Is this syntax correct in C++? (see below)
(remov... | Since you are using Visual Studio .Net 2003, you are using Managed C++, not C++/CLI. There is a significant difference in syntax. For a property, you must use the __property keyword, not the C++/CLI property keyword and its new style.
It should therefore be:
__property bool get_ClickAnywhere() {
return (label1->Doc... |
1,591,547 | 1,591,559 | Template classes and their methods | Linking my program produces a bunch of errors like below.
/home/starlon/Projects/LCDControl/DrvQt.cpp:8: undefined reference to `Generic<LCDText>::Generic(Json::Value*, int)'
/home/starlon/Projects/LCDControl/DrvQt.cpp:18: undefined reference to `Generic<LCDText>::~Generic()'
/home/starlon/Projects/LCDControl/DrvQt.cpp... | More code to debug would be nice, please post some code as that debug message is not enough to go with (for me atleast).
For now, It sounds like an undefined reference so you might want to make sure that the declaration and implementation of the template class is in the same file. Not separated into a .hpp and .cpp as ... |
1,591,568 | 1,591,638 | Signal and Slot vs Multithreading in Boost Library | I have gone through similar questions on Stackoverflow but still can't get a good answer:
how boost implements signals and slots
How signal and slots are implemented
I am quite puzzled on how this signal/slot is achieved.
Q1: From the following code, sig is connected to two function(Hello() and World()), and it seem... | Q1:
The calls are serialized. What signals are doing internally is, greatly simplified:
foreach connection:
call handler
Therefore you don't want to block in the handlers for long. If you need to do much work you can invoke it from there though, for example by creating a thread for it.
Q2:
boost signals 1 isn't even... |
1,591,591 | 1,591,713 | Can one leverage std::basic_string to implement a string having a length limitation? | I'm working with a low-level API that accepts a char* and numeric value to represent a string and its length, respectively. My code uses std::basic_string and calls into these methods with the appropriate translation. Unfortunately, many of these methods accept string lengths of varying size (i.e. max(unsigned char),... | you can pass a custom allocator to std::basic_string which has a max size of whatever you want. This should be sufficient. Perhaps something like this:
template <class T>
class my_allocator {
public:
typedef T value_type;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type... |
1,591,779 | 1,591,883 | Why should I use Apache C++ Standard Library rather than any other STL implementation along with Boost? | What benefits do I get from Apache C++ standard library that I don't get from STL implementations that come with the compiler and from Boost libraries?
|
The Apache C++ Standard Library
project is a complete implementation
of the ISO/IEC 14882 C++ Standard
Library.
The most distinguishing characteristic
of this implementation of the C++
Standard Library is its portability to
a large number of C++ compilers,
operating systems, and hardware
architectures.... |
1,591,873 | 1,592,035 | How do I write a cpp __DIR__ macro, similar to __FILE__ | The __FILE__ and __LINE__ macros are built into the C Pre-Processor, and are often used for printing debug output with file names and line numbers. I need something similar, but with just the name of the directory at the end of the path. For instance if my code is in:
/home/davidc/some/path/to/some/code/foo/bar I need ... | If you are using GNU make to build your project, then you might be able to do something like this:
%.o: %.cpp
$(CC) $(CFLAGS) -D__DIR__="$(strip $(lastword $(subst /, , $(dir $(abspath $<)))))" -c $< -o $@
That has to be about the most God-awful thing that I have thought about doing in a Makefile in quite a while.... |
1,591,924 | 1,591,989 | using namespace issue | When I use the following
#include <map>
using namespace LCDControl;
Any reference to the std namespace ends up being associated with the LCDControl name space.
For instance:
Generic.h:249: error: 'map' is not a member of 'LCDControl::std'
How do I get around this? I didn't see anything specific to this on any docume... | It looks like there's a std namespace within LCDControl that's hiding the global std namespace. Try using ::std::map instead of std::map.
I would say that either there's a using namespace std somewhere within the LCDControl namespace, or possibly there's an #include of a STL header that defines std within the LCDContr... |
1,592,039 | 1,593,484 | recursively find subsets | Here is a recursive function that I'm trying to create that finds all the subsets passed in an STL set. the two params are an STL set to search for subjects, and a number i >= 0 which specifies how big the subsets should be. If the integer is bigger then the set, return empty subset
I don't think I'm doing this correct... | From what I understand you are actually trying to generate all subsets of 'i' elements from a given set right ?
Modifying the input set is going to get you into trouble, you'd be better off not modifying it.
I think that the idea is simple enough, though I would say that you got it backwards. Since it looks like homewo... |
1,592,277 | 1,593,006 | Conversion from unsigned to signed type safety? | Is it safe to convert, say, from an unsigned char * to a signed char * (or just a char *?
| The access is well-defined, you are allowed to access an object through a pointer to signed or unsigned type corresponding to the dynamic type of the object (3.10/15).
Additionally, signed char is guaranteed not to have any trap values and as such you can safely read through the signed char pointer no matter what the v... |
1,592,360 | 1,592,411 | C++ writing string to file = extra bytes | I am using c++ to look through 256 counts and write the ASCII representative to a file.
If i use the method of generating a 256 character string then write that string to the file, the file weighs 258bytes.
string fileString = "";
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i+... | Both of these create a 256 byte file:
#include <fstream>
#include <string>
int main(void)
{
std::ofstream file("output.txt", std::ios_base::binary);
std::string fileString;
for(int i = 0; i < 256; i++)
{
fileString += static_cast<char>(i);
}
file << fileString;
}
And:
#include <fstre... |
1,592,476 | 1,592,854 | Why isn't std::string::max_size() == std::string::allocator::max_size() | Recently I've noticed that the following statement is not true given std::string s.
s.max_size() == s.get_allocator().max_size();
I find this interesting, by default std::string will use std::allocator<char> which has a theoretical limit of size_type(-1) (yes i know I'm assuming 2's complement, but that's unrelated to... | In Microsoft Connect was posted bug related to your question. Microsoft has interesting answer to it:
We've resolved it as By Design according to our interpretation of the Standard, which doesn't clearly explain what the intended purpose for max_size() is. Allocator max_size() is described as "the largest value that c... |
1,592,535 | 1,592,545 | Operator new and bad_alloc on linux | On Linux, malloc doesn't necessarily return a null pointer if you're out of memory. You might get back a pointer and then have the OOM killer start eating processes if you're really out of memory. Is the same true for c++'s operator new or will you get the bad_alloc exception?
| The same is true for operator new, alas :^(
|
1,592,632 | 1,592,652 | De-referencing null in VS with Windows 7 | I have noticed that when I was running Windows XP, if my code dereferenced null I would get a crash in debug and I could then easily identify where the bug was coming from. It seems that in Windows 7 (I'm running 64-bit), instead of crashing or creating any sort of notification, the code will simply break its current ... | The access violation exception is probably being caught by something higher up in the program. If you're using MSVC, under your "debug" menu, look at "Exceptions..." and make sure that "Access violation" is checked (to tell the debugger to give you a first-chance break when the exception is thrown, before it gets perco... |
1,592,690 | 1,592,721 | Setting a timeout when using connect() in C++ | I'm using sockets in c++ on linux to connect to a server using connect(), but it doesn't seem to have a timeout value. What would be the easiest/best way to give it a timeout of a few seconds. I'll post the code I have up to, and including, the blocking call to connect():
using namespace std;
int main( int argc, char... | Make the socket a non-blocking socket, and then use select() or poll() with a timeout value to check for writability. If the select() returns with a timeout you did not connect in time, and you can close the socket and deal with the connection failure. If it returns with a completion, everything is fine and you can p... |
1,592,901 | 1,600,458 | n-values UUID generator, reusable IDs | I need a simple UUID generator.
The ID is required to be unique for this single instance.
Another requirement is, that it has n hashes coexisting at a time, and being releasable.
I don't know wether this fits the UUID concept or not.
I allrdy thought about a Stack with n-values using pop and push, but this practice see... | Universally Unique Identifiers (UUID) / Globally Unique Identifier (GUID)
The problem of generating unique IDs can be broken down as uniqueness over space and uniqueness over time which, when combined, aim to produce a globally unique sequence.
UUIDs are officially and specifically defined as part of the ISO-11578 stan... |
1,592,930 | 1,594,593 | Send command to service from C++ | how can I send command to a Windows service from C++? Equivalent .NET code is:
ServiceController sc = new ServiceController("MyService");
sc.ExecuteCommand(255);
| From native C++, you will need to:
Open a handle to the service control manager,
Use the service control manager to obtain a service handle for the service you want to control,
Send a control code or codes to the service, and
Close the handles opened in steps 1 and 2.
For example, this code restarts the time synchron... |
1,593,039 | 1,593,118 | load libavcodec in Qt-Projekt | I want to include the libavcodec in my Qt-project.
Should I do that with
#include <ffmpeg/libavcodec.h>
or with something more Qt, for example
QLibrary mylib("libavcodec");
And also a question to understand if I really got it: To use libavcodec, do I need to import the source-files or the .dll?
| You should use libavcodec like any other library. That is, include it's headers and link against it's import library. If you are using qmake, you will need to modify the INCLUDEPATH and LIBS variables, see the documentation for some examples.
The QLibrary option is only useful for DLLs that you want to load at run-time... |
1,593,231 | 1,593,297 | Possible to use precompiled headers with MIDL generated files? | We do have a project wich uses the MIDL tool to create specific header/iid and proxy files. Those files are compiled and linked with the rest of the project using a post build step that calls nmake.
Is it possible to use precompiled headers with thos IDL generated files? How can I inject #include "stdafx-h" and remove ... | Use the /FI option (Force Include): "This option has the same effect as specifying the file with double quotation marks in an #include directive on the first line of every source file specified on the command line, in the CL environment variable, or in a command file."
It won't remove the other headers, but this is not... |
1,593,233 | 1,593,241 | How can I call a masked function in C++? | Let's say I have this C++ code:
void exampleFunction () { // #1
cout << "The function I want to call." << endl;
}
class ExampleParent { // I have no control over this class
public:
void exampleFunction () { // #2
cout << "The function I do NOT want to call." << endl;
}
// other stuff
};
class ... | Do the following:
::exampleFunction()
:: will access the global namespace.
If you #include <ctime>, you should be able to access it in the namespace std:
std::time(0);
To avoid these problems, place everything in namespaces, and avoid global using namespace directives.
|
1,593,349 | 1,593,592 | VS2008 win32 project defaults - remove default precompiled headers | I have been through every option to try to find a way to get the IDE to let me create a new win32pject without precompiled headers. I have read every thread on this forum with the words "precpmpiled headers" in it and the closest I got was:
Precompiled Headers
Using 2008 pro (not express, althought the behaviour seems ... | You could make your own template to do this, or you could edit the default one. The relevant wizard can be found here:
C:\Program Files\Microsoft Visual Studio 9.0\VC\VCWizards\AppWiz\Generic\Application
Obviously if you're gonna edit the default template, backup the folder first.
I'll show you how to get started on e... |
1,593,580 | 1,593,588 | C++ how to get the address stored in a void pointer? | how can i get the memory address of the value a pointer points to? in my case it is a void pointer.
just assigning it to an uint gives me this error:
Error 1 error C2440: 'return' : cannot convert from 'void *' to 'UInt32'
thanks!
| std::size_t address = reinterpret_cast<std::size_t>(voidptr);
// sizeof(size_t) must be greater or equal to sizeof(void*)
// for the above line to work correctly.
@Paul Hsieh
I think it is sufficient to convert void* to size_t in this specific question for three reasons:
The questioner didn't specify if he
wants a p... |
1,593,737 | 1,593,763 | ImageList and BltBit - ting | I am having trouble in CE BltBit from a previously created compatable hdc to device's hdc.
The following code works:
hdc = pdis->hDC;
FillRect(hdc, &(pdis->rcItem), (HBRUSH)GetStockObject(BLACK_BRUSH));
ImageList_Draw(himl, imageIndex, hdc, 15 , 30, ILD_NORMAL);
However the following just draws the black rectangl... | CreateCompatibleDC doesn't do what you think it does. From the linked page:
Before an application can use a memory device context for drawing operations, it must select a bitmap of the correct width and height into the device context. This may be done by using CreateCompatibleBitmap to specify the height, width, and c... |
1,594,187 | 1,594,213 | How does function-style cast syntax work? | I guess I am a bit puzzled by the syntax. What does the following mean?
typedef char *PChar;
hopeItWorks = PChar( 0x00ff0000 );
| It is equivalent to (PChar) 0x00ff0000 or (char *) 0x00ff0000. Syntactically think of it as invoking a one-argument constructor.
|
1,594,582 | 1,594,619 | C format specifier question | While I was working i came across a code which was written by somebody else.
i see a statement as ,
sprintf(o_params->o_file_name,
"%s_%s_%04.4d_%s_%s.ASC",
"OUTD", "RM", sequence_no, DateStamp_buf1, TimeStamp_buf1
);
In the above statement, I see %04.4d. Is this a correct format specifier?
The varia... | From the FreeBSD manpage man 3 printf
An optional precision, in the form of
a period . followed by an optional
digit string. If the digit string is
omitted, the precision is taken as
zero. This gives the minimum number
of digits to appear for d, i, o, u,
x, and X conversions, the number of
digits to... |
1,594,607 | 1,594,646 | index operator constness | Why do we need two? Under which circumstance each of the following operator[]s are called?
class X {
public:
//...
int &operator [](int index);
const int &operator [](int index) const;
};
| foo( X x )
{
x[0]; // non-const indexer is called
}
bar ( const X x )
{
x[0]; //const indexer is called
}
|
1,594,631 | 1,594,669 | std::map difference between index and insert calls | What is the difference between the index overloaded operator and the insert method call for std::map?
ie:
some_map["x"] = 500;
vs.
some_map.insert(pair<std::string, int>("x", 500));
| I believe insert() will not overwrite an existing value, and the result of the operation can be checked by testing the bool value in the iterator/pair value returned
The assignment to the subscript operator [] just overwrites whatever's there (inserting an entry if there isn't one there already)
Either of the insert an... |
1,594,746 | 1,594,788 | Win32 equivalent of getuid() | I'm in the process of porting a C++ library from Linux to Windows, and am having problems with getuid(), which is not supported in Windows.
Any ideas what I can use in its place?
| You can retrieves the name of the user associated with the current thread with GetUserName :
// ANSI version
string GetWindowsUserNameA()
{
char buffer[UNLEN + 1] = {0};
DWORD buffer_len = UNLEN + 1;
if (!::GetUserNameA(buffer, & buffer_len))
{
// error handling
... |
1,594,803 | 1,595,552 | Is std::string thead-safe with gcc 4.3? | I'm developing a multithreaded program running on Linux (compiled with G++ 4.3) and if you search around for a bit you find a lot of scary stories about std::string not being thread-safe with GCC. This is supposedly due to the fact that internally it uses copy-on-write which wreaks havoc with tools like Helgrind.
I've ... | Threads are not yet part of the standard. But I don't think that any vendor can get away without making std::string thread-safe, nowadays. Note: There are different definitions of "thread-safe" and mine might differ from yours. Of course, it makes little sense to protect a container like std::vector for concurrent acce... |
1,594,809 | 1,594,955 | Convert float array image to a format usable for opencv | i wonder if there is a easy way to convert my float array image to iplimage,
which can be handled by opencv. Of course i could create an empty iplimage with the same size and just copy ever pixel from my float array image to the emplty iplimage, but is there more elegant solution to this. Maybe a faster less memory con... | You can do something like this (assuming 32 bit floats):
float* my_float_image_data;
CvSize size;
size.height = height ;
size.width = width;
IplImage* ipl_image_p = cvCreateImageHeader(size, IPL_DEPTH_32F, 1);
ipl_image_p->imageData = my_float_image_data;
ipl_image_p->imageDataOrigin = ipl_image_p->imageData;
|
1,594,841 | 1,594,860 | Which language to use for implementing few Linux shell commands (homework) - plain C or C++? | I need to implement a few commands of Linux shell for my homework - 5 or 6 of them, including ls. Do not know much about which parameters to implement for each of commands...
I planned to use C++, but when I asked my colleague for advice what language to choose - plain C or C++, he said that interpreter was not a prog... | First: Use what you know.
There is no reason to enter uncharted waters if you can get there with a familiar route.
C++ is a very viable option in your circumstance, anyways. So, you aren't making a mistake to just use it.
Second: Your friend is wrong. (I would use harsher words, but I'll be nice.)
C++ and C are both c... |
1,594,949 | 1,594,965 | What is a good book/guide for socket programming in C? | Could anybody please tell me which is best guide/book/material for socket programming in C?
I am reading beej's guide for network programming but it just gives an overview.
Can you suggest any other books or guides?
| UNIX Network Programming, Volume 1, Second Edition: Networking APIs: Sockets and XTI.
Then go from there.
|
1,595,063 | 1,595,127 | How could a pointer to a structure be an array? | This is really a noob quick question.
Imagine you have a struct called "No" and the following piece of code:
No *v_nos; // What does this mean?
Where I took this from they were calling "v_nos" a array? Isn't it simply a pointer to a struct "No"?
Thanks.
| In terms of implementation, arrays and pointers are the same. That is, arrays are simply implemented as pointers to the first element in the array. The difference between
No *v_nos;
and
No v_nos[3];
Is that the latter sets aside memory for 3 elements for that array, while the pointer would need to have memory allocat... |
1,595,085 | 1,595,159 | How to implement automatically select item in a html and click submit? | I have a website, and username and password,
and usually I will login the website with the username and password, and select some items in check boxes and submit them to execute actions.
but right now i need to write a application to select the checkbox by some keywords and submit them automatically.
Do anyone have go... | You may be interested in HttpUnit.
|
1,595,270 | 13,337,612 | how does the stl's multimap insert respect orderings? | I have some data which come with a integer index. I am continuous generating new data which needs to added to the collection of data I have, sorted by that index, at the same time I want to easily be able to go the start of the data and iterate through it. This sounds like std::multimap is just what I need.
However, ... | It seems the new standard (C++11) changed this:
The order of the key-value pairs whose keys compare equivalent is the order of insertion and does not change.[cppreference]
I'm hesitating to use it though, as this seems like a detail easily overlooked when modifying the standard library to be C++11 compliant and it's ... |
1,595,355 | 1,595,414 | syncing iostream with stdio | I am trying to add iostream to the legacy code and thus want to sync those two libraries.
According to this article, I should use std::ios_base::sync_with_stdio.
Now, I wonder how it is used in practice (examples please), side-effects I should be aware of.
Thx
| By default the streams are synchronized, it's guaranteed to work by the standard, you don't have to do anything. sync_with_stdio is only here to disable synchronisation if you want to.
From the article you mentioned :
For the predefined streams, it's safe
to mix stdio and iostreams. For
example, you can safely us... |
1,595,439 | 1,595,462 | User Interface clarifications | As you know, many programs are written in C++.
Some of these have fancy GUI with non-classical-Windows style ( think to Photoshop, 3ds max, maya etc )..now my question is: how are they done? In pure Win32 API? MFC? DirectX/OpenGL? or other?
I can reach similar results with C#/WPF but how can I do it in C++?
| Read Programming Windows by Petzold
In my experience, it seems to be the most practical way to learn Win32 programming.
If you care about cool effects, Petzold can definitely help you. After you're somewhat familiar with win32, you can skip to the chapter in Petzold to bitblt'ng and doing animation. I had to do some fa... |
1,595,859 | 1,596,017 | Why is non-type template parameter expression handling inconsistent across compilers? | Here is something I observed across various compilers. It seems there are compiler bugs.
template <int I>
struct X
{ };
int main(void)
{
X<(16 > 1)> a; // Works on vc9, works on g++ 4.1.2, works on Comeau 4.3.10.1
X<(int(16) > 1)> b; // Works on vc9, works on g++ 4.1.2, works on Comeau 4.3.10.1
X<(16 >> 1... | The rules are as follows for C++03:
After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is always taken as the beginning of a template-argument-list and never as a name followed by the less-than operator. When parsing a template-id, the first non-nested > [foot-note: A... |
1,596,053 | 1,596,120 | Inlining std::inner_product | Allegedly inlining std::inner_product() does NOT get inlined with gcc compiler < gcc 4.1
compilers, per the following bug .
Hence I would like to implement my own version of inner_product. Are
there existing implementation available?
Thanks
| You just need to look in your C++ header files, find the definition, and redefine it with the "inline" keyword (possibly in your namespace). For example, looking at my headers:
template <class T1, class T2, class T> inline T inner_product(T1 first1, T1 last1, T2 first2, T init)
{
for (; first1 != last1; ++first1, ++f... |
1,596,104 | 1,596,666 | How to change the color of a textual cue when sending an EM_SETCUEBANNER Message? | When you send an EM_SETCUEBANNER message, you get a grey textual cue in your edit control. How do you change the color of the textual cue in Win32/C ?
| Edit controls do not support custom cue banner colors. You will have to subclass the Edit control and custom-draw it manually to get that kind of effect.
|
1,596,117 | 1,603,591 | "Don't show this again" option in message boxes | In C++/MFC, what's the simplest way to show a message box with a "Don't show this again" option?
In my case, I just want a simple MB_OK message box (one OK button).
| Or just use the SHMessageBoxCheck() function.
|
1,596,239 | 1,596,326 | Simple Flex/Bison C++ | I already looked for my answer but I didn't get any quick response for a simple example.
I want to compile a flex/bison scanner+parser using g++ just because I want to use C++ classes to create AST and similar things.
Searching over internet I've found some exploits, all saying that the only needed thing is to declare ... | You need the extern "C" {} for yylex to be in shady.l:
%{
extern "C"
{
int yylex(void);
}
#include "shady.tab.h"
%}
%%
"MOV"|"mov" { return T_MOV; }
"NOP"|"nop" { return T_NOP; }
...etc...
Also, after adding a dummy grammar rule, I was able to build and run this with just:
559 flex shady... |
1,596,401 | 1,596,480 | C++ Serial Port Question | Problem:
I have a hand held device that scans those graphic color barcodes on all packaging. There is a track device that I can use that will slide the device automatically. This track device functions by taking ascii code through a serial port. I need to get this thing to work in FileMaker on a Mac. So no terminal pro... | Sending a ^ and then a M doesn't send control-M, thats just the way you write it,
to send a control character the easiest way is to just use the ascii control code.
ps. ^M is carriage return ie "\r" and ^J is linefeed "\n"
edit: Probably more than you will (hopefully) ever need to know - but read The Serial Port... |
1,596,432 | 1,596,448 | Getter and setter, pointers or references, and good syntax to use in c++? | I would like to know a good syntax for C++ getters and setters.
private:
YourClass *pMember;
the setter is easy I guess:
void Member(YourClass *value){
this->pMember = value; // forget about deleting etc
}
and the getter?
should I use references or const pointers?
example:
YourClass &Member(){
return *this->pMem... | As a general law:
If NULL is a valid parameter or return value, use pointers.
If NULL is NOT a valid parameter or return value, use references.
So if the setter should possibly be called with NULL, use a pointer as a parameter. Otherwise use a reference.
If it's valid to call the getter of a object containing a NULL ... |
1,596,575 | 1,596,583 | Good C++ Debugging/IDE Environment for Linux? | I have a friend who is trying to make the switch to Linux, but is hung up on the apparent lack of debugging/IDE environments for C++, especially as they relate to template programming. He has been using visual studio for years and is maybe a little spoiled by their awesome IDE. Does anyone have any good suggestions for... | Although many people think of it as a Java IDE, he could try NetBeans. I've used it on Windows for C and C++ development without a problem, and I know NetBeans is supported on Linux, so it would be worth a shot.
It looks like most of the features he wants are included in the C/C++ development toolkit, including integra... |
1,596,594 | 1,596,605 | C++ Template + Iterator (noob question) | My disclaimer here is that I started teaching myself C++ about a week ago and my former experience with programming has been with dynamic languages (Python, javascript).
I'm trying to iterate though the contents of a vector using a generic function to print out the items:
#include <iostream>
#include <algorithm>
#inclu... | Try:
for_each(myV.begin(), myV.end(), p<int>);
There were two mistakes in your code:
The iterators were not the same type
The function pointer was not actually a pointer.
Normally templated functions can be deduced from there parameters. But in this case you are not actually using it you are passing it (or its addr... |
1,596,668 | 1,596,681 | Logical XOR operator in C++? | Is there such a thing? It is the first time I encountered a practical need for it, but I don't see one listed in Stroustrup. I intend to write:
// Detect when exactly one of A,B is equal to five.
return (A==5) ^^ (B==5);
But there is no ^^ operator. Can I use the bitwise ^ here and get the right answer (regardless of ... | The != operator serves this purpose for bool values.
|
1,596,691 | 1,596,807 | cvCanny and float 32 bit (IPL_DEPTH_32F) problem | I have some problems with OpenCVs cvCanny(...) and the Image data types it can handle. Well, maybe you guys/gals know a solution.
I have a 32 bit float image and I want to perform cvCanny on it.
The problem is cvCanny can only handle "IPL_DEPTH_8S" or U (signed / unsigned short), or at least that's what I suspect. The... | Sorry, since cvCanny only supports single-channel 8-bit images, the only thing I can think of is to scale each value in your image by 255/16 into a new image of type CV_8UC1 so that it ranges from 0 - 255 to minimize the precision you've lost.
|
1,596,837 | 1,596,877 | Can I create an anonymous, brace-initialized aggregate in C++? | One can create an anonymous object that is initialized through constructor parameters, such as in the return statement, below.
struct S {
S(int i_, int j_) : i(i_), j(j_) { }
int i, j;
};
S f()
{
return S(52, 100);
}
int main()
{
cout << f().i << endl;
return 0;
}
However, can one similarly create an anony... | You can't in the current version of C++. You will be able to in C++ 0x -- I believe anyway. Of course, it's still open to revision -- at one time I believed you'd be able to specify concepts in C++ 0x, but that's gone...
Edit: The reference would be [dcl.init] (§8.5/1) in N2960. The most relevant bit is the definition ... |
1,597,373 | 1,597,412 | Getters without shared ownership | How to write a getter that can not be deleted?
I want to own the variables and not share them.
reading here and there I figured out that no matter what I return the memory can be freed
however I define it, is this true?
references, const pointers, no matter what, the function which is calling the getter can delete it a... | Depends on what you mean. Any time you have a pointer, it is possible to call delete on it.
And if you have a reference, you can take the address of it, which gives you a pointer
Anyway, if you have this class for example:
class X {
int getByVal() { return i; } // returns a copy of i
int& getByRef() { return i; } /... |
1,597,503 | 1,597,520 | derive from an arbitrary number of classes | I have a class whose functionality I'd like to depend on a set of plug-in policies. But, I'm not sure how to get a class to derive from an arbitrary number of classes.
The code below is an example of what I'm trying to achieve.
// insert clever boost or template trickery here
template< class ListOfPolicies >
class CM... | With the Boost.MPL library:
//Warning: Untested
namespace bmpl = boost::mpl;
template<class Typelist>
class X : bmpl::inherit_linearly<Typelist, bmpl::inherit<bmpl::_1, bmpl::_2> >::type
{
...
};
Used as:
X<bmpl::vector<Foo, Bar, Baz> > FooBarBaz;
For the "OR-ing all MY_IDENTIFIER" part, something along the lines of ... |
1,597,695 | 1,597,721 | Make my C++ Class iterable via BOOST_FOREACH | I have a class which I want to expose a list of structs (which just contain some integers).
I don't want the outside to modify these data, just iterate over it and read them
Example:
struct TestData
{
int x;
int y;
// other data as well
}
class IterableTest
{
public:
// expose TestData here
};
now in my c... | It sounds like you have to write your own iterators.
The Boost.Iterator library has a number of helpful templates. I've used their Iterator Facade base class a couple of times, and it's nice and easy to define your own iterators using it.
But even without it, iterators aren't rocket science. They just have to expose th... |
1,597,827 | 1,598,151 | using boost::mpl::bitor_ | I have a class that accepts a list of policy classes using boost::mpl. Each policy class contains an identifying tag. I would like MyClass to produce the OR-ed result of each policy class' identifying tag. Unfortunately, I'm having some trouble figuring out how to correctly use the boost::mpl::fold<> functionality. If ... | I haven't explicitly tested if it does what you intend to (aside from not getting the assert), but as fold returns a type containing a value, the line giving you an error should be:
return bmpl::fold< ListOfPolicies,
bmpl::int_<0>,
bmpl::bitor_<bmpl::_1, bmpl::_2>
... |
1,598,207 | 1,598,217 | Odd Circular Dependency Issue | So I have 2 classes, Bullet and Ship, that are dependent on each other, hence circular inclusion. Since I have Ship's interface #included into Bullet's interface, the obvious decision was to forward declare Bullet to Ship.
However, when I first tried this I still got compiler errors. I read up a bit on forward declarat... | You want:
Bullet fired_bullet(*this);
But your coupling is very tight. What does Bullet need from Ship, and what does Ship need from bullet?
I assume the bullet needs to know what ship it came from so enemy bullets don't hurt enemy's and vice versa. Perhaps you need a team type?
enum bullet_team
{
bullet_player,
... |
1,598,351 | 1,598,678 | emacs, etags and using emacs as an IDE | My usual tools are Emacs with g++ on a Linux system to implement my research algorithms. For the last some years, I have used emacs in a fairly basic way. I open C or C++ files, edit them with a syntax highlighting scheme of my choice and compile and do other stuff from within emacs (or maybe from a terminal), includin... | For just tagging info, I also recommend GNU Global. CScope can do a lot also. In both cases, they provide a way to find the location of a tag by name, and also the uses of a particular tag.
For "IDE Stuff" there is more to it than just a tagging system. For that, I recommend the CEDET set of tools for Emacs. This p... |
1,598,397 | 1,598,409 | Creating array of objects on the stack and heap | Consider the following code:
class myarray
{
int i;
public:
myarray(int a) : i(a){ }
}
How can you create an array of objects of myarray on the stack and how can you create an array of objects on the heap?
| You can create an array of objects on the stack† via:
myarray stackArray[100]; // 100 objects
And on the heap† (or "freestore"):
myarray* heapArray = new myarray[100];
delete [] heapArray; // when you're done
But it's best not manage memory yourself. Instead, use a std::vector:
#include <vector>
std::vector<myarray> ... |
1,598,514 | 1,598,994 | Infinite loop on EOF in C++ | This code works as desired for the most part, which is to prompt the user for a single character, perform the associated action, prompt the user to press return, and repeat. However, when I enter ^D (EOF) at the prompt, an infinite loop occurs. I am clearing the error state via std::cin.clear() and calling std::cin.i... | You should always check whether any of a stream's failure flags are set after calling formatted extraction operation, in your example you are checking response without checking whether response was correctly extracted.
Also, you are using std::endl in your prompt output where it doesn't make sense. std::endl prints \n ... |
1,598,673 | 1,598,760 | Dynamic arrays size and dynamic arrays allocators in VC++ | I'm confused a little while writing own tiny discovering program to clear up how Visual C++ allocates the memory for dynamic arrays. I must note, I have never met technical documents that describe this question on new[]/delete[] operators for any C++ implementation.
Initially I thought that new[] and delete[] are somet... | I'm not sure what you are looking for here but fake_int_ctor(int) is printing uninitialized memory in the allocated array. Try something like this instead:
void fake_int_ctor(int& _this) {
printf("born at %p\n", (void*)&_this);
}
void fake_int_dtor(int& _this) {
printf("dies at %p\n", (void*)&_this);
}
This ... |
1,598,703 | 1,598,977 | Profiling DLL/LIB Bloat | I've inherited a fairly large C++ project in VS2005 which compiles to a DLL of about 5MB. I'd like to cut down the size of the library so it loads faster over the network for clients who use it from a slow network share.
I know how to do this by analyzing the code, includes, and project settings, but I'm wondering if t... | When you build your DLL, you can pass /MAP to the linker to have it generate a map file containing the addresses of all symbols in the resulting image. You will probably have to do some scripting to calculate the size of each symbol.
Using a "strings" utility to scan your DLL might reveal unexpected or unused printable... |
1,598,710 | 1,598,758 | How to design an efficient image buffer in C++? | I am trying to create a data buffer, more specifically, an image buffer, which will be shared among multiple modules. Those modules only reads from the buffer and don't communicate with each other at all. My difficulty is:
1.Large data size:
larger than 10M per image, that means copying those data around for different... | Assuming you hand the shared_ptrs to the modules as soon as the buffer is created, they are a good fit. You don't even need to store them centrally in that case.
It gets more complicated however, if you create the buffers at one point and only at some other point later the modules request the buffer.
In that case you h... |
1,598,742 | 1,606,768 | Sending large chunks of data over Boost TCP? | I have to send mesh data via TCP from one computer to another... These meshes can be rather large. I'm having a tough time thinking about what the best way to send them over TCP will be as I don't know much about network programming.
Here is my basic class structure that I need to fit into buffers to be sent via TCP:... | Have you tried it with Boost's TCP? I don't see why 2MB would be an issue to transfer. I'm assuming we're talking about a LAN running at 100mbps or 1gbps, a computer with plenty of RAM, and don't have to have > 20ms response times? If your goal is to just get all 2MB from one computer to another, just send it, TCP w... |
1,598,807 | 1,598,842 | MapViewOfFile with pointers between threads | I have some programs that use MapViewOfFile to share data, but I am getting strange access violations that seem to be from accessing the mapped file data.
Some of the shared data has pointers, however these pointers are only set and used by one process, but by several threads within the process.
I understand that you ... | Yes, it is safe to share pointers (in mapped memory or not) between threads in the same process, since the threads share the same address space.
|
1,598,967 | 1,598,980 | Benefits of Initialization lists | Of what I know of benefits of using initialization list is that they provide efficiency when initializing class members which are not build-in. For example,
Fred::Fred() : x_(whatever) { }
is preferable to,
Fred::Fred() { x_ = whatever; }
if x is an object of a custom class. Other than that, this style is used ev... | The second version is calling string's default ctor and then string's copy-assignment operator -- there could definitely be (minor) efficiency losses compared to the first one, which directly calls c's copy-ctor (e.g., depending on string's implementation, there might be useless allocation-then-release of some tiny str... |
1,599,171 | 1,599,191 | C++ Class member access problem with templates | Ive got a problem that if I have a template class, which in turn has a template method that takes a parameter of another instance of the class (with different template arguments), that it can not access protected or private members of the class passed as a parameter, eg:
template<typename T>class MyClass
{
T v;
pub... | They are different types: templates construct new types from a template.
You have to make other instantiations of your class friends:
template <typename T>class MyClass
{
T v;
public:
MyClass(T v):v(v){}
template<typename T2>void foo(MyClass<T2> obj)
{
std::cout << v << " ";
std::co... |
1,599,382 | 1,599,391 | Is it worth passing values of "simple" types by reference? | Consider the following :
int increment1 (const int & x)
{ return x+1; }
int increment2 (const int x)
{ return x+1; }
I understand passing references to class objects an such, but I'm wondering if it's worth to pass reference to simple types ? Which is more optimal ? Passing by reference or passing by value (in case o... | Unless you need the "call by reference" semantics, i.e. you want to access the actual variable in the callee, you shouldn't use call by reference for simple types.
For a similar, more general discussion see: "const T &arg" vs. "T arg"
|
1,599,414 | 1,599,489 | Active Wait in Windows I/O Driver | Continuing the question in:
Keep windows trying to read a file
Thanks to accepted answer in that question I realized that keeping windows waiting for data is a driver responsability.
As i'm using Dokan, I am be able to look into the driver code. Dokan complete the IRP request with a STATUS_END_OF_FILE when you return n... | You should return STATUS_PENDING and set CancelRoutine for the IRP. Complete your IRP when the data is available or an error occurred. See Asynchronous I/O Responses and Canceling IRPs for more info.
|
1,599,416 | 1,599,535 | can you have a private member of the same class as the base class you're inheriting? | Im using the Qt library. I'm currently trying to create my own QDockWidget (the class MY class is inheriting). Right now MY class has an ptr to QDockWidget. Does this even make sense? is that a legal statement? is there a better way to separate the QDockWidget from the rest of my program in Qt? Im a little lost on how ... | You seem to be confusing the IS-A relationship and the HAS-A relationship.
IS-A relations are implemented by inheritance. For instance, a QWidget IS-A QObject.
HAS-A relations are implemted by members. For instance, a QWidget HAS-A size.
Now, what's the relation between the class you are trying to develop and a QDockWi... |
1,599,536 | 1,599,566 | How can I create an interface without parameterless constructor in C++? | How can I hide the default constructor from consumers? I tried to write in private but got compilation issues.
solution is:
class MyInterface
{
public:
MyInterface(SomeController *controller) {}
};
class Inherited : public MyInterface
{
private:
Inherited () {}
public:
Inherited(So... | In your case, since you have already provided a constructor that takes one parameter SomeController*, compiler doesn't provide any default constructor for you. Hence, default constructor is not available.
ie,
MyInterface a;
will cause compiler to say no appropriate constructor.
If you want to make constructor explici... |
1,599,604 | 1,620,994 | Mouse jiggling / message processing loop | I have written a multithreaded program which does some thinking and prints out some diagnostics along the way. I have noticed that if I jiggle the mouse while the program is running then the program runs quicker. Now I could go in to detail here about how exactly I'm printing... but I will hold off just for now because... | i can see 3 problems here:
the documentation for WM_PAINT says: The WM_PAINT message is generated by the system and should not be sent by an application. unfortunately i don't know any workaround, but i think SetWindowText() will take care of repainting the window, so this call may be useless.
SendMessage() is a block... |
1,599,662 | 1,715,999 | Black border around characters when draw Image to a transparent Bitmap | I have to draw a String on a transparent bitmap at first, then draw A to destination canvas.
However on certain case, there is black border around the characters.
Bitmap* tempImg = new Bitmap(1000, 1000, PixelFormat32bppARGB);
Graphics tempGr(tempImg);
tempGr.Clear(Color(0, 255,255,255));
Gdiplus::SolidBrush* brush = n... | I think the problem here is that you are drawing the text onto a transparent background.
You could try adding this line after the call to tempGr.Clear...
tempGr.TextRenderingHint = TextRenderingHint.AntiAlias;
ps - sorry not sure the exact syntax in C++ ;)
|
1,599,702 | 1,599,724 | C++ Console Application, hiding the title bar | I have a Windows console application written in C++ and want to hide/remove the complete title bar of the console window, including the close, min/max controls etc. I searched a lot but didn't found anything useful yet.
I inquire the console HWND with GetConsoleWindow and tried to change the console window style with ... | You can't. Generally the hWnd of a console window is not guaranteed to be suitable for all window handle operations as, for example, documented here.
|
1,599,869 | 1,599,942 | Project dependency in Visual Studio | In Visual Studio, I have two C++ projects - Gui.vcproj and Dll.vcproj.
Gui is an application and Dll produces a DLL.
What's the best way to make the dependency resolution automatic?
I tried adding Dll.vcproj into Gui.vcproj's references, but it doesn't seem working.
|
Create a solution
Add Gui.vcproj and Dll.vcproj to the solution
From solution explorer window, right click the solution yuo just created.
Choose Project dependencies.
Select the project you want of these two, and check the 'Depends on' check box.
|
1,599,895 | 1,599,917 | Multiple definitions of Split | Maybe I should still be in bed. I woke up wanting to program. At any rate, now I'm getting some linker errors that I'm baffled over. What do you make of all this? I hope I'm not posting too much of it. I was going to post just a piece, but that didn't feel right. I checked some of the header files mentioned in the erro... | A usual cause for multiple definitions errors like this is when you define the function in a header file without the inline keyword. Also, if the Split function you posted is from a LCD class the signature is missing the LCD:: part.
|
1,600,282 | 1,600,346 | Guideline: while vs for | Disclaimer: I tried to search for similar question, however this returned about every C++ question... Also I would be grateful to anyone that could suggest a better title.
There are two eminent loop structure in C++: while and for.
I purposefully ignore the do ... while construct, it is kind of unparalleled
I know of ... | Not all loops are for iteration:
while(condition) // read e.g.: while condition holds
{
}
is ok, while this feels forced:
for(;condition;)
{
}
You often see this for any input sources.
You might also have implicit iteration:
while(obj.advance())
{
}
Again, it looks forced with for.
Additionally, when forcing for ins... |
1,600,399 | 1,600,413 | Are C++ libs created with different versions of Visual Studio compatible with each other? | I am creating a open-source C++ library using Visual Studio 2005. I would like to provide prebuilt libs along with the source code. Are these libs, built with VS2005, also going to work with newer versions of Visual Studio (esp VS Express Edition 2008)? Or do I need to provide separate libs per VS version?
| If you are distributing static libraries, you may be able to distribute version-independent libraries, depending on exactly what you are doing. If you are only making calls to the OS, then you may be OK. C RTL functions, maybe. But if you use any C++ Standard Library functions, classes, or templates, then probably ... |
1,600,464 | 1,600,561 | templates problem ('typename' as not template function parameter) | Actually I've a problem with compiling some library with intel compiler.
This same library has been compiled properly with g++.
Problem is caused by templates.
What I'd like to understand is the declaration of
**typename** as not template function parameter and variable declaration inside function body
example:
void f... | You need to use typename for so-called "dependent types". Those are types that depend on a template argument and are not known until the template is instantiated. It's probably best explained using an example:
struct some_foo {
typedef int bar;
};
template< typename Foo >
struct baz {
typedef Foo::bar barbar; // ... |
1,600,936 | 1,600,968 | Officially, what is typename for? | On occasion I've seen some really indecipherable error messages spit out by gcc when using templates... Specifically, I've had problems where seemingly correct declarations were causing very strange compile errors that magically went away by prefixing the typename keyword to the beginning of the declaration... (For exa... | Following is the quote from Josuttis book:
The keyword typename was introduced to
specify that the identifier that
follows is a type. Consider the
following example:
template <class T>
Class MyClass
{
typename T::SubType * ptr;
...
};
Here, typename is used to clarify that
SubType is a type of class T. Th... |
1,600,939 | 1,600,976 | Storing heterogeneous objects in vector with stack-allocated objects | Storing objects in heterogeneous vector with stack-allocated objects
Hello,
Say I have an abstract class CA, derived into CA1, CA2, and maybe others.
I want to put objects of these derived types into a vector, that I embbed into a class CB. To get polymorphism right, I need to store a vector of pointers:
class CB
{
... | Commonly, you will provide a clone function:
struct CA
{
virtual CA *clone(void) const = 0;
virtual ~CA() {} // And so on for base classes.
}
struct CA1 : public CA
{
virtual CA *clone(void) const
{
return new CA1(*this);
}
}
struct CA2 : public CA
{
virtual CA *clone(void) const
{... |
1,601,008 | 1,601,044 | identify the exact header file | I am using some macro in my source file (*.c ) .
Is there any way during compilation or from the library that I can identify the exact header file from which this particular macro is getting resolved ?
The issue is we are using a macro #defined to 10 in some header file, but the value being received in the code is 4 ... | If you just run cpp (the C preprocessor) on the file, the output will contain #line directives of the form
#line 45 "silly-file-with-macros.h"
for the compiler saying where everything came from. So one way is to use
cpp my-file.c | more
and look for the #line directive.
Depending on your compiler, another trick you ... |
1,601,030 | 1,601,082 | Internet Explorer window in Qt? | Is there a way to show an Internet Explorer instance/frame inside a Qt Widget? I need to show a web page in my application (just show, no need for interaction), and while I read about WebKit for Qt, I'd like to know if there is another way without it, since I'm trying to keep the application as small as possible, and i... | Yes, you need the commercial edition of Qt and then, you can use ActiveQt.
|
1,601,060 | 1,602,142 | STL like container with O(1) performance | I couldn't find an answer but I am pretty sure I am not the first one looking for this.
Did anyone know / use / see an STL like container with bidirectional access iterator that has O(1) complexity for Insert/Erase/Lookup ?
Thank you.
| In practice, it may be sufficient to use array (vector) and defer costs of inserts and deletes.
Delete element by marking it as deleted, insert element into bin at desired position and remember offset for larger indices.
Inserts and deletes will O(1) plus O(N) cleanup at convenient time; lookup will be O(1) average, ... |
1,601,129 | 1,601,374 | DLL Injection/IPC question | I'm work on a build tool that launches thousands of processes (compiles, links etc). It also distributes executables to remote machines so that the build can be run accross 100s of slave machines. I'm implementing DLL injection to monitor the child processes of my build process so that I can see that they opened/clos... | First, since you're apparently dealing with communication between machines, not just within one machine, I'd rule out shared memory immediately.
I'd think hard about trying to minimize the amount of data instead of worrying a lot about how fast you can send it. Instead of sending millions of file I/O reports, I'd batch... |
1,601,261 | 1,601,482 | Marking library functions as deprecated/unusable without modifying their source code | I have a large codebase that uses a number of unsafe functions, such as gmtime and strtok. Rather than trying to search through the codebase and replace these wholesale, I would like to make the compiler emit a warning or error when it sees them (to highlight the problem to maintenance developers). Is this possible w... | Create a custom header deprecated.h. In there, create your own wrapper functions, deprecated_strtok() etcetera that merely call strtok. Mark those with __attribute__((deprecated)). Below those definitions, #define strtok deprecated_strtok. Finally, use -include deprecated.h
|
1,601,431 | 1,612,131 | Is Lua the best/fastest choice for a gaming server? | I am working on a project where I want users to be able to modify and customize as much as possible.
Open source might be a good choice but not due to the fact that I want to keep a few internal classes closed.
Two other options that I thought about were plug-ins as external libraries and Lua scripting.
The problem wit... | I'm afraid the only one who can answer if Lua will be fast enough for you is... you. We have no idea what exactly are you doing and how are you implementing it. My suggestion is to prototype and measure. Write a small, but relevant, part of your system in both Lua and C/C++, measure the performance of both and decide i... |
1,601,457 | 1,601,486 | C++ Interfaces in stl::list | LessonInterface
class ILesson
{
public:
virtual void PrintLessonName() = 0;
virtual ~ILesson() {}
};
stl container
typedef list<ILesson> TLessonList;
calling code
for (TLessonList::const_iterator i = lessons.begin(); i != lessons.end(); i++)
{
i->PrintLessonName();
}
The error:
D... | You can't "put" objects of a class that has pure virtual functions(because you can't instantiate it). Maybe you mean:
// store a pointer which points to a child actually.
typedef list<ILesson*> TLessonList;
OK, as others pointed out, you have to make PrintLessonName a const member function. I would add that there is ... |
1,601,598 | 1,601,891 | Confusion with the problems of inline function | In the problems of inline functions in wikipedia :
http://en.wikipedia.org/wiki/Inline_expansion#Problems
it says : "# A language specification may allow a program to make additional assumptions about arguments to procedures that it can no longer make after the procedure is inlined."
Could somebody elaborate this point... | In C++, the inline keyword really only has one required meaning: that the One-Definition Rule is suspended for that function (e.g., the function can be defined in several translation units, and the code still conforms).
Specifically, using the inline keyword does not ensure that the code for that function will be gener... |
1,601,904 | 1,602,088 | stuck in a template requirement loop | I have a class that uses an "add-on" template to add additional functionality as below:
template< class T >
class AddOn_A
{
public:
int SomeFuncA()
{
T* pT = static_cast< T* >( this );
return pT->DoSomething() + 1;
};
};
class CMyClass : public AddOn_A< CMyClass >
{
public:
int DoSomet... | Apparently you are trying to use the famous Curiously Recurring Template Pattern.
I am not sure of what you exactly want to do, but you might get away with another solution:
What if you used two classes:
class Base {};
class MyClass: public AddOn<Base> {};
You may also use a Policy Based approach:
class PolicyA_A ... |
1,601,943 | 1,601,974 | Mutex lock on write only | I have a multithreaded C++ application which holds a complex data structure in memory (cached data).
Everything is great while I just read the data. I can have as many threads as I want access the data.
However the cached structure is not static.
If the requested data item is not available it will be read from databas... | Look into read-write-lock.
You didn't specify which framework can you use but both pThread and boost have implemented that pattern.
|
1,602,058 | 1,602,165 | Why is the copy-constructor argument const? | Vector(const Vector& other) // Copy constructor
{
x = other.x;
y = other.y;
Why is the argument a const?
| You've gotten answers that mention ensuring that the ctor can't change what's being copied -- and they're right, putting the const there does have that effect.
More important, however, is that a temporary object cannot bind to a non-const reference. The copy ctor must take a reference to a const object to be able to ma... |
1,602,083 | 1,605,107 | Async operations with I/O Completion Ports return 0 bytes transferred | Asynchronous operations with I/O Completion Ports return 0 bytes transferred, although the I/O operations work as expected (my read buffers become full).
BYTE buffer[1024] = {0};
OVERLAPPED o = {0};
HANDLE file = CreateFile(
_T("hello.txt"),
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FI... | For GetIoCompletionPort to work correctly, you need to specify a non-null pointer to a ULONG_PTR for it to write the 'key' value to:
ULONG_PTR key;
GetQueuedCompletionStatus(
completion_port,
&numBytes,
&key,
&po,
INFINITE
);
To use GetOverlappedResult successfully, I believe you need to specify a... |
1,602,451 | 1,602,594 | C++ valarray vs. vector | I like vectors a lot. They're nifty and fast. But I know this thing called a valarray exists. Why would I use a valarray instead of a vector? I know valarrays have some syntactic sugar, but other than that, when are they useful?
| Valarrays (value arrays) are intended to bring some of the speed of Fortran to C++. You wouldn't make a valarray of pointers so the compiler can make assumptions about the code and optimise it better. (The main reason that Fortran is so fast is that there is no pointer type so there can be no pointer aliasing.)
Valarra... |
1,602,692 | 1,602,765 | Pointer stability under Windows Vista | I have been using Visual Studio 2005 under Windows XP Pro 64-bit for C and C++ projects for a while. One of the popular tricks I have been using from time to time in the debugger was to remember a numeric pointer value from the previous debugging run of the program (say 0x00000000FFAB8938), add it to watch window with ... | Windows Vista implements address space layout randomization, heap randomization, and stack randomization. This is a security mechanism, trying to prevent buffer overflow attacks that rely on the knowledge of where each piece of code and data is in memory.
It's possible to turn off ASLR by setting the MoveImages registr... |
1,602,998 | 1,603,039 | Fastest way to obtain the largest X numbers from a very large unsorted list? | I'm trying to obtain the top say, 100 scores from a list of scores being generated by my program. Unfortuatly the list is huge (on the order of millions to billions) so sorting is a time intensive portion of the program.
Whats the best way of doing the sorting to get the top 100 scores?
The only two methods i can thi... |
take the first 100 scores, and sort them in an array.
take the next score, and insertion-sort it into the array (starting at the "small" end)
drop the 101st value
continue with the next value, at 2, until done
Over time, the list will resemble the 100 largest value more and more, so more often, you find that the inse... |
1,603,000 | 1,603,272 | decorator with a base that requires a constructor argument | I have a decorator-like pattern with a base that requires a constructor parameter. The decorator is constructed such that it can take an arbitrary number of add-on components as template parameters (up to 3 in this example).
Unfortunately, I can't figure out how to pass the base's constructor parameter to it when more ... | Your errors are generally originating out of the fact that CMyClass does not have a default constructor (because you define a CMyClass(int) instead), so it is necessary to explicitly instantiate your parents with the CMyClass(int) constructor that you have. So, for example, in your definition of CMyClass you need to ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.