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 |
|---|---|---|---|---|
2,949,587 | 2,949,655 | Why are argument substitutions not replaced during rescanning? | Consider the following macro definitions and invocation:
#define x x[0]
#define y(arg) arg
y(x)
This invocation expands to x[0] (tested on Visual C++ 2010, g++ 4.1, mcpp 2.7.2, and Wave).
Why? Specifically, why does it not expand to x[0][0]?
During macro replacement,
A parameter in the replacement list...is replace... | I believe you've quoted the crucial paragraph, you just stopped too soon. 16.3.4/2 (emphasis mine):
If the name of the macro being replaced is found during this scan of
the replacement list (not including
the rest of the source file’s
preprocessing tokens), it is not
replaced. Further, if any nested
replacem... |
2,949,833 | 2,949,864 | List of functions references | I'm using boost::function for making references to the functions. Can I make a list of references?
For example:
boost::function<bool (Entity &handle)> behaviorRef;
And I need in a list of such pointers. For example:
std::vector<behaviorRef> listPointers;
Of course it's wrong code due to behaviorRef isn't a type.
So t... | typedef boost::function<bool (Entity&)> behaviorRef_type;
std::vector<behaviorRef_type> listPointers;
|
2,949,892 | 2,951,795 | Auto scrolling control (WinAPI)? | In C# (.Net) you can create a panel and set autoscroll to true. you can then add controls into it, including beyond it's size, then it will scroll.
I was wondering if when using the real WinAPI in c++ (not .net) how one could acheive the same result.
Must I keep track of the controls inside and move them all when I scr... | For an edit control (textbox), you can supply ES_AUTOVSCROLL when creating it via CreateWindow or CreateWindowEx. For adding a scrollbar for multiple controls in a window, I believe you have to do it manually. Write a function to sum the vertical height of all the child controls + spacing between them and if it's small... |
2,949,976 | 2,950,008 | why must you provide the keyword const in operator overloads | Just curious on why a param has to be a const in operation overloading
CVector& CVector::operator= (const CVector& param)
{
x=param.x;
y=param.y;
return *this;
}
couldn't you have easily done something like this ??
CVector& CVector::operator= (CVector& param) //no const
{
x=param.x;
y=param.y;
return *this... | A const parameter is const throughout the function using it, it does not change its constness outside of it.
In this case you want to declare a const argument so that your assignment operator accepts both non-const variables and const variables; the latter case, in particular, includes the result of expressions, which ... |
2,950,029 | 2,950,722 | What does 'unsigned temp:3' in a struct or union mean? |
Possible Duplicate:
What does this C++ code mean?
I'm trying to map a C structure to Java using JNA. I came across something that I've never seen.
The struct definition is as follows:
struct op
{
unsigned op_type:9; //---> what does this mean?
unsigned op_opt:1;
unsigned op_latefree:1;
unsigned ... | This construct specifies the length in bits for each field.
The advantage of this is that you can control the sizeof(op), if you're careful. the size of the structure will be the sum of the sizes of the fields inside.
In your case, size of op is 32 bits (that is, sizeof(op) is 4).
The size always gets rounded up to the... |
2,950,044 | 2,950,270 | Work with function references | I have another one question about functions reference.
For example, I have such definition:
typedef boost::function<bool (Entity &handle)> behaviorRef;
std::map< std::string, ptr_vector<behaviorRef> > eventAssociation;
The first question is: how to insert values into such map object?
I tried:
eventAssociation.insert(s... | PART 1
There's no need to use a ptr_vector. boost::function has value semantics, so can be stored in a standard container. So the following should work:
typedef boost::function<bool (Entity &handle)> behaviorRef;
std::map< std::string, std::vector<behaviorRef> > eventAssociation;
eventAssociation.insert(std::make_pair... |
2,950,194 | 7,760,666 | QGraphicsItem repaint | I want to change text color inside a rectangle periodically.
Here is my trial:
TrainIdBox::TrainIdBox()
{
boxRect = QRectF(0,0,40,15);
testPen = QPen(Qt:red);
i=0;
startTimer(500);
}
QRectF TrainIdBox::boundingRect() const
{
return boxRect;
}
void TrainIdBox::paint(QPainter *painter, const QStyleOptio... | If you inherit from QGraphicsObject ... I give here an example:
Declare:
class Text : public QGraphicsObject
{
Q_OBJECT
public:
Text(QGraphicsItem * parent = 0);
void paint ( QPainter * painter,
const QStyleOptionGraphicsItem * option, QWidget * widget );
... |
2,950,260 | 2,952,243 | Alternative to C++ exception | I'm writing a reactive software, which repeatedly recieves input, processes it and emits relevant output. The main loop looks something like:
initialize();
while (true) {
Message msg,out;
recieve(msg);
process(msg,out);
//no global state is saved between loop iterations!
send(out);
}
I want that wh... | Coding these kind of services all day long I understand your problem. Although we do have exceptions within our code, we don't return them to the external libraries that invoke it, instead we have a simple 'tribool'.
enum ReturnCode
{
OK = 0, // OK (there is a reason for it to be 0)
KO, // An error occurred, ... |
2,950,332 | 2,950,358 | Why does a C-Array have a wrong sizeof() value when it's passed to a function? | Complete example:
#include <stdio.h>
void test(int arr[]) {
int arrSize = (int)(sizeof(arr) / sizeof(arr[0]));
printf("%d\n", arrSize); // 2 (wrong?!)
}
int main (int argc, const char * argv[]) {
int point[3] = {50, 30, 12};
int arrSize = (int)(sizeof(point) / sizeof(point[0]));
printf("%d\n", ar... | When you pass an array into a function in C, the array decays into a pointer to its first element. When you use sizeof on the parameter, you are taking the size of the pointer, not the array itself.
If you need the function to know the size of the array, you should pass it as a separate parameter:
void test(int arr[],... |
2,950,501 | 2,950,518 | Iterating through std queue | I'm trying to use BOOST_FOREACH for iterating through the std::queue. But there isn't iterators in that class cause I have an error:
std::queue<std::string> someList;
BOOST_FOREACH(std::string temp, someList)
{
std::cout << temp;
}
>no matching function for call to begin(...)
>no type named ‘iterator’ in ‘class std... | std::deque supports efficient insert and removal at the beginning and end of the data structure. You can do queue operations manually using push_back and pop_front.
A queue uses a deque internally by default. It's a wrapper that only exposes queue operations (hence why you can't iterate over it). I asked a similar q... |
2,950,512 | 2,950,560 | In C++, I want to implement a ring iterator for a deque that contains a personally defined class | I have a function of a "Table" class that should add a player to the table. I decided that if the seat is taken, the function should try and go through all the seats and add the player to the next available seat. How do I implement this in my addPlayer function?
int Table::addPlayer(Player player, int position)
{
deq... | Instead of using position, use the iterator to point to that position, using something like this:
it = playerList.begin() + position;
Then, check if the seat is taken using the iterator.
If the seat is taken, increment the iterator, but check for end, like this:
while (no empty seat found yet)
{
++it;
if (it=... |
2,950,573 | 2,950,605 | MSXML problem in VC++ 6 | I have this bit of code:
typedef CComQIPtr<MSXML::IXMLDOMDocument2> XML_DocumentPtr;
then inside some class:
XML_DocumentPtr m_spDoc;
then inside some function:
XML_NodePtr rn=m_spDoc->GetdocumentElement();
I cannot find anywhere in the MSDN documentation what that GetDocumentElement() is supposed to do? Can anyone... | IXMLDocument2 inherits from IXMLDocument. The GetDocumentElement() method is defined in that interface. See here.
Basically GetdocumentElement returns the root element of the XML document.
The property is read/write. It returns
an IXMLDOMElement that represents the
single element that represents the
root of the ... |
2,950,639 | 2,950,851 | printing 2d table (headers) | Is there are a better way than this one to print 2d table?
std::cout
<< std::setw(25) << left << "FF.name"
<< std::setw(25) << left << "BB.name"
<< std::setw(12) << left << "sw.cycles"
<< std::setw(12) << left << "hw.cycles" << "\n"
<< std::setw(25) << left << "------"
<< std::se... | You could put the headers into an array or vector, then generate the correct widths automatically:
boost::array<std::string, 4> head = { ... }
BOOST_FOREACH(std::string& s, head)
{
int w = 5*(s.length()/5 + 1);
std::cout << std::setw(w) << left << s;
}
std::cout << '\n';
BOOST_FOREACH(std::string& s, head)
{
... |
2,950,811 | 2,950,920 | C++ linker unresolved external symbol (again;) from other source file *.obj file. (VC++ express) | I'm back to C/C++ after some break.
I've a following problem:
I've a solution where I've several projects (compilable and linkable).
Now I need to add another project to this solution which depends on some sources from other projects.
My new project compiles without any problems (I've added "existing sources" to my pro... | Seems like you need to make sure the functions are declared properly as C functions:
#ifdef __cplusplus
extern "C" {
#endif
int saveLic(char *,struct Auth *);
void getSysInfo(struct Auth *);
#ifdef __cplusplus
}
#endif
In a header file included by LicenceManager.cpp.
|
2,950,863 | 2,951,354 | How to prevent removal of slots from a certain signal? | Is it possible to block the removal of certain slots from a signal in the boost.signals library?
If so how should a code that does such a thing will look like? Do I need to create a derived class just for that specific signal to do so?
| Supply your own slot connection function that fails to return the connection. Without the connection the client can't break it.
Edit: code example:
struct my_class
{
boost::signals::connection listen_event1(boost::function<void (my_class const&)> const& f)
{
return signal1.connect(f);
}
void listen_event2(... |
2,951,117 | 2,951,138 | How to manage member variable in C++ | In brief, my question is about member variables as pointers in unmanaged C++.
In java or c#, we have "advanced pointer". In fact, we can't aware the "pointer" in them. We usually initialize the member of a class like this:
member = new Member();
or
member = null;
But in c++, it becomes more confusing. I have seen man... | The Boost source code is not a good example for how you should write your source code. The Boost libraries are designed to wrap up all the tedious, difficult, and error-prone code so that you don't have to worry about it in your code.
Your best bet is to follow two general rules in your code:
Don't use pointers where... |
2,951,273 | 2,951,294 | pure-specifier on function-definition | While compiling on GCC I get the error: pure-specifier on function-definition, but not when I compile the same code using VS2005.
class Dummy {
//error: pure-specifier on function-definition, VS2005 compiles
virtual void Process() = 0 {};
};
But when the definition of this pure virtual function is not inline, ... | Ok, I've just learned something. A pure virtual function must be declared as follows:
class Abstract
{
public:
virtual void pure_virtual() = 0;
};
It may have a body, although it is illegal to include it at the point of declaration. This means that to have a body the pure virtual function must be defined outsid... |
2,951,361 | 2,951,386 | Can multiple threads access a vector at different places? | Lets say I have a vector of int which I've prefilled with 100 elements with a value of 0.
Then I create 2 threads and tell the first thread to fill elements 0 to 49 with numbers, then tell thread 2 to fill elements 50 to 99 with numbers. Can this be done? Otherwise, what's the best way of achieving this?
Thanks
| Yes, this should be fine. As long as you can guarantee that different threads won't modify the same memory location, there's no problem.
|
2,951,388 | 2,951,426 | Encrypting a file in win API | hi I have to write a windows api code that encrypts a file by adding three to each character.
so I wrote this now its not doing anything ... where i go wronge
#include "stdafx.h"
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE filein,fileout;
filein=CreateFile
(L"d:\\test.txt",G... | First, you can't overwrite a file that's in use. You will need to use different pathnames for your input and output, and then rename files at the end.
|
2,951,464 | 2,951,496 | Byte from string/int in C++ | I'm a beginning user in C++ and I want to know how to do this:
How can I 'create' a byte from a string/int. So for example I've:
string some_byte = "202";
When I would save that byte to a file, I want that the file is 1 byte instead of 3 bytes.
How is that possible?
Thanks in advance,
Tim
| I would use C++'s String Stream class <sstream> to convert the string to an unsigned char.
And write the unsigned char to a binary file.
so something like [not real code]
std::string some_byte = "202";
std::istringstream str(some_byte);
int val;
if( !(str >> val))
{
// bad conversion
}
if(val > 255)
{
// too big
}... |
2,951,472 | 2,962,040 | MySql UDF using shared library won't load | I am attempting to create a mysql UDF which will match a fingerprint using Digital Persona's free linux SDK library. I have written a trivial UDF as a learning experience which worked fine. However, when I added a dependency to Digital Persona's shared object I can no longer get MySql to load my UDF.
I added includes... | Your problem is that your library depends on another, bu MySQL/dl doesn't know this and therefore doesn't load it. You need to explicitly link your library against Digital Persona's library. You can do this by using the -l{libname} (and maybe -L/lib/path).
|
2,951,541 | 2,951,743 | How to generate RSA-SHA256 digital signature with OpenSSL libraries? | I need to generate a digital signature from C++ code, using OpenSSL libraries.
I understood that I need for that DSA \ DSA_do_sign, but didn't understand how exactly to use it.
Does someone have an example for that, or a reference for better than OpenSSL's supplied docs?
Thanks in advance!
| You seem to have RSA and DSA confused. However, if you want to sign using RSA-sha256, then use the EVP interface for signing. You can initialize with the EVP_SignInit_ex() method with EVP_sha256() for the type argument.
|
2,951,576 | 2,951,662 | int ** vs int [ROWS][COLS] |
Possible Duplicate:
casting char[][] to char** causes segfault?
I have a 2D array declared like this:
int arr[2][2]={ {1,2},{3,4}};
Now if I do:
int ** ptr=(int**) arr;
and:
cout<<**ptr;
I am getting a segmentation fault (using g++-4.0).
Why so? Shouldn't it be printing the value 1 (equal to arr[0][0])?
| You are attempting to assign a double pointer variable to an array... this has been covered exhaustively, see here for information on this. Furthermore, since you declared
int arr[2][2] = ...;
and then try to assign arr to a double pointer
int ** ptr = ... ;
which is guaranteed to not work, hence a segmentation fau... |
2,951,586 | 2,951,700 | Default Struct Initialization in C++ | Say I have a struct that looks like this (a POD):
struct Foo
{
int i;
double d;
};
What are the differences between the following two lines:
Foo* f1 = new Foo;
Foo* f2 = new Foo();
| The first one leaves the values uninitialised; the second initialises them to zero. This is only the case for POD types, which have no constructors.
|
2,951,605 | 2,951,653 | How to pass function reference into arguments | I'm using boost::function for making function-references:
typedef boost::function<void (SomeClass &handle)> Ref;
someFunc(Ref &pointer) {/*...*/}
void Foo(SomeClass &handle) {/*...*/}
What is the best way to pass Foo into the someFunc?
I tried something like:
someFunc(Ref(Foo));
| In order to pass a temporary object to the function, it must take the argument either by value or by constant reference. Non-constant references to temporary objects aren't allowed. So either of the following should work:
void someFunc(const Ref&);
someFunc(Ref(Foo)); // OK, constant reference to temporary
void someFu... |
2,951,703 | 2,952,730 | Working with sockets in MFC | I'm trying to make a MFC application(client) that connects to a server on ("localhost",port 1234), the server replies to the client and the client reads from the server's response.
The server is able to receive the data from the client and it sends the reply back to the socket from where it received it, but I am unable... | You should be aware that all network operations are potentially time-consuming operations. Now, since you're using MFC's CAsyncSocket class, it performs all the operations asynchronously (doesn't block you). But return from the function doesn't mean it's already completed.
Let's look at the following lines of code:
soc... |
2,951,773 | 2,957,543 | How to construct objects based on XML code? | I have XML files that are representation of a portion of HTML code.
Those XML files also have widget declarations.
Example XML file:
<message id="msg">
<p>
<Widget name="foo" type="SomeComplexWidget" attribute="value">
inner text here, sets another attribute or
inserts another widget to the ... | Create the tool, include it into your build steps and everything will be fine.
See comments to my previous answer for additional details.
|
2,951,780 | 2,951,933 | How do I compile variadic templates conditionally? | Is there a macro that tells me whether or not my compiler supports variadic templates?
#ifdef VARIADIC_TEMPLATES_AVAILABLE
template<typename... Args> void coolstuff(Args&&... args);
#else
???
#endif
If they are not supported, I guess I would simulate them with a bunch of overloads. Any better ideas? Maybe there ar... | It looks like the current version of Boost defines BOOST_NO_VARIADIC_TEMPLATES if variadic templates are unavailable. This is provided by boost/config.hpp; see here for config.hpp documentation.
If variadic templates are unavailable, then you'll probably have to simulate them with a bunch of overloads, as you said. T... |
2,952,216 | 2,952,398 | delegating into private parts | Sometimes, C++'s notion of privacy just baffles me :-)
class Foo
{
struct Bar;
Bar* p;
public:
Bar* operator->() const
{
return p;
}
};
struct Foo::Bar
{
void baz()
{
std::cout << "inside baz\n";
}
};
int main()
{
Foo::Bar b; // error: 'struct Foo::Bar' is priva... | Trying to find anything in the standard that would spell it out in detail but I can't. The only thing I can find is 9.9:
Type names obey exactly the same scope rules as other names. In particular, type names defined within a class definition cannot be used outside their class without qualification.
Essentially, the n... |
2,952,407 | 2,952,636 | Sorting 1000-2000 elements with many cache misses | I have an array of 1000-2000 elements which are pointers to objects. I want to keep my array sorted and obviously I want to do this as quick as possible. They are sorted by a member and not allocated contiguously so assume a cache miss whenever I access the sort-by member.
Currently I'm sorting on-demand rather than on... | Simple approach: insertion sort on every insert. Since your elements are not aligned in memory I'm guessing linked list. If so, then you could transform it into a linked list with jumps to the 10th element, the 100th and so on. This is kind of similar to the next suggestion.
Or you reorganize your container structure i... |
2,952,631 | 2,952,665 | format specifier for short integer | I don't use correctly the format specifiers in C. A few lines of code:
int main()
{
char dest[]="stack";
unsigned short val = 500;
char c = 'a';
char* final = (char*) malloc(strlen(dest) + 6);
snprintf(final, strlen(dest)+6, "%c%c%hd%c%c%s", c, c, val, c, c, dest);
pr... | I'm confused - the problem is that you are saying strlen(dest)+6 which limits the length of the final string to 10 chars (plus a null terminator). If you say strlen(dest)+8 then there will be enough space for the full string.
Update
Even though a short may only be 2 bytes in size, when it is printed as a string each ch... |
2,952,706 | 2,954,182 | OpenGL Vertex Buffer Object code giving bad output | My Vertex Buffer Object code is supposed to render textures nicely but instead the textures are being rendered oddly with some triangle shapes.
What happens - http://godofgod.co.uk/my_files/wrong.png
What is supposed to happen - http://godofgod.co.uk/my_files/right.png
This function creates the VBO and sets the vertex ... | If you want to use the one VBO for both vertex and texture coordinates you need to group them using a struct.
Define your data:
typedef struct {
GLdouble x, y;
GLint s, t;
} VertexData;
VertexData data[] = {
// x y s t
{0.0, 0.0, 0, 0},
{0.0, size[1], 0, 1},
{size[0],... |
2,952,707 | 2,952,744 | Heap Behavior in C++ | Is there anything wrong with the optimization of overloading the global operator new to round up all allocations to the next power of two? Theoretically, this would lower fragmentation at the cost of higher worst-case memory consumption, but does the OS already have redundant behavior with this technique, or does it do... | The default memory allocator is probably quite smart and will deal well with large numbers of small to medium sized objects, as this is the most common case. For all allocators, the number of bytes requested is never always the amount allocated. For example, if you say:
char * p = new char[3];
the allocator almost cer... |
2,952,715 | 2,952,791 | Any problems with this C++ const reference accessor interface idiom? | I was converting a struct to a class so I could enforce a setter interface for my variables.
I did not want to change all of the instances where the variable was read, though.
So I converted this:
struct foo_t {
int x;
float y;
};
to this:
class foo_t {
int _x;
float _y;
public:
foot_t() : x(_x), y... | There is an aliasing issue in that because you expose a reference to the foo_t's internal data, it's possible for code external to a foo_t object to hold on to references into its data beyond the object's lifetime. Consider:
foo_t* f = new foo_t();
const int& x2 = f->x;
delete f;
std::cout << x2; // Undefined behavior;... |
2,952,755 | 2,952,775 | Trouble assigning a tr1::shared_ptr | I've got a class that has a tr1::shared_ptr as a member, like so:
class Foo
{
std::tr1::shared_ptr<TCODBsp> bsp;
void Bar();
}
In member function Bar, I try to assign it like this:
bsp = newTCODBsp(x,y,w,h);
g++ then gives me this error
no match for ‘operator=’ in ‘((yarl::mapGen::MapGenerator*)this)->yarl::m... | call .reset(new TCODBsp) or say bsp = std::tr1::shared_ptr(new TCODBsp). Shared pointers are explicit. You can't just assign the ptr type to them.
|
2,952,895 | 2,952,932 | copying a short int to a char array | I have a short integer variable called s_int that holds value = 2
unsighed short s_int = 2;
I want to copy this number to a char array to the first and second position of a char array.
Let's say we have char buffer[10];. We want the two bytes of s_int to be copied at buffer[0] and buffer[1].
How can I do it?
| The usual way to do this would be with the bitwise operators to slice and dice it, a byte at a time:
b[0] = si & 0xff;
b[1] = (si >> 8) & 0xff;
though this should really be done into an unsigned char, not a plain char as they are signed on most systems.
Storing larger integers can be done in a similar way, or with a l... |
2,953,086 | 2,953,113 | subscript requires array or pointer ERROR | I know what is my mistake can't figer how to solve it.
Im writing an winAPI that counts how many 'a' characters are found is a givien file.
Im still getting the error " subscript requires array or pointer " (please find the comment in the code)
#include "stdafx.h"
#include <windows.h>
int _tmain(int argc, _TCHAR* arg... | ReadFile() puts the data into the second parameter, in your case x.
In your code, really is the number of bytes read. It's just a number. You can't put an subscript on a plain number, thus the error message.
So change
if(really[i]==str)
To
if (x[i] == str)
But you're going to hit another problem:
DWORD really;
int c... |
2,953,111 | 2,953,244 | Start Windows GUI Application Development With C++ | I'm looking into creating a GUI program for Windows in C++, I have a good knowledge of C++ in the command line and also in game creation. But I'm not sure where to start with GUI application development.
I have Visual Studio 2010 and have created new projects with a GUI but these templates are complex and leaves me no... | Having written Windows code since Win2.0, I have to say: start with C#. It's a very easy language to learn after C++, and many of the new features (like built-in event handling) were put there to make writing GUI applications easier.
Then, once you're used to the basic concepts of window management and messaging, then ... |
2,953,230 | 2,954,487 | More elegant way to make a C++ member function change different member variables based on template parameter? | Today, I wrote some code that needed to add elements to different container variables depending on the type of a template parameter. I solved it by writing a friend helper class specialized on its own template parameter which had a member variable of the original class. It saved me a few hundred lines of repeating my... | After reading Emile Cormier's comment, I thought of a way to both keep from repeating myself and to also eliminate the Worker class: make two trivial non-template doIt functions for F and G and have each call a third templated doIt function with the variable to change passed as a parameter. Here is the modified code.
... |
2,953,251 | 2,953,685 | Is it safe to make GL calls with multiple threads? | I was wondering if it was safe to make GL calls with multiple threads. Basically I'm using a GLUtesselator and was wondering if I could divide the objects to draw into 4 and assign a thread to each one.
I'm just wondering if this would cause trouble since the tesselator uses callback functions. Can 2 threads run the s... | The answer to "Can 2 threads run the same callback at the same time as long as that callback does not access ant global variables?" is a clear YES.
However, you will get problems when you modify the state of OpenGL in your callback functions, especially when using glBegin / glEnd (eg if you generate a DisplayList). As ... |
2,953,334 | 2,953,353 | problem passing listener class to a function | I'm using a library that manipulates a binary search tree. In this library is a function that traverses the tree and passes each node it finds to a callback class:
bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback *callback, void *userData)
ITCODBspCallback is a base class in the library from which the user is... | This all looks like you forgot to include the MyCallback header. Since its parser doesn't interpret MyCallback as a type if it doesn't know it is one, it comes up with an own type, and ignores MyCallback(), i think. The type it comes up with is int*.
Notice that your code leaks because you need to call delete on any n... |
2,953,459 | 2,953,719 | strnicmp equivalent for UTF-8? | What do I use to perform a case-insensitive comparison on two UTF-8 encoded sub-strings? Essentially, I'm looking for a strnicmp function for UTF-8.
| Case conversion rules in various Unicode scripts are murderously difficult, it requires large case conversion tables. You cannot get this right yourself, you'll need a library. ICU is one of them.
|
2,953,483 | 2,953,584 | Does acos, atan functions in stl uses lots of cpu cycles | I wanted to calculate the angle between two vectors but I have seen these inverse trig operations such as acos and atan uses lots of cpu cycles. Is there a way where I can get this calculation done without using these functions? Also, does these really hit you when you in your optimization?
| There are no such functions in the STL; those are in the math library.
Also, are you sure it's important to be efficient here? Have you profiled to see if there's function calls like this in the hot spots? Do you know that the performance is bad when using these functions? You should always answer these questions ... |
2,953,491 | 2,953,498 | Finding the position of the maximum element | Is there a standard function that returns the position (not value) of the maximum element of an array of values?
For example:
Suppose I have an array like this:
sampleArray = [1, 5, 2, 9, 4, 6, 3]
I want a function that returns the integer of 3 that tells me that sampleArray[3] is the largest value in the array.
| In the STL, std::max_element provides the iterator (which can be used to get index with std::distance, if you really want it).
int main(int argc, char** argv) {
int A[4] = {0, 2, 3, 1};
const int N = sizeof(A) / sizeof(int);
cout << "Index of max element: "
<< distance(A, max_element(A, A + N))
<< ... |
2,953,530 | 2,953,868 | unique_ptr boost equivalent? | Is there some equivalent class for C++1x's std::unique_ptr in the boost libraries? The behavior I'm looking for is being able to have an exception-safe factory function, like so...
std::unique_ptr<Base> create_base()
{
return std::unique_ptr<Base>(new Derived);
}
void some_other_function()
{
std::unique_ptr<Ba... | It's not possible to create something like unique_ptr without C++0x (where it's part of the standard library, and so Boost doesn't need to provide it).
Specifically without rvalue references, which are a feature in C++0x, a robust implementation of unique_ptr is impossible, with or without Boost.
In C++03, there are a ... |
2,953,554 | 2,953,570 | Recycle Freed Objects | suppose I need to allocate and delete object on heap frequently (of arbitrary size), is there any performance benefit if instead of deleting those objects, I will return it back to some "pool" to be reused later?
would it give benefit by reduce heap allocation/deallocation?, or it will be slower compared to memory allo... | Pooling is a very common technique to avoid frequent allocations and deallocations. Some treat it as a design pattern.
There are typically existing implementations, so there is no benefit to reinventing the wheel.
You may want to take a look at the question Object pool vs. dynamic allocation
|
2,953,611 | 2,953,925 | Are variadic constructors supposed to hide the implicitly generated ones? | Are variadic constructors supposed to hide the implicitly generated ones, i.e. the default constructor and the copy constructor?
struct Foo
{
template<typename... Args> Foo(Args&&... x)
{
std::cout << "inside the variadic constructor\n";
}
};
int main()
{
Foo a;
Foo b(a);
}
Somehow I was e... | Declaration of the implicitly declared copy constructor is not, in fact, being suppressed. It's just not being called due to the rules of overload resolution.
The implicitly declared copy constructor has the form Foo(const Foo&). The important part of this is that it takes a const reference. Your constructor templat... |
2,953,684 | 2,953,783 | Why doesn't ADL find function templates? | What part of the C++ specification restricts argument dependent lookup from finding function templates in the set of associated namespaces? In other words, why does the last call in main below fail to compile?
namespace ns {
struct foo {};
template<int i> void frob(foo const&) {}
void non_template(foo const... | This part explains it:
C++ Standard 03 14.8.1.6:
[Note: For simple function names, argument dependent lookup (3.4.2) applies even when the function name is not visible within the scope of the call. This is because the call still has the syntactic form of a function call (3.4.1). But when a function template with expli... |
2,953,702 | 2,953,722 | searching for hidden files using winapi | HI
i want to search for a hidden files and directories in a specefic given path but I don't know how to do it for hidden files i do know how to search for normal files and dir i did this code but im stuck can't make it search for only hidden files
#include "stdafx.h"
#include <windows.h>
int _tmain(int argc, _TCHAR* ... | The WIN32_FIND_DATA structure isn't telling FindFirstFile/FindNextFile what to search for; it's returning the results of the search. You need to do a bit mask on the dwFileAttributes member to determine if the file is hidden or not.
if ((data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0)
|
2,953,992 | 2,967,856 | breakpoint inside QComboBox subclass not working | I have subclassed QComboBox to customize it for special needs. The subclass is used to promote QComboBoxes in a ui file from QtDesigner. Everything works except that when I put a break point in a slot, the program does not stop at the breakpoint. I do however know that it is being called from the result it generates. I... | I found the problem. All I needed to do was to put the function definition in the .cpp file.
|
2,954,184 | 2,954,191 | the scope of a pointer? | Ok, so I did find some questions that were almost similar but they actually confused me even more about pointers.
C++ Pointer Objects vs. Non Pointer Objects
In the link above, they say that if you declare a pointer it is actually saved on the heap and not on the stack, regardless of where it was declared at. Is this ... | The variable itself is stored on the stack or DATA segment, but the memory it points to after being allocated with new is within the heap.
|
2,954,212 | 2,954,249 | Extract a portion of a Qt .ui file into its own .ui file | We have a designer creating a user interface for an application. The main window has several QStackedWidgets used for in place panel switching. What I'd like to be able to do is extract each individual panel that makes up each page of the QStackedWidget into it its own .ui file.
Is there an easy way to accomplish t... | You can cut/paste each panel into a blank QWidget (created with File > New), and save these widgets in their own .ui file.
|
2,954,399 | 2,954,430 | Convert CString to string (VC6) | I want to convert CString to string. (Yup. I know what am I doing. I know the returned string will be incorrect, if CString value range is outside ANSI, but That's Is OK!)
The following code will work under VC2008.
std::string Utils::CString2String(const CString& cString)
{
// Convert a TCHAR string to a LPCSTR
... | Microsoft says that CT2CA replaces T2CA, so try the latter and see if that works.
|
2,954,473 | 2,954,601 | "variable tracking" is eating my compile time! | I have an auto-generated file which looks something like this...
static void do_SomeFunc1(void* parameter)
{
// Do stuff.
}
// Continues on for another 4000 functions...
void dispatch(int id, void* parameter)
{
switch(id)
{
case ::SomeClass1::id: return do_SomeFunc1(parameter);
case ::Some... | You can turn off variable tracking. Variable tracking is used to make the debug information a bit more valuable, but if this code is auto-generated and you're not really going to be debugging it much then it's not really useful. You can just turn it off for that file only.
gcc -fno-var-tracking ...
Should do the trick... |
2,954,582 | 2,954,623 | how to write a constructor | is that correct to write a constructor like this?
class A
{
A(const A& a)
{
....
}
};
if yes, then is it correct to invoke it like this:
A* other;
...
A* instance = new A(*(other));
if not, what do you suggest?
Thanks
| Almost correct. When declaring the constructor in the class, simply write A, not A::A; you would use A::A when giving a definition for the constructor outside of the class declaration. Otherwise, yes.
Also, as James points out, unless you are copying from an object that you are accessing via a pointer, you don't need ... |
2,954,586 | 2,954,605 | Thread Proc for an instancable class? | Basically I have a class and it is instincable (not static). Basically I want the class to be able to generate its own threads and manage its own stuff. I don't want to make a global callback for each instance I make, this doesnt seem clean and proper to me. What is the proper way of doing what I want. If I try to pass... | class Obj
{
static ULONG WINAPI ThreadProc(void* p)
{
Obj* pThis = (Obj*)p;
... do stuff ...
return 0;
}
void StartMemberThread()
{
CreateThread(... ThreadProc, this, ... );
}
};
Trickiest part is making sure the thread doesn't use pThis after the object goes awa... |
2,954,802 | 2,954,931 | how to play rtsp streamming in QT | I am trying to find a way to play in Qt 4.6 rtsp streaming, that i got from youtube api
can it be done somehow?
| Live555 has some very useful libraries on this subject.
|
2,954,815 | 2,954,824 | Works on debug but not release | I have a thread that sets a value to true when it is done. Until then I wait:
while(1)
{
if(done[0] == true)
{
break;
}
}
This code works just fine in Debug but in Release it stays in the loop forever even though the debugger clearly says that it is true and not false.
Why would this not work?
Tha... | This is symptomatic of not marking done as volatile.
Without volatile the optimising compiler can cache the value in a register.
e.g.
private volatile int i;
|
2,954,821 | 2,955,115 | Using an iterator without its container | I am mixing some C and C++ libraries and have only a single pointer available to do some work in a callback function. All I need to do is iterate through a vector. Here's a simplified, untested example:
bool call_back(void* data){
done=...
if (!done) cout << *data++ << endl;
return done;
}
Note that this func... | Why not have data point to a structure with all the information you need.
The point about the old "C" style callbacks is that a void* can point to any object. Your callback function knows what the type is, but it can be anything.
typedef struct Plop
{
std::vector<int>::iterator begin;
std::vector<int>::iterator... |
2,955,082 | 2,955,163 | one line assert to test if STL container is sorted | Is there a way to write a one line condition that would return true if STL container is sorted? The container in question is std::vector
I intend to use it in an assert
| Use adjacent_find in combination with less or greater functor.
Restriction:
You should know whether the container is sorted in ascending or descending.
If the vector is supposed to be sorted in ascending order:
//Checks the first element where adjacent value where elem > nextElem
//returns end if the vector is sorted!
... |
2,955,220 | 2,955,401 | Gzip In-Memory Compression | Quick and simple question.
There are examples online about achieving in-memory gzip compression with zlib (C++) WITHOUT external libraries (like boost or such)?
I just need to compress and decompress a block of data without much options. (it must be gzip as its the same format used by another mine C# program (the data... | This isn't a complete answer to your question, but you will probably be interested in How can I decompress a gzip stream with zlib?. There is a little bit of poorly documented magic that you need to supply in order for zlib to work with gzip streams.
The zlib API has many functions for doing in-memory compression that ... |
2,955,379 | 2,955,829 | Operators vs Functions in C/C++ | Someone recently asked me the difference between a C++ standard operator (e.g. new,delete,sizeof) and function (e.g. tan,free, malloc). By "standard" I mean those provided by default by the compiler suite, and not user defined. Below were the answers I gave, though neither seemed satisfactory.
(1) An operator doesn't... | Operators are keywords with a fixed syntax. Those which can be overloaded might vary a bit in syntax, but that's within the boundaries. The new operator is still spelled new, even when overloaded and the syntax of invoking it is always the same.
Function names are identifiers, which can be almost arbitrary. There's no... |
2,955,398 | 2,955,765 | How do I insert format str and don't remove the matched regular expression in input string in boost::regex_replace() in C++? | I want to put space between punctuations and other words in a sentence. But boost::regex_replace() replaces the punctuation with space, and I want to keep a punctuation in the sentence!
for example in this code the output should be "Hello . hi , "
regex e1("[.,]");
std::basic_string<char> str = "Hello.hi,";
std::basic... | You need to use a replacement variable in your fmt string. If I understand the documentation correctly, then in the absence of a flags field, you'll want to use a Boost-Extended format string.
In that sub-language, you use $& to mean whatever was matched, so you should try defining fmt as:
std::basic_string<char> fmt =... |
2,955,797 | 2,956,061 | How to address thread-safety of service data used for maintaining static local variables in C++? | Consider the following scenario. We have a C++ function with a static local variable:
void function()
{
static int variable = obtain();
//blahblablah
}
the function needs to be called from multiple threads concurrently, so we add a critical section to avoid concurrent access to the static local:
void functionT... | C++ says that your static variable should only be initialized once - however C++ doesn't deal with threads(yet).
gcc(atleast on *nix systems) does the proper magic to safely guard multiple threads initializing such a static variable. According to this link, msvc does not - and in such a case you'll have to lock the ini... |
2,955,858 | 2,956,260 | How to use Application Verifier to find memory leaks | I want to find memory leaks in my application using standard utilities.
Previously I used my own memory allocator, but other people (yes, you AlienFluid) suggested to use Microsoft's Application Verifier, but I can't seem to get it to report my leaks.
I have the following simple application:
#include <iostream>
#includ... | CRT memory leaks detection (without stack trace):
// debug_new.h
#pragma once
#include "crtdbg.h"
#ifdef _DEBUG
#ifndef DEBUG_NEW
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif
All .cpp files:
#include "debug_new.h"
...
// After all other include lines:
#ifdef _DEBUG
#define new DEBUG_... |
2,955,921 | 3,090,741 | Thread-safe initialization of function-local static const objects | This question made me question a practice I had been following for years.
For thread-safe initialization of function-local static const objects I protect the actual construction of the object, but not the initialization of the function-local reference referring to it. Something like this:
namespace {
const some_typ... | This is my second attempt at an answer. I'll only answer the first of your questions:
safe enough in practice?
No. As you're stating yourself you're only ensuring that the object creation is protected, not the initialization of the reference to the object.
In absence of a C++98 memory model and no explicit statemen... |
2,956,097 | 2,956,142 | Is there performance to be gained by moving storage allocation local to a member function to its class? | Suppose I have the following C++ class:
class Foo
{
double bar(double sth);
};
double Foo::bar(double sth)
{
double a,b,c,d,e,f
a = b = c = d = e = f = 0;
/* do stuff with a..f and sth */
}
The function bar() will be called millions of times in a loop. Obviously, each time it's called, the variables a..f have... | Access to stack-allocated variables is faster than to class members. Stack variables are dereferenced using stack pointer, without using of a class pointer. Add new class members only if it is required by program algorithm. Initialize stack variables directly in declaration:
double a = 0.0, b = 0.0 ...
|
2,956,309 | 2,956,350 | UIDs for data objects in MySQL | I am using C++ and MySQL.
I have data objects I want to persist to the database. They need to have a unique ID for identification purposes. The question is, how to get this unique ID?
Here is what I came up with:
1) Use the auto_increment feature of MySQL. But how to get the ID then? I am aware that MySQL offers this "... | The query:
SELECT LAST_INSERT_ID()
will return the last ID inserted on your specific connection, not globally. So there is no race condition, unless your own code is multi-threaded, in which case you would want to surround the INSERT and the SELECT with an MT lock of some sort.
|
2,956,331 | 2,956,375 | How to use cppcheck's inline suppression filter option for C++ code? | I would like to use Cppcheck for static code analysis of my C++ code. I learned that I can suppress some kind of warnings with --inline-suppr command.
However, I can't find what "suppressed_error_id" I should put in the comment:
// cppcheck-suppress "suppressed_error_id"
| According to the cppcheck help:
The error id is the id that you want
to suppress. The easiest way to get it
is to use the --xml command line flag.
Copy and paste the id string from the
xml output.
So run cppcheck against some code that contains the error with the --xml flag, and then look in the generated XML... |
2,956,394 | 2,957,000 | Problem with "write" function in linux | I am trying to write 2 server/client programs under Linux, in which they communicate through named pipes. The problem is that sometimes when I try to write from the server into a pipe that doesn't exist anymore (the client has stopped), I get a "Resource temporarily unavailable" error and the server stops completely.
... | If you wish that write() to returns -1 on error (and set errno to EPIPE) instead of stopping your server completly when the write end of your pipe is unconnected, you must ignore the SIGPIPE signal with signal( SIGPIPE, SIG_IGN ).
|
2,956,398 | 2,956,993 | Static libpng link with visual studio 2010 | I'm trying to add PNG support to my application and thus I want to include libpng. I know it needs zlib and thus I downloaded that as well. I went into the png folder/projects/vstudio and I opened the solution. I compiled it and it went just fine. I added some headers from it into my application and I copied the lib fi... | To make all your libraries static, you would have to recompile everything "from scratch" as static libraries.
This simply means you should create a set of projects for each library you have in your sequence and set the output type to static library.
After that you should eliminate library dependencies between the lib... |
2,956,404 | 2,956,481 | Type casting in C++ by detecting the current 'this' object type | My question is related to RTTI in C++ where I'm trying to check if an object belongs to the type hierarchy of another object. The BelongsTo() method checks this.
I tried using typeid, but it throws an error and I'm not sure about any other way how I can find the target type to convert to at runtime.
#include <iostream... | This doesn't make sense - the very fact that you can call the function means that the parameter belongs to the X hierarchy, as that is the type of the parameter. Dynamic casts are intended to find out the actual type within a known hierarchy.
The syntax error in your code:
return dynamic_cast<typeid(*p_a)*>(this) != NU... |
2,956,419 | 2,956,732 | C++ template-function -> passing a template-class as template-argument | i try to make intensive use of templates to wrap a factory class:
The wrapping class (i.e. classA) gets the wrapped class (i.e. classB) via an template-argument to provide 'pluggability'.
Additionally i have to provide an inner-class (innerA) that inherits from the wrapped inner-class (innerB).
The problem is the follo... | Line 32 should read:
return A::template createInnerBs<innerA>(b);
since createInnerBs is dependent on the template parameter A.
You'll also need to make the constructors of innerA and innerB public.
|
2,956,608 | 2,956,751 | write a MIDI file in C++ | Hi I Have some problems finding the right information about this and would be glad if someone could point me in the right direction.
How do you code a midifile? e.g. how can I write a snippet that plays a random tone for 1 second.
Basically what I would need to get done is representing differnet midi melodys as vectors... | You could also read up on the MIDI file spec (quick search turned up this) and generate the file yourself. Using a library is probably easier, but the MIDI file format isn't too complicated, especially if you already know how MIDI works (eg. note on/note off messages).
|
2,956,637 | 2,956,927 | QT4 Designer - Implement Widget | I'm currently trying to get into QT4 and figure out a workflow for myself.
While trying to create a widget which allows the user to connect to a hostname:port some questions appeared. The widget itself contains a LineEdit for entering the hostname, a SpinBox for entering the port and a PushButton which should emit a co... | I think I've found the answer myself. (Why does it need 2-3h of reading through tutorials etc until I give up and ask the question at Stackoverflow and then 5min after continuing to search, I find the solution myself? -.-)
I think the chapter of the QT-Documentation is describing how to use uic-generated files in an ow... |
2,957,062 | 2,957,601 | Using an array of derived objects as an array of base objects when the sizes are the same (CComVariant/VARIANT) | I'm using code that treats an array of derived objects as an array of base objects. The size of both objects is the same. I'm wondering:
Is this safe in practice, bearing in mind that the code will only ever be compiled on Microsoft compilers?
Here's my example:
BOOST_STATIC_ASSERT(sizeof(VARIANT)==sizeof(CComVariant... | Yes, CComVariant was designed to be a direct substitute for VARIANT. It derives from the variant structure and adds no virtual members nor fields (and no virtual destructor) to ensure the memory layout is the same. Lots of little helper classes like that in ATL/MFC, like CRect, CPoint etc.
|
2,957,352 | 2,957,469 | Code assistance in Netbeans on Linux | My IDE (NetBeans) thinks this is wrong code, but it compiles correctly:
std::cout << "i = " << i << std::endl;
std::cout << add(5, 7) << std::endl;
std::string test = "Boe";
std::cout << test << std::endl;
It always says unable to resolve identifier .... (.... = cout, endl, string);
So I think it has something to do w... | It works fine for me. I'm using NetBeans 6.8; the only undefined reference I got was for the add() function.
Can you test with a new project to see if you can reproduce the problem?
EDIT (reply):
Yep, tested on Linux. No includes added in project properties.
In the global C/C++ options I have an extra include path for... |
2,957,715 | 3,151,685 | right click event in opencv | I am developing a computer vision program using OpenCV (IDE = devcpp). I am able to get the hand contour , move cursor position according to our our hand. i want to implement right click functionality .Please help me with it .
i am using event SetCursorPos(x,y) to set the cursor position on the screen.
is there any si... | Maybe this will help: http://www.codeguru.com/forum/showthread.php?t=377394
void RightClick ( )
{
INPUT Input={0};
// right down
Input.type = INPUT_MOUSE;
Input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN;
::SendInput(1,&Input,sizeof(INPUT));
// right up
::ZeroMemory(&Input,sizeof(INPUT));
Input.typ... |
2,957,759 | 2,957,897 | Using gprof with sockets | I have a program I want to profile with gprof. The problem (seemingly) is that it uses sockets. So I get things like this:
::select(): Interrupted system call
I hit this problem a while back, gave up, and moved on. But I would really like to be able to profile my code, using gprof if possible. What can I do? Is t... | The socket code needs to handle interrupted system calls regardless of profiler, but under profiler it's unavoidable. This means having code like.
if ( errno == EINTR ) { ...
after each system call.
Take a look, for example, here for the background.
|
2,957,872 | 2,957,899 | C++: Print only one char | When I read one char* from std::cin and I want to write it to std::cout, it prints until it finds a \0 in memory. So what did was:
char c;
cin >> c;
char* pChar = &c;
pChar++;
*pChar = '\0';
println(&c); // My own method: void println(char * str) { cout << str << endl; }
But I don't think this is a safe action.
Is the... | Simply:
char c;
cin >> c;
cout << c;
|
2,957,923 | 2,958,067 | boost::filesystem - how to create a boost path from a windows path string on posix platforms? | I'm reading path names from a database which are stored as relative paths in Windows format, and try to create a boost::filesystem::path from them on a Unix system. What happens is that the constructor call interprets the whole string as the filename. I need the path to be converted to a correct Posix path as it will b... | Unfortunately the Windows path grammar is conditionally compiled, and only included when compiling on Windows. I don't understand why they have done this. Anyway, this means you have at most two parsers available at all times; the portable one, which is the same as the Posix one, and the native one, which depends on wh... |
2,957,984 | 2,958,064 | Why I have to redeclare a virtual function while overriding [C++] | #include <iostream>
using namespace std;
class Duck {
public:
virtual void quack() = 0;
};
class BigDuck : public Duck {
public:
// void quack(); (uncommenting will make it compile)
};
void BigDuck::quack(){ cout << "BigDuckDuck::Quack\n"; }
int main() {
BigDuck b;
Duck *d = &b;
... | The redeclaration is needed because:
The standard says so.
It makes the compiler's work easier by not climbing up the hierarchy to check if such function exists.
You might want to declare it lower in the hierarchy.
In order to instantiate the class the compiler must know that this object is concrete.
|
2,958,007 | 2,958,014 | What does the "L" mean at the end of an integer literal? | I have this constant:
#define MAX_DATE 2958465L
What does the L mean in this sense?
| It is a long integer literal.
Integer literals have a type of int by default; the L suffix gives it a type of long (Note that if the value cannot be represented by an int, then the literal will have a type of long even without the suffix).
|
2,958,114 | 2,958,261 | Handling EINTR (with goto?) | Background: This is a follow-up question to this thread about handling EINTR for system calls in C++ (Linux/GCC). Regardless of whether or not I intend to profile my application, it seems like I should be handling system calls setting errno to EINTR as a special case. There are many, many, many opinions about the use... | As far as I know the socket system call can't return with errno set to EINTR.
For other cases I use a loop:
while ((::connect(sock, (struct sockaddr *)&destAddress, sizeof(struct sockaddr))) == -1) {
if (errno == EINTR) {
LOGERROR("connect interrupted, retry");
continue;
} else if (errno == EINP... |
2,958,137 | 2,958,260 | cannot not find library files in eclipse cdt | properties/C/C++ Build/Settings
GCC C++ Linker/Libraries
Under libraries(-I) I have
libbost_system
libbost_filesystem
...
and under Library search path(-L) I have
/home/etobkru/boost_1_43_0/boostBinaries/lib
but when I compile I get
g++ -L/home/etobkru/boost_1_43_0/boostBinaries/lib/ -o"searchDirs" ./main.o -llibb... | You don't need the "lib" part in the name. Just link with
-lboost_system -lboost_filesystem -lboost_regex
|
2,958,142 | 2,958,315 | How do boost operators work? | boost::operators automatically defines operators like + based on manual implementations like += which is very useful. To generate those operators for T, one inherits from boost::operators<T> as shown by the boost example:
class MyInt : boost::operators<MyInt>
I am familiar with the CRTP pattern, but I fail to see how i... | There's a big multiple inheritance chain, at the top of which there are a number of classes that implement the operators, but do so as friend functions, thus placing them in the enclosing namespace rather than as members of the class.
For example, the final implementation of operator+ becomes:
template <class T, class ... |
2,958,226 | 2,970,441 | How do I create a set with std::pair thats sorted based on the ::second pair member using bind | I know I could use the following:
template <typename Pair>
struct ComparePairThroughSecond : public std::unary_function<Pair, bool>
{
bool operator ()(const Pair& p1, const Pair& p2) const
{
return p1.second < p2.second;
}
};
std::set<std::pair<int, long>, ComparePairThroughSecond> somevar;
... | How about the following one. I'm using boost::function to 'erase' the actual type of the comparator. The comparator is created using boost:bind itself.
typedef std::pair<int, int> IntPair;
typedef boost::function<bool (const IntPair &, const IntPair &)> Comparator;
Comparator c = boost::bind(&IntPair::second, _1)... |
2,958,285 | 2,958,332 | C++ refactor common code with one different statement | I have two methods f(vector<int>& x, ....) and g(DBConn& x, ....)
where the (....) parameters are all identical.
The code inside the two methods are completely identical except for one statement
where we do different actions based on the type of x:
in f(): we do x.push_back(i)
in g(): we do x.DeleteRow(i)
What is the... | You could write a simple adapter with two implementations, each calling the desired method of a different class.
class MyInterface {
public:
virtual doIt(int i) = 0;
}
class VectorImp : public MyInterface {
public:
vector<int>& v;
VectorImp(vector<int>& theVector) : v(theVector) {}
doIt(int i) { x.push_back(i)... |
2,958,398 | 2,958,415 | GNU C++ how to check when -std=c++0x is in effect? | My system compiler (gcc42) works fine with the TR1 features that I want, but trying to support newer compiler versions other than the systems, trying to accessing TR1 headers an #error demanding the -std=c++0x option because of how it interfaces with library or some hub bub like that.
/usr/local/lib/gcc45/include/c++/b... | If you compile with -std=c++0x, then __GXX_EXPERIMENTAL_CXX0X__ will be defined.
|
2,958,416 | 2,958,481 | Call c++ library from c# | This question might seem a repeat of previous ones. I have read through a series of posts, but not completely clear for my situation.
I have a c++ library which is created using momentics IDE. I have to be able to use this library into a c# project.
Someone had been working on this project before being handed over to ... | Given that you're using a C++ library, I'm assuming it takes advantage of C++ semantics like classes, rather than just exposing procedures. If this is the case, then the way this is typically done is via a manually-created managed C++ interop library.
Basically, you create a managed C++ library in Visual Studio, refere... |
2,958,457 | 15,554,949 | gcc -Wshadow is too strict? | In the following example:
class A
{
public:
int len();
void setLen(int len) { len_ = len; } // warning at this line
private:
int len_;
};
gcc with -Wshadow issue a warning:
main.cpp:4: warning: declaration of `len' shadows a member of `this'
function len and integer len are of different type. Why the ... | This seems to be solved on newer versions of GCC.
From version 4.8
changelog:
The option -Wshadow no longer warns if a declaration shadows a function declaration,
unless the former declares a function or pointer to function, because this is a common
and valid case in real-world code.
And it references Linus Torvalds'... |
2,958,610 | 3,882,067 | Event Log Oldest Record Number | I'm trying to use the new event log API to get the oldest record number from a windows event log, but cannot get the the API to return the same answer as event viewer displays (looking at the details EventRecordID). Some sample code I'm using is below:
EVT_HANDLE log = EvtOpenLog(NULL, _logName, EvtOpenChannelPath);
E... | I was not able to get the new API to work for the oldest record number and had to revert to using the legacy API to retrieve the oldest record number.
msdn.microsoft.com/en-us/library/aa363665(VS.85).aspx
|
2,958,648 | 4,241,547 | What are the pitfalls of ADL? | Some time ago I read an article that explained several pitfalls of argument dependent lookup, but I cannot find it anymore. It was about gaining access to things that you should not have access to or something like that. So I thought I'd ask here: what are the pitfalls of ADL?
| There is a huge problem with argument-dependent lookup. Consider, for example, the following utility:
#include <iostream>
namespace utility
{
template <typename T>
void print(T x)
{
std::cout << x << std::endl;
}
template <typename T>
void print_n(T x, unsigned n)
{
for (u... |
2,958,694 | 3,042,040 | Recommended migration strategy for C++ project in Visual Studio 6 | For a large application written in C++ using Visual Studio 6, what is the best way to move into the modern era?
I'd like to take an incremental approach where we slowly move portions of the code and write new features into C# for example and compile that into a library or dll that can be referenced from the legacy ap... | Faced with the same task, my strategy would be something like:
Identify what we hope to gain by moving to 2010 development - it could be
improved quality assurance: unit testing, mocking are part of modern development tools
slicker UI: WPF provides a modern look and feel.
productivity: in some areas, .NET development... |
2,958,747 | 2,958,802 | What is the nicest way to parse this in C++? | In my program, I have a list of "server address" in the following format:
host[:port]
The brackets here, indicate that the port is optional.
host can be a hostname, an IPv4 or IPv6 address (possibly in "bracket-enclosed" notation).
port, if present can be a numeric port number or a service string (like: "http" or "ss... | Have you looked at boost::spirit? It might be overkill for your task, though.
|
2,958,836 | 2,958,887 | What is this conversion called? | Is there a name or a term for this type of conversion in the c++ community?
Has anyone seen this conversion be referred to as "implicit conversion"?
class ALPHA{};
class BETA{
public:
operator ALPHA(){return alpha;}
private:
ALPHA alpha;
};
void func(ALPHA alpha){}
int main(){
BETA beta;... | It's normally called a conversion function. It isn't an implicit conversion per se, but does allow implicit conversion to the target type.
Edit: just checked to be sure -- §12.3.2 of the standard uses the phrase "conversion function".
Edit2: I checked in the official standard, which isn't (at least supposed to be) free... |
2,959,069 | 2,959,080 | C++ memcpy from double array to float array | Is is possible to memcpy from a double array to a float array safely?
| Depends on what you want. The values certainly won't be preserved. If you need that, use std::copy.
#include <algorithm>
int main()
{
double a[] = {1.618, 3.1416, 2.7, 0.707, 1.0};
float b[5];
std::copy(a, a + 5, b);
}
|
2,959,164 | 2,959,210 | Extract a C/C++ header file from a C# class exposed to COM | I'm not sure I've setup everything I've needed to in my C# class to properly, but it does work in COM. I've been looking for an example of a C# class that was successfully used in a C/C++ project, but haven't come across anything.
I've tried using the OLE/COM Object View app to open the .tlb file and save as .h, but it... | If you have a tlb you do not need a header file. #import of the tlb will generate it for you automatically.
#import "my.tlb" named_guids raw_interfaces_only
See more about #import here.
|
2,959,297 | 2,959,376 | Is there any C\C++ Cross-platform library for sharing data between app's? | Is there any C\C++ Cross-platform library for sharing data between app's?
| Google's Protocol Buffers might fit the bill.
|
2,959,473 | 2,959,829 | Setting Environment Variables For NMAKE Before Building A 'Makefile Solution' | I have an MSVC Makefile Project in which I need to set an environment variable before running NMAKE. For x64 builds I needs to set it to one value, and for x86 builds I need to set it to something else.
So for example, when doing a build I would want to SET PLATFORM=win64 if I'm building a 64-bit compile, or SET PLATF... | Just edit the Configuration Properties + NMake + Build Command Line. Click the button with the dots and enter something like this:
set PLATFORM=win32
nmake -f makefile.mak
Repeat for your 64-bit configuration.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.