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,642,131 | 2,642,176 | Ideas for a C/C++ library | I thought one of the best ways to familiarise myself with C/C++, is to make a helpful library. I was maybe thinking like a geometry library, like to calculate areas, surface area, etc. It would be useful in game programming. Or maybe an algebra library, like for different formulas like the distance formula, quadratic formula, etc. Or maybe like a standard library for very simple functions, like calculating the number of items in an array.
| If it is for the sake of an exercise, writing a library to deal with fractions is a good one.
http://en.wikipedia.org/wiki/Fraction_(mathematics)
Implement the basic operations and a way to print them.
|
2,642,165 | 2,642,266 | Is it okay to implement reference counting through composition? | Most common re-usable reference counted objects use private inheritance to implement re-use. I'm not a huge fan of private inheritance, and I'm curious if this is an acceptable way of handling things:
class ReferenceCounter {
std::size_t * referenceCount;
public:
ReferenceCounter()
: referenceCount(NULL) {};
ReferenceCounter(ReferenceCounter& other)
: referenceCount(other.referenceCount) {
if (!referenceCount) {
referenceCount = new std::size_t(1);
other.referenceCount = referenceCount;
} else {
++(*referenceCount);
}
};
ReferenceCounter& operator=(const ReferenceCounter& other) {
ReferenceCounter temp(other);
swap(temp);
return *this;
};
void swap(ReferenceCounter& other) {
std::swap(referenceCount, other.referenceCount);
};
~ReferenceCounter() {
if (referenceCount) {
if (!*referenceCount)
delete referenceCount;
else
--(*referenceCount);
}
};
operator bool() const {
return referenceCount && (*referenceCount != 0);
};
};
class SomeClientClass {
HANDLE someHandleThingy;
ReferenceCounter objectsStillActive;
public:
SomeClientClass() {
someHandleThingy = RegCreateKeyEx(...);
}
~SomeClientClass() {
if (objectsStillActive)
return;
RegCloseKey(someHandleThingy);
};
};
or are there subtle problems with this I'm not seeing?
EDIT
I'm not super duper concerned with this particular implementation (it probably has bugs -- I'm going to spend some time looking at shared_ptr's innards before using something like this in production code) -- I'm just concerned if in general there is a specific reason reusable reference counting goodies always seem to be implemented using inheritance rather than composition.
| You have to remember to copy the counter when copying the handle. You might prefer not to pass operating system types into templates, but I think safety here requires inheritance. (Not inheritance from HANDLE, though.)
HANDLE might also be something of a special case because it's POD. Essentially you have a pointer of type besides T*.
I see the motivation that you want something besides delete to happen when the count goes to zero. An adaptation of smart_ptr would probably work, and you might not be that far from just that.
|
2,642,199 | 2,642,333 | Qt/C++ - confused about caller/callee, object ownership | I am creating a GUI to manipulate a robot arm. The location of the arm can be described by 6 floats (describing the positions of the various arm joints.
The interface consists of a QGraphicsView with a diagram of the arm (which can be clicked to change the arm position - adjusting the 6 floats). The interface also has 6 lineEdit boxes, to also adjust those values separately.
When the graphics view is clicked, and when the line edit boxes are changed, I'd like the line edit boxes / graphics view to stay in synchronisation.
This brings me to confusion about how to store the 6 floats, and trigger events when they're updated. My current idea is this:
The robot arm's location should be represented by a class, RobotArmLocation. Objects of this class then have methods such as obj.ShoulderRotation() and obj.SetShoulderRotation().
The MainWindow has a single instance of RobotArmLocation.
Next is the bit I'm more confused about, how to join everything up. I am thinking:
The MainWindow has a ArmLocationChanged slot. This is signalled whenever the location object is changed.
The diagram class will have a SetRobotArmLocation(RobotArmLocation &loc). When the diagram is changed, it's free to change the location object, and fire a signal to the ArmLocationChanged slot.
Likewise, changing any of the text boxes will fire a signal to that ArmLocationChanged slot. The slot then has code to synchronise all the elements.
This kind of seems like a mess to me, does anyone have any other suggestions? I've also thought of the following, does it have any merrit?
The RobotArmLocation class has a ValueChanged slot, the diagram and textboxes can use that directly, and bypass the MainWindow directly (seems cleaner?)
thanks for any wisdom!
| Except for really simple cases (e.g. a label that shows the value of a slider) my experience has been to stay away from inter-component signal/slot connections inside Qt Designer. Rather, have the component firing the signal of interest connect to a slog defined in the top level QWidget class you're subclassing (i.e. QMainWidow, etc... let's just call it the Form class). You can also go the other way: if you have a custom signal in the Form class, you can connect it with Qt Designer to one of the public widget slots.
To be specific using your example:
I'm going to assume that you have subclassed QMainWindow and QGraphicsView. Let's call the subclasses RobotMainWindow and RobotView.
RobotMainWindow contains the QLineEdit fields and RobotView. The way you specify RobotView in Qt Designer is to insert a QWidget and use the Promote to... feature to tell Qt that the QWidget should be replaced at compile time with your custom RobotView.
Name the QLineEdit fields edit1, edit2...edit6.
In the Qt Designer signal/slot editor define slots in RobotMainWindow to be called when the value in a QLineEdit changes. There are some more elegant ways of doing this, but for simplicity let's say you define 6 slots named setValue1(float), setValue2(float), etc.
In the source code for RobotMainWindow, go declare and define these slots, such that they update your arm, shoulder, whatever.
Also in the source code, define a signal valueChanged() (or multiple for each field, your choice). Have the slots you defined emit valueChanged().
Back in Qt Designer you can now link the appropriate signal from each QLineEdit to the corresponding slot in RobotMainWindow.
Back in the signal/slot editor add the valueChanged() signal to the RobotMainWindow (so Qt Designer knows about it). Connect this signal to a new slot in RobotView, using the procedure above, so it can update the rendering.
Repeat all of this for handling changes from RobotView to the editing fields (via RobotMainWindow.
In short, I think you'll find everything more straight-forward if your route the signals through your Form subclass (which I think of as the Controller in MVC parlance).
|
2,642,242 | 2,644,641 | Displaying a popup widget in QT over application border | Let's say that I have an application frame, and I want to show a popup QCalendarWidget over on the right side of the frame. Normally, QT will clip the edges of the QCalendarWidget, cutting it in half and not displaying the rest, as it would be over the right side border.
Is there a way to work around this limitation without resorting to implementing a QDialog?
I want the widget to be visible outside the bounds of it's container.
| If you'd show your Calendar, let's say, after a button click, as QDateTimeEditor does, it's contents will not be clipped, cause it do not belong to frame. It will be just a widget, that shows in a dialog manner. And maybe you should even place it in QDialog, that is modal and provides some convenience methods, rather then simple QWidget.
Btw, why don't you want to use QDatetimeEditor?
|
2,642,321 | 2,642,341 | static function in an abstract class | How to implement a static function in an abstract class?? Where do I implement this?
class Item{
public:
//
// Enable (or disable) debug descriptions. When enabled, the String produced
// by descrip() includes the minimum width and maximum weight of the Item.
// Initially, debugging is disabled.
static enableDebug(bool);
};
| First of all, that function needs a return type. I'll assume it's supposed to be void.
You implement it in a source file, just as you would implement any other method:
void Item::enableDebug(bool toggle)
{
// Do whatever
}
There's nothing special about it being static or the Item class being abstract. The only difference is that you do not have access to a this pointer (and consequently also not to member variables) within the method.
|
2,642,373 | 2,642,379 | converting an int to char* | This is a very very basic question and I know one way is to do the following:
char buffer[33];
itoa(aq_width, buffer,10);
where aq_width is the int, but then I can't guarantee what size of buffer I would need in order to do this... I can always allocate a very large buffer size, but that wouldn't be very nice... any other pretty and simple way to do this?
| std::stringstream ss;
ss << 3;
std::string s = ss.str();
assert(!strcmp("3", s.c_str()));
|
2,642,385 | 27,619,955 | Throwing a C++ exception after an inline-asm jump | I have some odd self modifying code, but at the root of it is a pretty simple problem: I want to be able to execute a jmp (or a call) and then from that arbitrary point throw an exception and have it caught by the try/catch block that contained the jmp/call.
But when I do this (in gcc 4.4.1 x86_64) the exception results in a terminate() as it would if the exception was thrown from outside of a try/catch. I don't really see how this is different than throwing an exception from inside of some far-flung library, yet it obviously is because it just doesn't work.
How can I execute a jmp or call but still throw an exception back to the original try/catch? Why doesn't this try/catch continue to handle these exceptions as it would if the function was called normally?
The code:
#include <iostream>
#include <stdexcept>
using namespace std;
void thrower()
{
cout << "Inside thrower" << endl;
throw runtime_error("some exception");
}
int main()
{
cout << "Top of main" << endl;
try {
asm volatile (
"jmp *%0" // same thing happens with a call instead of a jmp
:
: "r"((long)thrower)
:
);
} catch (exception &e) {
cout << "Caught : " << e.what() << endl;
}
cout << "Bottom of main" << endl << endl;
}
The expected output:
Top of main
Inside thrower
Caught : some exception
Bottom of main
The actual output:
Top of main
Inside thrower
terminate called after throwing an instance of 'std::runtime_error'
what(): some exception
Aborted
| If you are using gcc 4.4.7(and above) on x86-64 linux, with dwarf exception handle mechanism (which might be the default one), I have a way to work this out.
Suppose your inline assembly code is a function inline_add. It'll call another function add, which might throw a exception. Here's code:
extern "C" int add(int a, int b) {
throw "in add";
}
int inline_add(int a, int b) {
int r = 0;
__asm__ __volatile__ (
"movl %1, %%edi\n\t"
"movl %2, %%esi\n\t"
"call add\n\t"
"movl %%eax, %0\n\t"
:"=r"(r)
:"r"(a), "r"(b)
:"%eax"
);
return r;
}
If you call inline_add like this:
try {
inline_add(1, 1);
} catch (...) {
std::cout << "in catch" << std::endl;
}
it'll crash, because gcc doesn't provide the exception frame for inline_add. When it comes to a exception, it has to crach. (see here for the 'Compatibility with C')
So we need to fake a exception frame for it, but it would be hard to hack with gcc assembly, we just use functions with proper exception frame to surround it
we define a function like this:
void build_exception_frame(bool b) {
if (b) {
throw 0;
}
}
and call inline_add like this:
try {
inline_add(1, 1);
build_exception_frame(false);
} catch (...) {
std::cout << "in catch" << std::endl;
}
and it just works.
build_exception_frame should come after the call, or it won't work
Further more, to prevent optimiziong gcc might take on build_exception_frame, we need to add this:
void build_exception_frame(bool b) __attribute__((optimize("O0")));
You can check the assembly code that gcc generates to verify the code.
It seems that gcc provide exception frame for the whole try/catch, as long as there's one function might throw, and position matters.
Need to see how gcc works on that later.
If any knows about that, please be kind enough to let me know. Thanks.
|
2,642,424 | 2,642,440 | Is VERIFY(...) a good practice in C++ coding? | Also, how does it compare to throwing an exception when something goes wrong ?
| VERIFY() serves the same purpose as ASSERT() (or the standard library assert()) - to let you catch things that really shouldn't ever™ be happening (i.e. a true code bug, something that should be fixed before release). The kinds of things that if for some reason the expression is false, there's no point to continuing because something is horribly, horribly wrong.
This is reflected in the fact that VERIFY() only stops the program on a false evaluation when compiling in Debug mode - in Release mode, it's transparent. The difference between VERIFY() and ASSERT() is that VERIFY() will still evaluate the expression in Release mode, it simply won't care about the result - whereas ASSERT() is completely removed from the program when compiling in Release mode and thus any side-effects of the expression within it won't take place.
Exceptions are more useful for things that might go wrong, but can be recovered from, since exceptions can be handled by other parts of the program.
|
2,642,509 | 2,642,525 | Removing elements from C++ std::vector | What is the proper way to remove elements from a C++ vector while iterating through it? I am iterating over an array and want to remove some elements that match a certain condition. I've been told that it's a bad thing to modify it during traversal.
I guess I should also mention that this is an array of pointers that I need to free before removing them.
EDIT:
So here's a snippet of my code.
void RoutingProtocolImpl::removeAllInfinity()
{
dv.erase(std::remove_if(dv.begin(), dv.end(), hasInfCost), dv.end());
}
bool RoutingProtocolImpl::hasInfCost(RoutingProtocolImpl::dv_entry *entry)
{
if (entry->link_cost == INFINITY_COST)
{
free(entry);
return true;
}
else
{
return false;
}
}
I'm getting the following error when compiling:
RoutingProtocolImpl.cc:368: error: argument of type bool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry*)' does not matchbool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry)'
Sorry, I'm kind of a C++ newb.
| bool IsEven (int i)
{
return (i%2) == 0;
}
//...
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.erase(std::remove_if(v.begin(),v.end(),IsEven), v.end());
//v now contains 1 and 3
|
2,642,511 | 2,642,538 | Is the old vector get cleared? If yes, how and when? | I have the following code:
void foo()
{
vector<double> v(100,1); // line 1
// some code
v = vector<double>(200,2); // line 2
// some code
}
what happened to the vector of size 100 after the second line? Is it gets cleared by itself? If the answer is yes, how and when it is cleared?
By the way, is there any other "easy and clean" ways to change the vector as in line 2? I don't want things like
v.resize(200);
for (int i=0; i<200; i++) v[i] = 2;
Another question. What if the vector is a member of a class:
class A{
public:
vector<double> data;
A(int size, double value)
{
data = vector<double>(size,value);
}
};
A object(10,1);
// some code
object = A(20,2); // ** What happened to the old object.data? **
// some code
| In the assignment, first a temporary vector object is created that contains 200 times the element 2. Then this temporary object is assigned to v: The vector v removes all the elements it currently contains and copies the contents of the temporary vector object. At the end of the statement the temporary vector object is destroyed again.
To do this more concisely without creating a temporary object you can use the assign() method:
v.assign(200, 2);
|
2,642,535 | 2,642,547 | Using a constructor for return | Just a quick question.
I've written some code that returns a custom class Command, and the code I've written seems to work fine. I was wondering if there are any reasons that I shouldn't be doing it this way. It's something like this:
Command Behavior::getCommand ()
{
char input = 'x';
return Command (input, -1, -1);
}
Anyway, I read that constructors aren't meant to have a return value, but this works in g++.
Thanks for any advice,
Rhys
| The constructor itself doesn't have a return value. What this does is constructs a temporary Command object and returns the constructed objet to the caller. It's effectively the same as if you said:
Command temp(input, -1, -1);
return temp;
It will work on any C++ compiler.
|
2,642,579 | 2,642,600 | Who can give me a link for the operator= of vector in MSDN? | Who can give me a link for the operator= of vector in MSDN?
Why I can only find operator[]?
If operator= is just something default, like copy everything in A to B, how this following code works?
vector<double> v(100,1);
v = vector<double>(200,2); // if operator= is just a trivail version, how to make sure the old v get cleared?
| std::vector is part of the STL, so any description of std::vector will do. The underlying implementation may differ slightly, but all conformant versions of STL must provide the same interface and the same guarantees for std::vector. I can't find in quickly on MSDN, but here are two such descriptions of operator=:
http://www.cplusplus.com/reference/stl/vector/operator=/
http://www.sgi.com/tech/stl/Vector.html
Now, the second part of your question puzzles me. What would you expect operator= to do on a vector if not "copy everything from A into B"?
In your example, your question was "how to make sure the old v get cleared?". I can interpret this in one of two ways: You might be asking "how do I know that this assignment v = vector<double>(200,2) will overwrite the contents of v and not append to it?". The answer is that you know that because that's the definition of how operator= works for STL containers. Any standards compliant implementation is guaranteed to work that way.
You might also be asking "what happens to the contents of v when I overwrite them using the assignment v = vector<double>(200,2)?" The answer is that they are deallocated, and if they are objects, their destructors are called. Note the important distinction that if the vector contains pointers to objects, the pointers themselves are deallocated, but not what they point to.
If I didn't answer your question, please try to clarify it.
|
2,642,618 | 2,642,636 | '??' is getting converted into '^' in Visual C++. Why is it happening and what is the way out? | '??' gets converted into '^' if I compile mn VC++ program and run it
e.g.
sprintf( ch, "??")
prints out
^
But if I run the same code in Turbo C/C++, there is no such problem. Why is it happening on VC++ on Windows?
| ?? alone is not a trigraph, although ??' corresponds to ^.
Perhaps you typed it here different from what you have in code and you can't see the trailing single quote in your string because it's too close to the closing quote.
So in code you probably have:
sprintf( ch, "??'");
|
2,642,671 | 2,642,682 | C++ compilation error when passing a function into remove_if | So here's a snippet of my code.
void RoutingProtocolImpl::removeAllInfinity()
{
dv.erase(std::remove_if(dv.begin(), dv.end(), hasInfCost), dv.end());
}
bool RoutingProtocolImpl::hasInfCost(RoutingProtocolImpl::dv_entry *entry)
{
if (entry->link_cost == INFINITY_COST)
{
free(entry);
return true;
}
else
{
return false;
}
}
I'm getting the following error when compiling:
RoutingProtocolImpl.cc:368: error: argument of type bool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry*)' does not matchbool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry)'
| The problem is that this: bool RoutingProtocolImpl::hasInfCost(...) is a nonstatic member function.
It requires an instance of the class to invoke on, ala: obj->hasInfCost(...). However, remove_if cares not and tries to call it as hasInfCost(...). These are incompatible.
What you can do is make it static:
static bool RoutingProtocolImpl::hasInfCost(RoutingProtocolImpl::dv_entry *entry) This no longer requires an instance of the class to invoke. (It has no member variables, no this pointer, etc.). It can be treated as a "normal" function.
|
2,642,691 | 2,642,702 | Call a non member function on an instance before is constructed | I'm writing a class, and this doubt came up. Is this undef. behaviour? On the other hand, I'm not sure its recommended, or if its a good practice. Is it one if I ensure no exceptions to be thrown in the init function?
//c.h
class C{
float vx,vy;
friend void init(C& c);
public:
C();
};
//c.cpp
C::C()
{
init(*this);
}
void init(C& c) //throws() to ensure no exceptions ?
{
c.vx = 0;
c.vy = 0;
}
Thanks in advance
| It's completely fine. Once you enter the body of the constructor, all the members have been initialized and they are ready to use. (The body is then to finish up any more work that needs to be done to create a fully constructed object.)
But it is poor style. Better is just:
C::C() :
vx(), vy() // or vx(0), vy(0) if you prefer to be explicit
{}
And do away with all the mess.
Exceptions have nothing to do with safety, constructors are free to throw. In fact, if you can't successfully construct an object then throwing an exception is the preferred course of action.
|
2,642,809 | 2,642,851 | Is there a better way than #if DebugMode for logging | I'm making a c++ library thats going to be P/Invoked from c#, so i am unable to breakpoint/debug the c++ side of things. So i decided to add logging so i can see if anything goes wrong and where it happens. I add a #define DebugMode 1 in order to determine if i am to log or not.
First of all i'm not very good at c++ but i know enough to get around. So my questions are:
Is there a better way than wrapping #if DebugMode #endifs around every Log call? I could simply do that inside the Log method and just return if logging isn't enabled but won't that mean then all those logging strings will be in the assembly?
How can i emulate what printf does with its "..." operator enabling me to pass something like Log("Variable x is {0}", x);
Is there any tricks such as getting the line number or stack trace information of some sort that i can use in the log?
Thanks!
| One simple way is to just define a macro that does nothing if you're not in debug mode. That way you don't have to wrap every call in an #ifdef.
A simple implementation might be:
#if DebugMode
#define MY_LOG(string, ...) printf(string, __VA_ARGS__)
#else
#define MY_LOG(string, ...)
#endif
There are other ways and libraries (such as boost) but this will get you something quickly.
|
2,642,825 | 2,644,887 | the choice for video capture in Mac OSX? | What is the best choice for webcam video/image capture under Mac OSX with C/C++? It seems that Apple recommended QTKit, but it is a Objective-C library. Any sample code to do the job?
| You can use the Objective-C library from your C++ program indirectly. Just create a C interface to the Objective-C functions and compile it with your Objective-C compiler.
|
2,642,863 | 2,643,017 | C++ boost wave, scoped macro | Is it possible to have scoped macros using custom defined macros through boost wave?
I know it should a possible with C++0x however I am working with regular C++.
If it is possible, can you provide link or reference how to accomplish this?
Thanks
| I suspect that Wave doesn't support macro scoping anymore. Older documents such as:
http://boost-spirit.com/old_docs/wave_v0_9/preliminary_cpp0x_support.html#macro_scoping
Discuss support for macro scoping experimentally, but I can't find any mention of it in the newer docs:
http://www.boost.org/doc/libs/1_42_0/libs/wave/index.html
http://www.boost.org/doc/libs/1_42_0/libs/wave/doc/wave_driver.html
It appears that macro scoping is being left out of C++0x; I'm not sure if it's still being worked by anyone, or if it's been dropped altogether. Looking at the changelog for Boost Wave, it looks like support for scoped macros was removed from Version 1.1.7 in Aug 2004.
|
2,642,868 | 2,642,921 | Trying to use boost lambda, but my code won't compile | I am trying to use boost lambda to avoid having to write trivial functors.
For example, I want to use the lambda to access a member of a struct or call a method of a class, eg:
#include <vector>
#include <utility>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
using namespace std;
using namespace boost::lambda;
vector< pair<int,int> > vp;
vp.push_back( make_pair<int,int>(1,1) );
vp.push_back( make_pair<int,int>(3,2) );
vp.push_back( make_pair<int,int>(2,3) );
sort(vp.begin(), vp.end(), _1.first > _2.first );
When I try and compile this I get the following errors:
error C2039: 'first' : is not a member of 'boost::lambda::lambda_functor<T>'
with
[
T=boost::lambda::placeholder<1>
]
error C2039: 'first' : is not a member of 'boost::lambda::lambda_functor<T>'
with
[
T=boost::lambda::placeholder<2>
]
Since vp contains pair<int,int> I thought that _1.first should work. What I am doing wrong?
| What you want is something akin to:
#include <boost/lambda/bind.hpp> // new header
// typedefs make code easier
typedef pair<int,int> pair_type;
typedef vector<pair_type> vector_type;
vector_type vp;
vp.push_back( make_pair(1,1) ); // don't specify template arguments!
vp.push_back( make_pair(3,2) ); // the entire point of make_pair is
vp.push_back( make_pair(2,3) ); // to deduce them.
sort(vp.begin(), vp.end(),
bind(&pair_type::first, _1) > bind(&pair_type::first, _2) );
|
2,643,010 | 2,643,020 | Problem with std::map and std::pair | I have a small program I want to execute to test something
#include <map>
#include <iostream>
using namespace std;
struct _pos{
float xi;
float xf;
bool operator<(_pos& other){
return this->xi < other.xi;
}
};
struct _val{
float f;
};
int main()
{
map<_pos,_val> m;
struct _pos k1 = {0,10};
struct _pos k2 = {10,15};
struct _val v1 = {5.5};
struct _val v2 = {12.3};
m.insert(std::pair<_pos,_val>(k1,v1));
m.insert(std::pair<_pos,_val>(k2,v2));
return 0;
}
The problem is that when I try to compile it, I get the following error
$ g++ m2.cpp -o mtest
In file included from /usr/include/c++/4.4/bits/stl_tree.h:64,
from /usr/include/c++/4.4/map:60,
from m2.cpp:1:
/usr/include/c++/4.4/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = _pos]’:
/usr/include/c++/4.4/bits/stl_tree.h:1170: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(const _Val&) [with _Key = _pos, _Val = std::pair<const _pos, _val>, _KeyOfValue = std::_Select1st<std::pair<const _pos, _val> >, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’
/usr/include/c++/4.4/bits/stl_map.h:500: instantiated from ‘std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename _Alloc::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const std::pair<const _Key, _Tp>&) [with _Key = _pos, _Tp = _val, _Compare = std::less<_pos>, _Alloc = std::allocator<std::pair<const _pos, _val> >]’
m2.cpp:30: instantiated from here
/usr/include/c++/4.4/bits/stl_function.h:230: error: no match for ‘operator<’ in ‘__x < __y’
m2.cpp:9: note: candidates are: bool _pos::operator<(_pos&)
$
I thought that declaring the operator< on the key would solve the problem, but its still there.
What could be wrong?
Thanks in advance.
| The problem is this:
bool operator<(_pos& other)
Should be this:
bool operator<(const _pos& other) const {
// ^^^^ ^^^^^
Without the first const, the right-hand side of the comparison (b in a < b) cannot be const, since without const the function may modify its argument.
Without the second const, the left-hand side of the comparison (a in a < b) cannot be const, since without const the function may modify this.
Internally, the key's of a map are always const.
It should be noted that you should prefer to use nonmember functions. That is, better is a free-function:
bool operator<(const _pos& lhs, const _pos& rhs)
{
return lhs.xi < rhs.xi;
}
In the same namespace as your class. (For our example, just underneath it.)
By the way, in C++ there is no need to prefix the declaration of a struct type variable with struct. This is perfect, and preferred:
_pos k1 = {0,10};
_pos k2 = {10,15};
_val v1 = {5.5};
_val v2 = {12.3};
(Though your type names are admittedly named in an unorthodox manner. :P)
Lastly, you should prefer the make_pair utility function for making pairs:
m.insert(std::make_pair(k1,v1));
m.insert(std::make_pair(k2,v2));
It saves you from having to write out the types for the pair, and is generally easier to read. (Especially when longer type names come along.)
|
2,643,264 | 2,643,313 | Getting memory section information | Can somebody explain me how the following code works?
# if defined(__ELF__)
# define __SECTION_FLAGS ", \"aw\" , @progbits"
/* writable flag needed for ld ".[cd]tors" sections bug workaround) */
# elif defined(__COFF__)
# define __SECTION_FLAGS ", \"dr\""
/* untested, may be writable flag needed */
# endif
asm
(
".section .ctors" __SECTION_FLAGS "\n"
".globl __ctors_begin__\n"
"__ctors_begin__:\n"
".previous\n"
);
asm /* ld ".[cd]tors" sections bug workaround */
(
".section .ctors0" __SECTION_FLAGS "\n"
".globl __ctors0_begin__\n"
"__ctors0_begin__:\n"
".previous\n"
);
Similarly we are getting __ctors_end__ , __ctors0_end__ and destructors location is also obtained this way. After some ld bug workarounds all functions pointed by pointers from __ctors_begin__ to __ctors_end__ are executed. I don't know assembler and this code is impossible for me to interpret.
BTW: I know that invoking C++ contructors/destructors from C is not a task to be considered safe or easy.
| This isn't actually code executed by the CPU but it's added to the metadata of the object files. It tells the linker to create some global variables (__ctors_begin__ in the example above) in the same section (= part) of the final executable where the constructors are stored (that section is called .ctors). To make it work, you just have to make sure that the file with the "begin" variable is linked first and the file with the "end" variable is linked last (but maybe you can also control this with the __SECTION_FLAGS). That gives you the memory range you're looking for.
As for "safe": Well, the C++ runtime isn't magic. Somehow it has to know how to run all the constructors and destructors at startup and that doesn't change all the time. So for a major version number of your compiler, this should be pretty safe. Also, you'll know pretty soon when it breaks :-)
|
2,643,473 | 2,643,599 | Does std::multiset guarantee insertion order? | I have a std::multiset which stores elements of class A. I have provided my own implementation of operator< for this class. My question is if I insert two equivalent objects into this multiset is their order guaranteed? For example, first I insert a object a1 into the set and then I insert an equivalent object a2 into this set. Can I expect the a1 to come before a2 when I iterate through the set? If no, is there any way to achieve this using multiset?
| In C++03 you are not guaranteed that insert and erase preserve relative ordering. However, this is changed in C++0x:
n3092, §23.2.4/4: An associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. The set and map classes support unique keys; the multiset and multimap classes support equivalent keys. For multiset and multimap, insert and erase preserve the relative ordering of equivalent elements. Emphasis mine.
This is discussed in this defect report. This page is the collection of comments on the issue, it's well-written and quite fleshed-out. (I very much recommend reading this one over the previous "overview" link.)
From that comment page you'll find a comparison of current implementations, so you can check if the implementations you intend to use follow what you expect.
I can't think of a way to force the ordering you want off the top of my head. :/
|
2,643,837 | 2,661,920 | What strategies are efficient to handle concurrent reads on heterogeneous multi-core architectures? | I am tackling the challenge of using both the capabilities of a 8 core machine and a high-end GPU (Tesla 10).
I have one big input file, one thread for each core, and one for the the GPU handling.
The Gpu thread, to be efficient, needs a big number of lines from the input, while
the Cpu thread needs only one line to proceed (storing multiple lines in a temp buffer was slower). The file doesn't need to be read sequentially. I am using boost.
My strategy is to have a mutex on the input stream and each thread locks - unlocks it.
This is not optimal because the gpu thread should have a higher precedence when locking the mutex, being the fastest and the most demanding one.
I can come up with different solutions but before rush into implementation I would like to have some guidelines.
What approach do you use / recommend ?
| You may not need to lock at all if "1 line per thread" is not a strict requirement and you can go up to 2 lines or three lines sometimes. Then you can split the file equally, based on a formula. Suppose you want to read the file in 1024 kbyte blocks in total (this could be gigabytes too): You split it up to the cores with prioritization. So:
#define BLOCK_SIZE (1024 * 1024)
#define REGULAR_THREAD_BLOCK_SIZE (BLOCK_SIZE/(2 * NUM_CORES)) // 64kb
#define GPU_THREAD_BLOCK_SIZE (BLOCK_SIZE/2)
Each core gets 64 KB chunk
Core 1: offset 0 , size = REGULAR_THREAD_BLOCK_SIZE
Core 2: offset 65536 , size = REGULAR_THREAD_BLOCK_SIZE
Core 3: offset 131072 , size = REGULAR_THREAD_BLOCK_SIZE
Core n: offset (n * REGULAR_THREAD_BLOCK_SIZE), size = REGULAR_THREAD_BLOCK_SIZE
GPU gets 512 KB, offset = (NUM_CORES * REGULAR_THREAD_BLOCK_SIZE), size = GPU_THREAD_BLOCK_SIZE
So ideally they don't overlap. There are cases where they can overlap though. Since you're reading a text file a line might fall into the next core's block. To avoid overlapping you always skip first line for other cores, and always complete the last line assuming the next thread would skip it anyway, here is pseudo code:
void threadProcess(buf, startOFfset, blockSize)
{
int offset = startOffset;
int endOffset = startOffset + blockSize;
if(coreNum > 0) {
// skip to the next line
while(buf[offset] != '\n' && offset < endOffset) offset++;
}
if(offset >= endOffset) return; // nothing left to process
// read number of lines provided in buffer
char *currentLine = allocLineBuffer(); // opening door to security exploits :)
int strPos = 0;
while(offset < endOffset) {
if(buf[offset] == '\n') {
currentLine[strPos] = 0;
processLine(currentLine); // do line processing here
strPos = 0; // fresh start
offset++;
continue;
}
currentLine[strPos] = buf[offset];
offset++;
strPos++;
}
// read the remaineder past the buf
strPos = 0;
while(buf[offset] != '\n') {
currentLine[strPos++] = buf[offset++];
}
currentLine[strPos] = 0;
processLine(currentLine); // process the carryover line
}
As you can see this parallelizes the processing of the read block not the reads themselves. How do you parallelize reads? The best most awesome way would be memory mapping the whole block into memory. That would gain the best I/O performance as it's the lowest level.
|
2,643,863 | 2,643,954 | Embed a Python persistance layer into a C++ application - good idea? | say I'm about to write an application with a thin GUI layer, a really fat calculation layer (doing computationally heavy calibrations and other long-running stuff) and fairly simple persistance layer. I'm looking at building the GUI + calculation layer in C++ (using Qt for the gui parts).
Now - would it be a crazy idea to build the persistance layer in Python, using sqlalchemy, and embed it into the C++ application, letting the layers interface with eachother through lightweigth data transfer objects (written in C++ but accessible from python)?
(the other alternative I'm leaning towards would probably be to write the app in Python from the start, using the PyQt wrapper, and then calling into C++ for the computational tasks)
Thanks,
Rickard
| I would go with the 'alternative' approach:
Write as much as possible in Python (you can use the GUI bindings PyQt or PySide) and then only write the computationally intensive parts (when proven critical for performance) in C++ (have a look at Boost.Python).
Developing in Python should be faster, easier and less error-prone then in C++ (unless you're a very experienced C++ developer; and then still). Exposing C++ via Boost.Python should be easier then the other way around.
|
2,643,876 | 2,644,086 | Writing controls like a button in C++\Win32 (not MFC or CLI)? | I have several questions concerning the controls like a button, if You could answer i would be very much pleased.
Questions:
Is there any way to create a control like a button, but not-standard, i mean, not that strict-rectangled button
How do I handle mouse hover events within the control
Regards,
Galymzhan Sh
| It's relatively easy. If you want the same behaviour as a button (click, hover etc etc), then the best bet is to subclass the button control.
Have a read of the following MSDN articles:
http://msdn.microsoft.com/en-us/library/bb773183.aspx
http://msdn.microsoft.com/en-us/library/ms997565.aspx
http://msdn.microsoft.com/en-us/library/ms633569.aspx
|
2,643,963 | 6,124,717 | Can I use Win32 FreeType without the .dll file? | I'm teaching myself OpenGL and I'm implementing ttf text rendering using FreeType 2. I downloaded the library from
http://gnuwin32.sourceforge.net/packages/freetype.htm
and after a couple of minor issues I got it running properly. The thing that's bothering me is that I have to place a copy of freetype6.dll in the directory with my executable in order for the thing to run. I generally try to avoid a bunch of unnecessary dll files floating around. I'm sort of new to windows programming, but from what I understand most libraries can be built to run fully from a lib rather than requiring a dll at runtime. Looking through the documentation from FT is making my brain melt, so I thought I would ask here to see if there were any devs that have worked with FT before and if so, do they know how to build the library such that no dll is required at runtime.
Thank you in advance for any advice or support.
| Check out this link. See the section Optional: Installing FreeType (by compiling it yourself)
Follow the instructions and you'll be good to go.
|
2,644,979 | 2,644,988 | OpenCL or CUDA Which way to go? | I'm investigating ways of using GPU in order to process streaming data. I had two choices but couldn't decide which way to go?
My criterias are as follows:
Ease of use (good API)
Community and Documentation
Performance
Future
I'll code in C and C++ under linux.
| OpenCL
interfaced from your production code
portable between different graphics hardware
limited operations but preprepared shortcuts
CUDA
separate language (CUDA C)
nVidia hardware only
almost full control over the code (coding in a C-like language)
lot of profiling and debugging tools
Bottom line -- OpenCL is portable, CUDA is nVidia only. However, being an independent language, CUDA is much more powerful and has a bunch of really good tools.
Ease of use -- OpenCL is easier to use out of the box, but once you setup the CUDA coding environment it's almost like coding in C.
Community and Documentation -- both have extensive documentation and examples, however I think CUDA has better.
Performance -- CUDA allows for greater control, hence can be better fine-tuned for higher performance.
Future -- hard to say really.
|
2,645,347 | 2,645,360 | Number of digits for N**K | For given integers N and K (1 <= N, K <= 2000000000) you have to find the number of digits of N^K.
Is there any formula or something ? Because I tried solving it by simply powering N**K but it's not working for large values and the program simply freezes because of the calculations. I am looking for some fast way maybe some math formula like I said before.
| The 10 base log of N should give you the number of digits in it. This must be enough as a hint :-)
|
2,645,383 | 2,645,406 | Problem with Initializing Consts | This code, when compiled in xlC 8.0 (on AIX 5.3), produces the wrong result.
It should print 12345, but instead prints 804399880.
Removing the const in front of result makes the code work correctly.
Where is the bug?
#include <stdio.h>
#include <stdlib.h>
#include <string>
long int foo(std::string input)
{
return strtol(input.c_str(), NULL, 0);
}
void bar()
{
const long int result = foo("12345");
printf("%u\n", result);
}
int
main()
{
bar();
return 0;
}
Compilation command:
/usr/vacpp/bin/xlC example.cpp -g
Edit: Changing the printf format string above to "%ld\n" doesn't help.
Edit 2: The AIX version used was 5.3, not 6.1.
| xlC 10.0 works fine, seems to be a compiler bug
|
2,645,394 | 2,753,663 | Cannot enter input with gdb. Help! | I've been having a tough time entering input with gdb using XCode or Eclipse. Every time the debugger hits std::cin, it looks like its waiting for input, but fails to accept it. I've scoured the internet for more information, but am having trouble finding anything.
What do I need to do to get cin to work with gdb? For reference, I'm using XCode 3.2.2 and Eclipse Galileo.
Thanks!
-Carlos Nunez
| I guess there is a bug in GCC related to the usage of std::cin and setting/unsetting breakpoints. I did a minimal example:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string option = "x";
while (option != "q")
{
cout << endl
<< "0 = Stop" << endl
<< "1 = Play" << endl
<< "q = Quit" << endl;
getline(cin, option);
cout << "You choosed " << option << endl;
}
}
This code works perfectly until you set or activate a breakpoint (at least using the XCode wrapper). From then on stdin buffer is broken and every getline() retrieves the last input even though you don't type a key, entering a endless loop.
I don't know how to work arround it... :-(
|
2,645,758 | 2,645,795 | Problem with passing vector of pointers to objects to member function of another object | I have a vector of pointers to Mouse objects called 'mice'.
I'm passing the mice to the cat by reference.
vector <Mouse*> mice;
Cat * c;
c->lookForMouse(&mice);
And here's my lookForMouse() member function
void Cat::lookForMouse(vector <Mouse*> *mice)
{
...
}
And now to the problem! Within the function above, I can't seem to access my mice. This below will not work
mice[i]->isActive();
The error message I receive suggests to use mice[i].isActive(), but this throws an error saying isActive() is not a member of std::vector<_Ty> ...
This works though...
vector <Mouse*> miceCopy = *mice;
miceCopy[i]->isActive();
I understand that I shouldn't be creating another vector of mice here, it defeats the whole point of passing it by reference (let me know if I'm wrong)...
Why can't I do mice[i]->isActive() What should I be doing?
Thanks for your time and help :D
James.
| The problem is that you are not passing a reference, but a pointer.
A reference would be passed like an object:
c->lookForMouse(mice);
and the function taking it would look like this:
void Cat::lookForMouse(vector <Mouse*> &mice)
Note that containers of dumb pointers are prone to leaking. For example:
void f()
{
std::vector<Mouse*> mice = g();
h(); // throws!
cleanup(mice); // deletes objects in vector, is never called if h() throws
}
|
2,646,094 | 2,646,276 | Is there a way to serialize automatically enums as int? | Is there a way to serialize enums automatically as int? Every time I define a new enum and write
std::stringstream stream;
stream << myenum1;
stream >> myenum2;
the compiler complains that the operators << and >> are not defined. Do you know a way to tell the compiler to treat enums as plain int's?
What makes the problem harder is that, actually, the serialization is inside a template. Something like this:
template <typename T>
void serialize(const T& value)
{
std::stringstream stream;
stream << value;
}
So I cannot add any casts :(
Maybe I can specialize it somehow?
Thank you.
| You can find out if the type is enum with boost's TypeTraits (is_enum).
Then you can combine this with enable_if / disable_if:
template <class T>
typename boost::disable_if<boost::is_enum<T> >::type serialize(const T&);
template <class T>
typename boost::enable_if<boost::is_enum<T> >::type serialize(const T&); //use casts here
However, it will not be possible to check if a given value is valid for a given enum (unless you write a specific overload for the given enum type).
|
2,646,121 | 2,646,182 | Quaternion Cameras and projectile vectors | In our software we have a camera based on mouse movement, and a quarternion at its heart.
We want to fire projectiles from this position, which we can do, however we want to use the camera to aim. The projectile takes a vector which it will add to its position each game frame.
How do we acquire such a vector from a given camera/quaternion?
| The quaternion doesn't represent a direction, it represents a rotation. You can define a vector that points in the direction that your camera is pointing initially (e.g. (0,0,1)) and transform it using the rotation represented by the quaternion.
|
2,646,234 | 2,646,269 | How to share a static variable between C++ source files? | I don't know if it is possible to do this, but I have tried several ways and nothing seems to work. Basically I need to access the same static member from several files which include the same class definition.
// Filename: S.h
class S {
public:
static int foo;
static void change(int new_foo) {
foo = new_foo;
}
};
int S::foo = 0;
Then in a class definition (other .cpp file) I have:
// Filename: A.h
#include "S.h"
class A {
public:
void do_something() {
S::change(1);
}
};
And in another file:
// Filename: program.cpp
#include "S.h"
#include "A.h"
int main (int argc, char * const argv[]) {
A a = new A();
S::change(2);
std::cout << S::foo << std::endl;
a->do_something();
std::cout << S::foo << std::endl;
}
Now, I would expect the second function call to change the S::foo to 1, but the output is still:
2
Is the A.h file creating a local copy of the static class?
Thank you
Tommaso
| This line:
int S::foo = 0;
needs to be in exactly one source file, not in the header. So move it from S.h to S.cpp.
|
2,646,304 | 2,670,516 | Is there an API to map 'touch' input to a different monitors? | I am trying to achieve the same functionality as multidigimon.exe, that is mapping an input digitizer to a given monitor, I was wondering if there is an API I can access or if the multidigimon.exe supports any parameters I can call it with to automate the mapping process.
So far I have found that multidigimon.exe writes the following registry key
key:20-\\?\hid#&col06#1&4784345&d&0005#{4d1e55b2-f16f-11cf-88cb-001111000030}
value:\\?\DISPLAY#Default_Monitor#5&5e64b29&0&UID268435456#{e6f07b5f-ee97-4a90-b076-33f57bf4eaa7}
to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Wisp\Pen\Digimon
| I did not find an API; however, I think I know how to do it:
Find the monitor that you want to map the input to via EnumDisplayDevices, we are interestded in the DeviceID,
Find the correct instance of the input device
Write to the following registry key:
HKLM\SOFTWARE\Microsoft\Wisp\Pen\Digimon
key = [you input device path instances]
value = [your monitor device path]
Restart wisptis.exe.
|
2,646,704 | 2,647,765 | Using Doxygen Correctly | I have been trying to document my C++ project using Doxygen, with little success: Doxygen to fails recognize certain macros, and consequently entire functions are misinterpreted and most of time does not generate docs even though they have special comment blocks. Case in point:
/**
* \def __MYLIB_FUNCTION_ATTRIBUTE(...)
* \brief Some brief comment
* \details Detailed doc
* \sa Some valid references
*/
#define __MYLIB_FUNCTION_ATTRIBUTE(...) __attribute__(__VA_ARGS__)
/**
* \def IN
* \brief Tag for input arguments to a function
* \details Blah...
* \sa OUT
*/
#define IN
/**
* \def OUT
* \brief Tag for output arguments to a function
* \details Blah...
* \sa IN
*/
#define OUT
class MyClass {
public:
/**
* \fn MyClass()
* \brief Constructor for MyClass
* \details Hi!
*/
__MYLIB_FUNCTION_ATTRIBUTE(__always_inline__)
MyClass() {
}
/**
* \fn const char *doNothing(const char *s IN)
* \brief A weird function
* \details Some very weird doc
* \param[in] s No good parameter
*/
const char* __SXC_FUNCTION_ATTRIBUTE(__const__) doNothing(const char *s IN) {
return s;
}
};
Documentation generated for the above class is always missing a description for doNothing and IN is interpreted as a function! Am I doing something wrong here?
| Two things:
1) The Doxygen parser does not "see" the "IN" in doNothing (since it is removed in the preprocessing phase), so the \fn should not include it: const char* doNothing(const char* s). BTW, this \fn is not necessary: Doxygen automatically associates the comment if it is immediately before the documented entity.
2) I don't know what __SXC_FUNCTION_ATTRIBUTE expands into but, if it is something similar to __MYLIB_FUNCTION_ATTRIBUTE, it probably confuses Doxygen. As a workaround, you could either define these macros to nothing in the PREDEFINED section of Doxygen's config file, or conditionally define them in the sources, like this:
#ifdef DOXYGEN
// Doxygen does not grok the normal definition of this
#define __MYLIB_FUNCTION_ATTRIBUTE(...)
#else
#define __MYLIB_FUNCTION_ATTRIBUTE(...) __attribute__(__VA_ARGS__)
#endif
and put PREDEFINED = DOXYGEN in your config file.
|
2,646,721 | 2,646,812 | Array not returned correctly | I am trying to return a simple array, but I am not getting the correct result.
I am getting the following
arr1[0] = 1
arr1[1] = 32767
result while the result should have been
arr1[0] = 1
arr1[1] = 15
Please suggest.
int *sum(int a, int b){
int arr[2];
int *a1;
int result = a+b;
arr[0]= 1;
arr[1]= result;
a1 = arr;
return a1;
}
int main(){
int *arr1 = sum(5,10);
cout<<"arr1[0] = "<<arr1[0]<<endl;
cout<<"arr1[1] = "<<arr1[1]<<endl;
return 0;
}
| Try this...
#include <vector>
#include <iostream>
std::vector<int> sum(int a, int b)
{
std::vector<int> rv(2);
rv[0]= 1;
rv[1]= a+b;
return rv;
}
int main()
{
std::vector<int> arr1 = sum(5,10);
std::cout << "arr1[0] = " << arr1[0] << std::endl;
std::cout << "arr1[1] = " << arr1[1] << std::endl;
return 0;
}
|
2,647,052 | 2,648,150 | timing of reads from serial port on windows | I'm trying to implement a protocol over serial port on a windows(xp) machine.
The problem is that message synchronization in the protocol is done via a gap in the messages, i.e., x millisecond gap between sent bytes signifies a new message.
Now, I don't know if it is even possible to accurately detect this gap.
I'm using win32/serport.h api to read in one of the many threads of our server. Data from the serial port gets buffered, so if there is enough (and there will be enough) latency in our software, I will get multiple messages from the port buffer in one sequence of reads.
Is there a way of reading from the serial port, so that I would detect gaps in when particular bytes were received?
| I've had to do something similar in the past. Although the protocol in question did not use any delimiter bytes, it did have a crc and a few fixed value bytes at certain positions so I could speculatively decode the message to determine if it was a complete individual message.
It always amazes me when I encounter these protocols that have no context information in them.
Look for crc fields, length fields, type fields with a corresponding indication of the expected message length or any other fixed offset fields with predictable values that could help you determine when you have a single complete message.
Another approach might be to use the CreateFile, ReadFile and WriteFile API functions. There are settings you can change using the SetCommTimeouts function that allows you to halt the i/o operation when a certain time gap is encountered.
Doing that along with some speculative decoding could be your best bet.
|
2,647,320 | 2,648,520 | struct bitfield max size (C99, C++) | What is maximal bit width for bit struct field?
struct i { long long i:127;}
Can I define a bit field inside struct, with size of bitfield up to 128 bit, or 256 bit, or larger? There are some extra-wide vector types, like sse2 (128-bit), avx1/avx2 (256-bit), avx-512 (512-bit for next Xeon Phis) registers; and also extensions like __int128 in gcc.
| C99 §6.7.2.1, paragraph 3:
The expression that specifies the
width of a bit-field shall be an
integer constant expression that has
nonnegative value that shall not
exceed the number of bits in an object
of the type that is specified if the
colon and expression are omitted. If
the value is zero, the declaration
shall have no declarator.
C++0xa §9.6, paragraph 1:
... The constant-expression shall be an
integral constant expression with a
value greater than or equal to zero.
The value of the integral constant
expression may be larger than the
number of bits in the object
representation (3.9) of the
bit-field’s type; in such cases the
extra bits are used as padding bits
and do not participate in the value
representation (3.9) of the bit-field.
So in C you can't do that at all, and in C++ it won't do what you want it to.
|
2,647,362 | 24,620,652 | Is the c-dev@axis.apache.org mailing list, um, dead? | c-dev@axis.apache.org
I've successfully subscribed to it, but nobody seems to be answering any questions there.
| Technically, no. However, according to the archives, there has been a severe drop off that started around this time (April 2010) and it only broke 100 messages once since then (Dec 2012). So in practical terms, kinda, yeah.
Archive stats can be seen here:
http://mail-archives.apache.org/mod_mbox/axis-c-dev/
|
2,647,376 | 2,647,427 | Correct flip/mirror of pixels of an image? | http://tinypic.com/r/fwubzc/5
That shows what a flip should be and what a mirror should be.
Code for both types of mirrors:
void mirrorLeftRight()
{
for (int x = 0; x < width/2; x++) {
for (int y = 0; y < height; y++) {
int temp = pixelData[x][y];
pixelData[x][y]=pixelData[width-x][y]
pixelData[width-x][y]=temp;
}
}
}
void mirrorUpDown()
{
for (int x = 0; x < width; x++) {
for (int y = 0; y < height/2; y++) {
int temp = pixelData[x][y];
pixelData[x][y]=pixelData[x][height-y]
pixelData[x][height-y]=temp;
}
}
}
Does this seem right for mirrors?
And for flip, just a matter of using width and height w/o dividing by 2?
| The code above seems more like the correct way to Flip, not mirror.
Mirror I would guess that you not switch the pixels, but rather copy from one side to the other.
With mirror I would guess that you need to change
int temp = pixelData[x][y];
pixelData[x][y]=pixelData[width-x][y]
pixelData[width-x][y]=temp;
to something like this only
pixelData[x][y]=pixelData[width-x][y]
|
2,647,429 | 2,647,446 | C++ [Windows] Path to the folder where the executable is located | I need to access some files with fstream in my C++ app on Windows. Those files are all located in subfolders of the folder where my exe file is located.
What is the easiest and more important: safest way to get the path to the folder of the current executable?
| Use GetModuleFileName to find out where your exe is running from.
WCHAR path[MAX_PATH];
GetModuleFileNameW(NULL, path, MAX_PATH);
Then strip the exe name from path.
|
2,647,455 | 2,647,710 | C/C++ library for seekable movie format | I'm doing some processing on some very large video files (often up to 16MP), and I need a way to store these videos in a format that allows seeking to specific frames (rather than to times, like ffmpeg). I was planning on just rolling my own format that concatenates all of the individually zlib compressed frames together, and then appends an index on the end that links frame numbers to file byte indices. Before I go about this though, I just wanted to check to make sure I'm not duplicating the functionality of another format/library. Has anyone heard of a format/library that allows lossless compression and random access of videos?
| The reason it is hard to seek to a specific frame in most video codecs is that most frames depend on another frame or frames, so frames must be decoded as a group. For this reason, most libraries will only let you seek to the closest I-frame (Intra-frame - independently decodable frame). To actually produce an image from a non-I-frame, data from other frames is required, so you have to decode a number of frames worth of data.
The only ways I have seen this problem solved involve creating an index of some kind on the file. In other words, make a pass through the file and create an index of what frame corresponds to a certain time or section of the file. Since the seeking functions of most libraries are only able to seek to an I frame so you may have to seek to the closest I-frame and then decode from there to the exact frame you want.
If space is not of high importance, I would suggest doing it like you say, but use JPEG compression instead of zlib as it will give you a lot higher compression ratio since it exploits the fact you are dealing with image data.
If space is an issue, P frames (depend on previous frame/frames) can greatly reduce the size of the file. I would not mess with B frames (depend on previous and future frame/frames) since they make it much harder to get things right.
I have solved the problem of seeking to a specific frame in the presence of B and P frames in the past using ffmpeg (libavformat) to demux the video into packets (1 frame's worth of data per packet) and concatenate these into a single file. The important thing is to keep and index into that file so you can find packet bounds for a given frame. If the frame is an I-frame, you can just feed that frame's data into an ffmpeg decoder and it can be decoded. If the frame is a B or P frame, you have to go back to the last I-frame and decode forward from there. This can be quite tricky to get right, especially for B-frames since they are often sent in a different order than how they are displayed.
|
2,647,660 | 2,647,682 | Creation of an object in C++ | Isn't
A a = new A(); // A is a class name
supposed to work in C++?
I am getting:
conversion from 'A*' to non-scalar
type 'A' requested
Whats wrong with that line of code?
This works in Java, right?
Also, what is the correct way to create a new object of type A in C++, then?
| No, it isn't. The new operation returns a pointer to the newly created object, so you need:
A * a = new A();
You will also need to manage the deletion of the object somewhere else in your code:
delete a;
However, unlike Java, there is normally no need to create objects dynamically in C++, and whenever possible you should avoid doing so. Instead of the above, you could simply say:
A a;
and the compiler will manage the object lifetime for you.
This is extremely basic stuff. Which C++ text book are you using which doesn't cover it?
|
2,647,796 | 2,647,825 | Syntax for const accessor by reference | Right now my implementation returns the thing by value. The member m_MyObj itself is not const - its value changes depending on what the user selects with a Combo Box. I am no C++ guru, but I want to do this right. If I simply stick a & in front of GetChosenSourceSystem in both decl. and impl., I get one sort of compiler error. If I do one but not another - another error. If I do return &m_MyObj;. I will not list the errors here for now, unless there is a strong demand for it. I assume that an experienced C++ coder can tell what is going on here. I could omit constness or reference, but I want to make it tight and learn in the process as well.
// In header file
MyObj GetChosenThingy() const;
// In Implementation file.
MyObj MyDlg::GetChosenThingy() const
{
return m_MyObj;
}
| The returned object will have to be const, so you cant change it from outside;
// In header file
const MyObj& GetChosenThingy() const;
// In Implementation file.
const MyObj& MyDlg::GetChosenThingy() const
{
return m_MyObj;
}
|
2,647,853 | 2,657,514 | How do I forward `<Ctrl>-<Tab>` in Konsole? | I want to use intelligent tabbing in Emacs in C++ mode, but I also want to be able to insert a tab character when necessary. From other posts, I gather that the easiest way is to bind <Ctrl>-<Tab> to indent. However, it appears that Konsole in KUbuntu won't forward the <Ctrl>?
My current .emacs file contains:
(defun my-c-mode-common-hook ()
(setq c++-tab-always-indent t)
(setq tab-width 4)
(setq indent-tabs-mode t)
)
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
(global-set-key [C-tab] 'self-insert-command)
So I believe that this will bind <Ctrl>-<Tab> to inserting a tab character. However, when I run:
<Ctrl>-h k <Ctrl>-<Tab>
Emacs only reports that I pressed the tab key. Is there some option to Konsole (which I have searched through to no avail) or global preferences in KUbuntu that I need to set so that the <Ctrl>- is also forwarded? (It certainly forwards all of the other <Ctrl>-blah commands.)
| You can use Control-Q (quote, is what I think of in order to remember this), and then press your Tab key, and you'll insert a tab character. You can use Control-Q to insert any character sequence you need to. Hope this helps. :)
|
2,647,858 | 2,647,920 | Multiplying complex with constant in C++ | The following code fails to compile
#include <iostream>
#include <cmath>
#include <complex>
using namespace std;
int main(void)
{
const double b=3;
complex <double> i(0, 1), comp;
comp = b*i;
comp = 3*i;
return 0;
}
with
error: no match for ‘operator*’ in ‘3 * i’
What is wrong here, why cannot I multiply with immediate constants? b*i works.
| In the first line:
comp = b*i;
The compiler calls:
template<class T> complex<T> operator*(const T& val, const complex<T>& rhs);
Which is instanced as:
template<> complex<double> operator*(const double& val, const complex<double>& rhs);
In the second case, there is no appropriate template int, so the instancing fails:
comp = 3.0 * i; // no operator*(int, complex<double>)
|
2,647,988 | 2,648,003 | Question on breakpoints in VS2010 C++ | I'm using VS2010 Ultimate.
Having code:
//file IntSet.h
#include "stdafx.h"
#pragma once
/*Class representing set of integers*/
template<class T>
class IntSet
{
private:
T** myData_;
std::size_t mySize_;
std::size_t myIndex_;
public:
#pragma region ctor/dtor
explicit IntSet();
virtual ~IntSet();
#pragma endregion
#pragma region publicInterface
IntSet makeUnion(const IntSet&)const;
IntSet makeIntersection(const IntSet&)const;
IntSet makeSymmetricDifference(const IntSet&)const;
void insert(const T&);
#pragma endregion
};
//file IntSet_impl.h
#include "StdAfx.h"
#include "IntSet.h"
#pragma region ctor/dtor
template<class T>
IntSet<T>::IntSet():myData_(nullptr),
mySize_(0),
myIndex_(0)
{
}
template<class T>
IntSet<T>::~IntSet()
{
}
#pragma endregion
#pragma region publicInterface
template<class T>
void IntSet<T>::insert(const T& obj)
{//BREAKPOINT---------------------------<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/*IF I SET A BREAKPOINT HERE AND AFTER THAT I CHANGE SOMETHING IN THE BODY
I'M GETTING MSG SAYING THAT THE BREAKPOINT WILL NOT CURRENTLY BE HIT, AFTER I REBUILD
THE BREAKPOINT IS VALID AGAIN*/
/*Check if we are initialized*/
if (mySize_ == 0)
{
mySize_ = 1;
myData_ = new T*[mySize_];
}
/*Check if we have place to insert obj in.*/
if (myIndex_ < mySize_)
{
myData_[myIndex_++] = new T(obj);
return;
}
/*We didn't have enough place...*/
T** tmp = new T*[mySize_];//for copying old to temporary basket
std::copy(&myData_[0],&myData_[mySize_],&tmp[0]);
delete myData_;
auto oldSize = mySize_;
mySize_ *= 2;
myData_ = new T*[mySize_];
std::copy(&tmp[0],&tmp[oldSize],&myData_[0]);
myData_[myIndex_] = new T(obj);
++myIndex_;
}
#pragma endregion
See linke marked as BREAKPOINT.
Thanks.
| If you change the code while the program is running, the code no longer matches what was compiled, so the debugger is (usually) unable to manage breakpoints until the program is stopped and rebuilt with the new source.
Under some circumstances, Visual Studio supports edit-and-continue debugging where you can edit a file while the debugger is stopped at a breakpoint, then when you resume it will recompile that code and resume with the modified code.
|
2,647,999 | 2,654,638 | How to change the toolbar button's Bitmap in win32? | I have created a toolbar with some controls on it using ReBar within a window. Can anyone please tell me,
How to get the HWND of a buttons/combobox/etc (not normal buttons in a window) if I know (only) the Id of it ?
How to obtain the HBITMAP if I know the id of the resource ?
How to set the bitmap to the controller ?
SendDlgItemMessageW(hWnd, nId, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);
This isn't working for toolbars, isn't it ? I couldn't find a way to do it, please help me. Thank you...
Regards
EDIT:
Anyone please ? :(
EDIT:
Ok. it seems everyone is busy these days. :( Btw, is it a wrong question ?
| You could download ControlSpy and try it in there to get a feel for it.
I checked the Rebar and saw that RB_SETBANDINFO (under Messages) could be what you are looking for.
|
2,648,086 | 2,648,111 | Out of Core Implementation of a Quadtree | I am trying to build a Quadtree data structure(or let's just say a tree) on the secondary memory(Hard Disk).
I have a C++ program to do so and I use fopen to create the files. Also, I am using tesseral coding to store each cell in a file named with its corresponding code to store it on the disk in one directory.
The problem is that after creating about 1,100 files, fopen just returns NULL and stops creating new files. I can create further files manually in that directory, but using C++ it can not create any further files.
I know about max limit of inode on ext3 filesystem which is (from Wikipedia) 32,000 but mine is way less than that, also note that I can create files manually on the disk; just not through fopen.
Also, I really appreciate any idea regarding the best way to store a very dynamic quadtree on disk(I need the nodes to be in separate files and the quadtree might have a depth of 50).
Using nested directories is one idea, but I think it will slow down the performance because of following the links on the filesystem to access the file.
Thanks,
Nima
| Whats the errno value of the failed fopen() call?
Do you keep the files you have created open? If yes you are most probably exceeding the maximum number of open files per process.
|
2,648,112 | 2,648,142 | include and using namespace in C++ | for using cout, I need to specify both:
#include<iostream>
and
using namespace std;
Where is cout defined? in iostream, correct? So, it is that iostream itself is there in namespace std?
What is the meaning of both the statements with respect to using cout?
I am confused why we need to include them both.
| iostream is the name of the file where cout is defined.
On the other hand, std is a namespace, equivalent (in some sense) to java's package.
cout is an instance defined in the iostream file, inside the std namespace.
There could exist another cout instance, in another namespace. So to indicate that you want to use the cout instance from the std namespace, you should write
std::cout, indicating the scope.
std::cout<<"Hello world"<<std::endl;
To avoid the std:: everywhere, you can use the using clause.
cout<<"Hello world"<<endl;
They are two different things. One indicates scope, the other does the actual inclusion of cout.
In response to your comment
Imagine that in iostream two instances named cout exist, in different namespaces
namespace std{
ostream cout;
}
namespace other{
float cout;//instance of another type.
}
After including <iostream>, you'd still need to specify the namespace. The #include statement doesnt say "Hey, use the cout in std::". Thats what using is for, to specify the scope
|
2,648,163 | 2,653,046 | Accessing a database using visual c++ and OLEDB | Does anybody have an example of working with database using Visual C++ and OLEDB? What should I include on top of my code?
I have searched the internet and most examples are using C# or VB. Examples written by C++ are usually not complete.
I really appreciate your help.
Best,
Shadi.
| You probably want to use ADO to do this. Writing code directly to OLE DB from C/C++ is a fair bit of work (understatement). If you google for c++ ado, there are a number of hits. The top two are this one on codeguru and one on codersource. They both look like good examples.
|
2,648,176 | 2,648,548 | Boost MultiIndex - objects or pointers (and how to use them?)? | I'm programming an agent-based simulation and have decided that Boost's MultiIndex is probably the most efficient container for my agents. I'm not a professional programmer, and my background is very spotty. I've two questions:
Is it better to have the container contain the agents (of class Host) themselves, or is it more efficient for the container to hold Host *? Hosts will sometimes be deleted from memory (that's my plan, anyway... need to read up on new and delete). Hosts' private variables will get updated occasionally, which I hope to do through the modify function in MultiIndex. There will be no other copies of Hosts in the simulation, i.e., they will not be used in any other containers.
If I use pointers to Hosts, how do I set up the key extraction properly? My code below doesn't compile.
// main.cpp - ATTEMPTED POINTER VERSION
...
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/tokenizer.hpp>
typedef multi_index_container<
Host *,
indexed_by<
// hash by Host::id
hashed_unique< BOOST_MULTI_INDEX_MEM_FUN(Host,int,Host::getID) > // arg errors here
> // end indexed_by
> HostContainer;
...
int main() {
...
HostContainer testHosts;
Host * newHostPtr;
newHostPtr = new Host( t, DOB, idCtr, 0, currentEvents );
testHosts.insert( newHostPtr );
...
}
I can't find a precisely analogous example in the Boost documentation, and my knowledge of C++ syntax is still very weak. The code does appear to work when I replace all the pointer references with the class objects themselves.
As best I can read it, the Boost documentation (see summary table at bottom) implies I should be able to use member functions with pointer elements.
| If Host contains lot of data you could use shared_ptr to avoid copying. You could use MultiIndex with shared_ptr in it:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::multi_index;
struct Host
{
int get_id() const { return id; }
private:
int id;
// more members here
};
typedef multi_index_container<
boost::shared_ptr<Host>, // use pointer instead of real Host
indexed_by<
// hash using function Host::get_id
hashed_unique< const_mem_fun<Host, int, &Host::get_id> >
> // end indexed_by
> HostContainer;
Then you could use it as follows:
int main()
{
HostContainer testHosts;
Host * newHostPtr;
newHostPtr = new Host;
testHosts.insert( boost::shared_ptr<Host>(newHostPtr) );
return 0;
}
|
2,648,364 | 2,648,579 | How to print a number with a space as thousand separator? | I've got a simple class Currency with overloaded operator<<. I don't know how can i separate the number with spaces every 3 digits, so it looks like: "1 234 567 ISK".
#include <cstdlib>
#include <iostream>
using namespace std;
class Currency
{
int val;
char curr[4];
public:
Currency(int _val, const char * _curr)
{
val = _val;
strcpy(curr, _curr);
}
friend ostream & operator<< (ostream & out, const Currency & c);
};
ostream & operator<< (ostream & out, const Currency & c)
{
out << c.val<< " " << c.curr;
return out;
}
int main(int argc, char *argv[])
{
Currency c(2354123, "ISK");
cout << c;
}
What interests me, is somehow the easiest solution for this particular situation.
| This can be done with facets
struct myseps : numpunct<char> {
/* use space as separator */
char do_thousands_sep() const { return ' '; }
/* digits are grouped by 3 digits each */
string do_grouping() const { return "\3"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new myseps));
std::cout << 10000; // 10 000
}
Alternatively, you may code your own loop
void printGrouped(ostream &out, int n) {
if(n < 0) {
out << "-";
return printGrouped(out, -n);
}
if(n < 1000) {
out << n;
} else {
printGrouped(out, n / 1000);
out << " " << setw(3) << setfill('0') << (n % 1000);
}
}
ostream & operator<< (ostream & out, const Currency & c) {
printGrouped(out, c.val);
out << " " << c.curr;
return out;
}
|
2,648,367 | 2,650,001 | DLL dependant on curllib.dll - How can I fix this? | I'm new to developing in C++. I've developed a dll where I'm using curllib to make HTTP requests.
When running the dll via depend.exe it notifies me that my dll now depends on the curllib.dll. This simply doesn't work for me. My dll is set as a static library not shared and will be distributed on its own. I cannot rely on a user having libcurl.dll installed.
I thought by including libcurl into my project this is all that would be needed and my dll could be independent.
If this is impossible to resolve is there an alternative method I can use to create HTTP requests? Obviously I would prefer to use libcurl.
Thanks in advance.
| You can compile curl as a lib instead of a dll by opening the solution file in visual studio and changing the build project to "lib release". Thus you wont need the dll at all and you can just include the lib in the linker.
|
2,648,382 | 2,664,524 | How to determine if a C++ usertype has been registered with tolua | We use tolua++ to generate Lua bindings for C++ classes.
Assume I have a C++ class:
class Foo
{
//Some methods in Foo, irrelevant to question.
};
and a tolua .pkg file with the following contents
class Foo
{
};
Consider the following function:
void call_some_lua_function(lua_State* luaState)
{
Foo* myFoo = new Foo();
tolua_pushusertype(luaState, (void*)myFoo, "Foo");
//More code to actually call Lua, irrelevant to question.
}
Now, the actual question:
tolua_pushusertype causes a segfault in Lua if the 3rd parameter does not correspond to a valid fully qualified string of a C++ class that was registered with a call to tolua_cclass. So, if parameter 3 where "Bar", we get a segfault.
What I would like to do is the following:
void call_some_lua_function(lua_State* luaState)
{
//determine if tolua is aware of my type, how to do this?
//Something like:
//if(!tolua_iscpptype_registered("Foo"))
//{
// abort gracefully
//}
Foo* myFoo = new Foo();
tolua_pushusertype(luaState, (void*)myFoo, "Foo");
//More code to actually call Lua, irrelevant to question.
}
Is there a way to do this using tolua?
| I am using tolua, not tolua++, but let's hope it is somehow similar. In tolua, you can test if the class is registered with it like this:
tolua_getmetatable(L, "ClassName");
if (lua_isnil(L, -1)) {
// the class wasn't found
}
Hint: check how tolua.cast is implemented and checks its arguments. It takes a type name as string.
Edited: More curious, I downloaded the tolua++ sources and looked inside. It doesn't look completely similar, and the critical function is missing. I have to give you an untested suggestion that might work:
luaL_getmetatable(L, "ClassName");
if (lua_isnil(L, -1)) {
// the class wasn't found
}
The difference between tolua and tolua++ seems to b that tolua uses a "namespace" for its created metatables ("tolua." prefix).
|
2,648,396 | 2,649,565 | Methods for implementing and using graphs of nodes in C++? | I am working on a research project that deals with social networks. I have done most of the backbone of the program in C++ and am now wanting to implement a way to create the graph of nodes and the connections as well as a way to visualize the connections between people. I have looked a little into Lemon and the Boost graph library, but was wondering which one would be easier to learn and implement or if I should just code my own.
| If you use the BGL then you should also be able to make use of the Graph Toolkit for Algorithms and Drawings (GTAD). The GTAD is meant to be compatible with BGL and adds a number of graph algorithms not in BGL as well as algorithms for layouts.
For visualization the BGL allows you to read and write some common graph file types such as GraphML and Dot for use with GraphViz.
Lemon looks to be a well featured library with a good array of algorithms. You can also use gLemon to view Lemon graphs. This visualizer looks quite basic though and was last updated in 2008, unlike Lemon which is still under development.
I would suggest you first work out what you want to do with any graphs you create, ie what algorithms you require (shortest-path etc) and compare the two libraries from that respect.
Also take a look at the tutorials for both. They have very good documentation and should help you decide which you'll find easier to implement.
Unless you really want to get into the details of how certain graph structures and algorithms are implemented I would use a library.
|
2,648,559 | 2,655,029 | C++: Need to make an HTTP request from a dll - where do I start? | I've tried using curllib, but find my dll becomes dependent on curllib.dll. Is there another method I can investigate and use? I simply want to make a request to a web page. My dll has to be independant so it can be distributed on its own.
Thanks
| For anyone in a similar situation I managed to compile the libcurl visual studio project in the latest curl distribution with Runtime library set to Multi-threaded dll. I think I left everything else the same apart from the output files (debug/release respectfully). Once the lib compiled with my dll I noticed now my dll is only dependant on 3 other dlls.
IESHIMS.dll - which I fixed with an environment variable path update (program files(x86)/Internet Explorer
MSVCR90.DLL
GPSVC.DLL.
I fear now its a Win7 64 bit issue. At least I got my dll working with no libcurl dependency, right!?
|
2,648,562 | 2,648,868 | How to output floating point numbers with a custom output format in C++? | The problem is that I want to output Mathematica compatible floating point numbers. The only difference with the standard IOStream or printf output format is that the exponential e is replaced by *^:
Standard C/C++ output format: 1.23e-4
Mathematica format: 1.23*^-4
Is there a way to manipulate streams to achieve this effect? My original idea was just to use istringstream and dump it to a string and then replace all the e's. I would also be okay if someone posted code to parse through the bits of the floating point number and output it directly (i.e. a printf("%e") replacement).
| Your idea should work out easily:
std::string FloatToStringMathematica(float x) {
std::stringstream a;
a << x;
std::string u = a.str();
size_t pos = u.find("e");
if(pos != std::string::npos) {
u.replace(p, 1, "*^");
}
return u;
}
|
2,648,577 | 2,653,041 | What is the difference between Inversion of Control and Dependency injection in C++? | I've been reading recently about DI and IoC in C++. I am a little confused (even after reading related questions here on SO) and was hoping for some clarification.
It seems to me that being familiar with the STL and Boost leads to use of dependency injection quite a bit. For example, let's say I made a function that found the mean of a range of numbers:
template <typename Iter>
double mean(Iter first, Iter last)
{
double sum = 0;
size_t number = 0;
while (first != last)
{
sum += *(first++);
++number;
}
return sum/number;
};
Is this (i.e., using iterators instead of accessing the collection itself) dependency injection? Inversion of control? Neither?
Let's look at another example. We have a class:
class Dice
{
public:
typedef boost::mt19937 Engine;
Dice(int num_dice, Engine& rng) : n_(num_dice), eng_(rng) {}
int roll()
{
int sum = 0;
for (int i = 0; i < num_dice; ++i)
sum += boost::uniform_int<>(1,6)(eng_);
return sum;
}
private:
Engine& eng_;
int n_;
};
This seems like dependency injection. But is it inversion of control?
Also, if I'm missing something, can someone help me out? This seems to be the natural way to do things, so if that's all there is to Dependency Injection, why do people have a hard time using it?
| Inversion of Control is a very generic concept, with different meanings depending on the sort of "control" you're talking about. Dependency injection is a specific form.
Inversion of Control and iteration
In this case "control" means "flow control".
I think your first example involving iteration is not really inversion of control, because that code explicitly does the flow control. Inversion of control would separate the action to perform from the flow control. It might look like this (pardon my java/C#):
SumVisitor sumVisitor = new SumVisitor();
collection.AcceptVisitor(sumVisitor);
int sum = sumVisitor.GetSum();
The visitor object does something for each collection element it visits, e.g. update a sum counter field. But it has no control over how or when it is called by the collection, hence inversion of control. You could also implement a MedianVisitor, MeanVisitor, MaximumVisitor, etcetera. Each one implements a generic IVisitor interface with a Visit(Element) method.
For the collection, the opposite is true: it has no knowledge about what the visitor does and simply takes care of the flow control by calling visitor.Visit(element) for each element in the collection. Different visitor implementations all look the same for the collection.
Inversion of Control and object graph construction
In this case "control" means "control over how components are created and wired together".
In any non-trivial application, code is split into components which have to collaborate. To keep the components reusable, they cannot directly create each other as that would permanently glue them together. Instead, individual components give up control over construction and component wiring.
Dependency injection is one way to achieve this, by taking references to collaborator objects in the constructor. You then need a separate piece of start-up code where all the components are created and wired together, or a dependency injection framework that takes care of this for you. Your Dice class is indeed an example of dependency injection.
Another way to give up control over object graph construction is the Service Locator pattern, though it has its disadvantages.
|
2,648,756 | 2,648,865 | From Java Object class to C++ | I'm relative new to C++ and my background is in Java. I have to port some code from Java to C++ and some doubts came up relative to the Object Java's class. So, if I want to port this:
void setInputParameter(String name, Object object) { ..... }
I believe I should use void* type or templates right? I don't know what's the "standard" procedure to accomplish it.
Thanks
| It depends what you want to do with object.
If you use a template, then any methods you call on object will be bound at compile time to objects type. This is type safe, and preferable, as any invalid use of the object will be flagged as compiler errors.
You could also pass a void * and cast it to the desired type, assuming you have some way of knowing what it should be. This is more dangerous and more susceptible to bugs in your code. You can make it a little safer by using dynamic_cast<> to enable run-time type checking.
|
2,648,802 | 2,649,916 | At what point is it worth using a database? | I have a question relating to databases and at what point is worth diving into one. I am primarily an embedded engineer, but I am writing an application using Qt to interface with our controller.
We are at an odd point where we have enough data that it would be feasible to implement a database (around 700+ items and growing) to manage everything, but I am not sure it is worth the time right now to deal with. I have no problems implementing the GUI with files generated from excel and parsed in, but it gets tedious and hard to track even with VBA scripts. I have been playing around with converting our data into something more manageable for the application side with Microsoft Access and that seems to be working well. If that works out I am only a step (or several) away from using an SQL database and using the Qt library to access and modify it.
I don't have much experience managing data at this level and am curious what may be the best way to approach this. So what are some of the real benefits of using a database if any in this case? I realize much of this can be very application specific, but some general ideas and suggestions on how to straddle the embedded/application programming line would be helpful.
This is not about putting a database in an embedded project. It is also not a business type application where larger databases are commonly used. I am designing a GUI for a single user on a desktop to interface with a micro-controller for monitoring and configuration purposes.
I decided to go with SQLite. You can do some very interesting things with data that I didn't really consider an option when first starting this project.
| A database is worthwhile when:
Your application evolves to some
form of data driven execution.
You're spending time designing and
developing external data storage
structures.
Sharing data between applications or
organizations (including individual
people)
The data is no longer short and
simple.
Data Duplication
Evolution to Data Driven Execution
When the data is changing but the execution is not, this is a sign of a data driven program or parts of the program are data driven. A set of configuration options is a sign of a data driven function, but the whole application may not be data driven. In any case, a database can help manage the data. (The database library or application does not have to be huge like Oracle, but can be lean and mean like SQLite).
Design & Development of External Data Structures
Posting questions to Stack Overflow about serialization or converting trees and lists to use files is a good indication your program has graduated to using a database. Also, if you are spending any amount of time designing algorithms to store data in a file or designing the data in a file is a good time to research the usage of a database.
Sharing Data
Whether your application is sharing data with another application, another organization or another person, a database can assist. By using a database, data consistency is easier to achieve. One of the big issues in problem investigation is that teams are not using the same data. The customer may use one set of data; the validation team another and development using a different set of data. A database makes versioning the data easier and allows entities to use the same data.
Complex Data
Programs start out using small tables of hard coded data. This evolves into using dynamic data with maps, trees and lists. Sometimes the data expands from simple two columns to 8 or more. Database theory and databases can ease the complexity of organizing data. Let the database worry about managing the data and free up your application and your development time. After all, how the data is managed is not as important as to the quality of the data and it's accessibility.
Data Duplication
Often times, when data grows, there is an ever growing attraction for duplicate data. Databases and database theory can minimize the duplication of data. Databases can be configured to warn against duplications.
Moving to using a database has many factors to be considered. Some include but are not limited to: data complexity, data duplication (including parts of the data), project deadlines, development costs and licensing issues. If your program can run more efficiently with a database, then do so. A database may also save development time (and money). There are other tasks that you and your application can be performing than managing data. Leave data management up to the experts.
|
2,648,877 | 2,653,123 | JNI Stream binary data from C++ to Java | I need help passing binary data into Java. I'm trying to use jbytearray but when the data gets into Java it appears corrupt. Can somebody give me a hand?
Here's a snip of some example code. First the native C++ side:
printf("Building audio array copy\n");
jbyteArray rawAudioCopy = env->NewByteArray(10);
jbyte toCopy[10];
printf("Filling audio array copy\n");
char theBytes[10] = {0,1,2,3,4,5,6,7,8,9};
for (int i = 0; i < sizeof(theBytes); i++) {
toCopy[i] = theBytes[i];
}
env->SetByteArrayRegion(rawAudioCopy,0,10,toCopy);
printf("Finding object callback\n");
jmethodID aMethodId = env->GetMethodID(env->GetObjectClass(obj),"handleAudio","([B)V");
if(0==aMethodId) throw MyRuntimeException("Method not found error",99);
printf("Invoking the callback\n");
env->CallVoidMethod(obj,aMethodId, &rawAudioCopy);
and then the Java callback method:
public void handleAudio(byte[] audio){
System.out.println("Audio supplied to Java [" + audio.length + "] bytes");
byte[] expectedAudio = {0,1,2,3,4,5,6,7,8,9};
for (int i = 0; i < audio.length; i++) {
if(audio[i]!= expectedAudio[i])
System.err.println("Expected byte " + expectedAudio[i]
+ " at byte " + i + " but got byte " + audio[i]);
else System.out.print('.');
}
System.out.println("Audio passed back accordingly!");
}
I get the following output when the callback is invoked:
library loaded!
Audio supplied to Java [-2019659176] bytes
Audio passed back accordingly!
| After fixing my above mistake I'm now looking for the most efficient way of copying raw byte arrays back into Java. What I have above seems a little less than ideal since I'm planning on supporting a high number of repeat copies. I experimented with passing the char array directly to the setByteArrayRegion call which appears to work in this simple case but I'm wondering if I need to perform pinning. How is that done when you create new arrays on the native side? Do I just call getByteArrayRegion with a FALSE after the set? Can I un-pin after the call into Java completes? Are there online examples of high performance raw binary data shuttling back to java that I can learn from?
|
2,648,878 | 2,648,912 | Range-based for statement definition redundancy | Looking at n3092, in §6.5.4 we find the equivalency for a range-based for loop. It then goes on to say what __begin and __end are equal to. It differentiates between arrays and other types, and I find this redundant (aka confusing).
It says for arrays types that __begin and __end are what you expect: a pointer to the first and a pointer to one-past the end. Then for other types, __begin and __end are equal to begin(__range) and end(__range), with ADL. Namespace std is associated, in order to find the std::begin and std::end defined in <iterator>, §24.6.5.
However, if we look at the definition of std::begin and std::end, they are both defined for arrays as well as container types. And the array versions do exactly the same as above: pointer to the first, pointer to one-past the end.
Why is there a need to differentiate arrays from other types, when the definition given for other types would work just as well, finding std::begin and std::end?
Some abridged quotes for convenience:
§6.5.4 The range-based for statement
— if _RangeT is an array type, begin-expr and end-expr are __range and __range + __bound, respectively, where __bound is the array bound. If _RangeT is an array of unknown size or an array of incomplete type, the program is ill-formed.
— otherwise, begin-expr and end-expr are begin(__range) and end(__range), respectively, where begin and end are looked up with argument-dependent lookup (3.4.2). For the purposes of this name lookup, namespace std is an associated namespace.
§24.6.5 range access
template <class T, size_t N> T* begin(T (&array)[N]);
Returns: array.
template <class T, size_t N> T* end(T (&array)[N]);
Returns: array + N.
| This avoids a corner-case with ADL:
namespace other {
struct T {};
int begin(T*) { return 42; }
}
other::T a[3];
for (auto v : a) {}
Because ADL finds other::begin when calling begin(a), the equivalent code would break causing a confusing compile error (along the lines of "can't compare int to other::T*" as end(a) would return a T*) or different behavior (if other::end was defined and did something likewise unexpected).
|
2,649,056 | 3,781,180 | How to write a browser plugin? | I'm curious as to the procedure for writing browser plugins for browsers like Chrome, Safari, and Opera. I'm thinking specifically of Windows here and would prefer working with C++.
Are there any tools or tutorials that detail the process?
Note: I am not referring to extensions or 'addons'. I'm referring to a plugin similar to how Flash and Adobe Reader have plugins to handle specific content-types.
| As others point out, plugins for those browser are written using the NPAPI.
Note: Both Firefox and Chrome will default most plugins to click-to-play soon, with Chrome planning to phase out NPAPI entirely. NPAPI for new projects is discouraged at this point.
Resources for getting started with NPAPI:
MDC plugin section
three part NPAPI tutorial
memory management in NPAPI
npsimple - the "Hello World" of NPAPI plugins
npapi-sdk - the source for the canonical NPAPI headers
Mozillas test plugin - good for looking up specific NPAPI use cases
The NPAPI itself is however relatively low-level, but there are tools and frameworks that can help you with it:
FireBreath - cross-browser, cross-platform frame-work for plugins
Nixysa - generate glue-code for NPAPI plugins
JUCE - application framework also providing support for plugins
QtBrowserPlugin - Qt based browser plugin framework
|
2,649,068 | 2,649,576 | Has anyone found the need to declare the return parameter of a copy assignment operator const? | The copy assignment operator has the usual signature:
my_class & operator = (my_class const & rhs);
Does the following signature have any practical use?
my_class const & operator = (my_class const & rhs);
You can only define one or the other, but not both.
| The principle reason to make the return type of copy-assignment a non-const reference is that it is a requirement for "Assignable" in the standard.
If you make the return type a const reference then your class won't meet the requirements for use in any of the standard library containers.
|
2,649,122 | 2,649,362 | Problem in Building mplsh-run in lshkit | been trying out this for quite some time but
I'm still unable to built mplsh-run from lshkit
Not sure if this would help to explain my situation during the
building process
/tmp/cc17kth4.o: In function `lshkit::MultiProbeLshRecallTable::reset(lshkit::MultiProbeLshModel, unsigned int, double, double)':
mplsh-run.cpp:(.text._ZN6lshkit24MultiProbeLshRecallTable5resetENS_18MultiProbeLshModelEjdd[lshkit::MultiProbeLshRecallTable::reset(lshkit::MultiProbeLshModel, unsigned int, double, double)]+0x230): undefined reference to `lshkit::MultiProbeLshModel::recall(double) const'
/tmp/cc17kth4.o: In function `void lshkit::MultiProbeLshIndex<unsigned int>::query_recall<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, float, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&) const':
mplsh-run.cpp:(.text._ZNK6lshkit18MultiProbeLshIndexIjE12query_recallINS_11TopkScannerINS_6MatrixIfE8AccessorENS_6metric5l2sqrIfEEEEEEvPKffRT_[void lshkit::MultiProbeLshIndex<unsigned int>::query_recall<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, float, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&) const]+0x2c4): undefined reference to `lshkit::MultiProbeLsh::genProbeSequence(float const*, std::vector<unsigned int, std::allocator<unsigned int> >&, unsigned int) const'
/tmp/cc17kth4.o: In function `void lshkit::MultiProbeLshIndex<unsigned int>::query<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, unsigned int, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&)':
mplsh-run.cpp:(.text._ZN6lshkit18MultiProbeLshIndexIjE5queryINS_11TopkScannerINS_6MatrixIfE8AccessorENS_6metric5l2sqrIfEEEEEEvPKfjRT_[void lshkit::MultiProbeLshIndex<unsigned int>::query<lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> > >(float const*, unsigned int, lshkit::TopkScanner<lshkit::Matrix<float>::Accessor, lshkit::metric::l2sqr<float> >&)]+0x4a): undefined reference to `lshkit::MultiProbeLsh::genProbeSequence(float const*, std::vector<unsigned int, std::allocator<unsigned int> >&, unsigned int) const'
collect2: ld returned 1 exit status
the command that i used to built mplsh-run is
g++ -I./lshkit/include -L/usr/lib -lm -lgsl -lgslcblas -lboost_program_options-mt mplsh-run.cpp
Do you guys have any clue on how I could solve this?
| Put the .cpp file as the first argument.
g++ mplsh-run.cpp -I./lshkit/include -lm -lgsl -lgslcblas -lboost_program_options-mt
Also try with different permutations of -lm -lgsl and -lgslcblas
|
2,649,207 | 2,649,276 | Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)? | It seems that a lot of people include example.h instead of cexample in their C++ code. I know that everything in the C++ versions is declared in namespace std, but I'm not aware of any other differences. So why do people use the C headers, and is it okay to do so?
| The difference between the two is that the C headers that C++ imported (by prefixing with c and removing the .h suffix) are in namespace std. This so any call or use of a standard facility is prefixed with std::, for uniformity. It's The Standard Way Of Doing Things(tm). Unless of course you already have a bunch of C code in which you don't feel like appending std:: to each standard call: then use the classic C headers.
|
2,649,334 | 2,649,430 | Difference between static and shared libraries? | What is the difference between static and shared libraries?
I use Eclipse and there are several project types including Static Libraries and Shared Libraries? Does one have an advantage over the other?
| Shared libraries are .so (or in Windows .dll, or in OS X .dylib) files. All the code relating to the library is in this file, and it is referenced by programs using it at run-time. A program using a shared library only makes reference to the code that it uses in the shared library.
Static libraries are .a (or in Windows .lib) files. All the code relating to the library is in this file, and it is directly linked into the program at compile time. A program using a static library takes copies of the code that it uses from the static library and makes it part of the program. [Windows also has .lib files which are used to reference .dll files, but they act the same way as the first one].
There are advantages and disadvantages in each method:
Shared libraries reduce the amount of code that is duplicated in each program that makes use of the library, keeping the binaries small. It also allows you to replace the shared object with one that is functionally equivalent, but may have added performance benefits without needing to recompile the program that makes use of it. Shared libraries will, however have a small additional cost for the execution of the functions as well as a run-time loading cost as all the symbols in the library need to be connected to the things they use. Additionally, shared libraries can be loaded into an application at run-time, which is the general mechanism for implementing binary plug-in systems.
Static libraries increase the overall size of the binary, but it means that you don't need to carry along a copy of the library that is being used. As the code is connected at compile time there are not any additional run-time loading costs. The code is simply there.
Personally, I prefer shared libraries, but use static libraries when needing to ensure that the binary does not have many external dependencies that may be difficult to meet, such as specific versions of the C++ standard library or specific versions of the Boost C++ library.
|
2,649,461 | 2,666,646 | Why can't my c++ program find the necessary .dll file? | I am trying to use OpenCV (a computer vision library), which appearently uses a few .dll files, located in C:\OpenCV\bin (which has been added to the system PATH variable). However, if I try to run a simple test program, it gives a system error:
The program can't start because highgui.dll is missing from your computer. Try reinstalling the program to fix this problem.
If I copy the highgui.dll file into the system32 folder, it works, but I don't want to have to put all the necessary .dll files in the system32 folder.
Does anyone know why the .dll file can't be found or what I should do to fix it?
(I already checked all paths in the PATH variable for validity.)
| I tracked down the executable that was built by Netbeans before running and launched it, and it gave no errors (so Netbeans probably uses its own paths for executing), so tried to find out how I could make Netbeans search the right paths for the DLLs, and after adding an environment variable PATH=C:/OpenCV2.1/bin (Project Properties > Run > Environment), the program ran correctly!
I do hope this is not some sort of hack that 'acdidentally' solves my problem while creating worse side-effects...
Thanks for the help!
|
2,649,634 | 2,649,688 | 'dxerr9.h': No such file or directory | I am trying to compile a program I took off a cd from a book that uses directx to render 3d objects. when i press compile I get the following error
C1083: Cannot open include file: 'dxerr9.h': No such file or directory
I am using VC++ 2008 Express Edition and i am running off of Vista. I went to the following folder
[edit]
C:\Program Files (x86)\Microsoft DirectX SDK (February 2010)\Include
I was able to find dxerr.h in the folder and the path is also being included in the VC++ Directories tab in the options window. dont know whats going on.
| It seems your program was written using older version of DirectX SDK. The 'dxerr9.h' is present at least in "Microsoft DirectX 9.0 SDK (December 2004)", but is absent at least in "Microsoft DirectX SDK (August 2009)".
|
2,649,653 | 2,649,691 | Change an array's value in x86 assembly (embedded in C++) | I am messing around with assembly for the first time, and can't seem to change the index values of an array. Here's the method I am working on
int ascending_sort( char arrayOfLetters[], int arraySize )
{
char temp;
__asm
{
//???
}
}
And these are what I tried
mov temp, 'X'
mov al, temp
mov arrayOfLetters[0], al
And this gave me an error C2415: improper operand type
so I tried
mov temp, 'X'
mov al, temp
mov BYTE PTR arrayOfLetters[0], al
This complied, but it didn't change the array...
| The arrayOfLetters value is equivalent to a pointer. So, your assembly code might need to be:
mov temp, 'X'
mov al, temp
mov edx, arrayOfLetters
mov [edx], al
In the above code, edx is loaded with the address of arrayOfLetters. Then the last instruction stores the al byte into the address pointed to by edx.
|
2,649,674 | 2,649,831 | How do I use texture-mapping in a simple ray tracer? | I am attempting to add features to a ray tracer in C++. Namely, I am trying to add texture mapping to the spheres. For simplicity, I am using an array to store the texture data. I obtained the texture data by using a hex editor and copying the correct byte values into an array in my code. This was just for my testing purposes. When the values of this array correspond to an image that is simply red, it appears to work close to what is expected except there is no shading.
first image http://dl.dropbox.com/u/367232/Texture.jpg
The bottom right of the image shows what a correct sphere should look like. This sphere's colour using one set colour, not a texture map.
Another problem is that when the texture map is of something other than just one colour pixels, it turns white. My test image is a picture of water, and when it maps, it shows only one ring of bluish pixels surrounding the white colour.
bmp http://dl.dropbox.com/u/367232/vPoolWater.bmp
When this is done, it simply appears as this:
second image http://dl.dropbox.com/u/367232/texture2.jpg
Here are a few code snippets:
Color getColor(const Object *object,const Ray *ray, float *t)
{
if (object->materialType == TEXTDIF || object->materialType == TEXTMATTE) {
float distance = *t;
Point pnt = ray->origin + ray->direction * distance;
Point oc = object->center;
Vector ve = Point(oc.x,oc.y,oc.z+1) - oc;
Normalize(&ve);
Vector vn = Point(oc.x,oc.y+1,oc.z) - oc;
Normalize(&vn);
Vector vp = pnt - oc;
Normalize(&vp);
double phi = acos(-vn.dot(vp));
float v = phi / M_PI;
float u;
float num1 = (float)acos(vp.dot(ve));
float num = (num1 /(float) sin(phi));
float theta = num /(float) (2 * M_PI);
if (theta < 0 || theta == NAN) {theta = 0;}
if (vn.cross(ve).dot(vp) > 0) {
u = theta;
}
else {
u = 1 - theta;
}
int x = (u * IMAGE_WIDTH) -1;
int y = (v * IMAGE_WIDTH) -1;
int p = (y * IMAGE_WIDTH + x)*3;
return Color(TEXT_DATA[p+2],TEXT_DATA[p+1],TEXT_DATA[p]);
}
else {
return object->color;
}
};
I call the colour code here in Trace:
if (object->materialType == MATTE)
return getColor(object, ray, &t);
Ray shadowRay;
int isInShadow = 0;
shadowRay.origin.x = pHit.x + nHit.x * bias;
shadowRay.origin.y = pHit.y + nHit.y * bias;
shadowRay.origin.z = pHit.z + nHit.z * bias;
shadowRay.direction = light->object->center - pHit;
float len = shadowRay.direction.length();
Normalize(&shadowRay.direction);
float LdotN = shadowRay.direction.dot(nHit);
if (LdotN < 0)
return 0;
Color lightColor = light->object->color;
for (int k = 0; k < numObjects; k++) {
if (Intersect(objects[k], &shadowRay, &t) && !objects[k]->isLight) {
if (objects[k]->materialType == GLASS)
lightColor *= getColor(objects[k], &shadowRay, &t); // attenuate light color by glass color
else
isInShadow = 1;
break;
}
}
lightColor *= 1.f/(len*len);
return (isInShadow) ? 0 : getColor(object, &shadowRay, &t) * lightColor * LdotN;
}
I left out the rest of the code as to not bog down the post, but it can be seen here. Any help is greatly appreciated. The only portion not included in the code, is where I define the texture data, which as I said, is simply taken straight from a bitmap file of the above image.
Thanks.
| It could be that the texture is just washed out because the light is so bright and so close. Notice how in the solid red case, there doesn't seem to be any gradation around the sphere. The red looks like it's saturated.
Your u,v mapping looks right, but there could be a mistake there. I'd add some assert statements to make sure u and v and really between 0 and 1 and that the p index into your TEXT_DATA array is also within range.
|
2,649,676 | 2,650,431 | C++ Win32 API equivalent of CultureInfo.TwoLetterISOLanguageName | The .NET framework makes it easy to get information about various locales; the Win32 C++ APIs are a bit harder to figure out.
Is there an equivalent function in Win32 to get the two-letter ISO language name given an integer locale ID?
In C# I'd do:
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(1034);
string iso = ci.TwoLetterISOLanguageName;
// iso == "es" now.
The code needs to run on XP and newer.
| Thanks to Trevor for directing me toward this answer in an earlier reply.
Call GetLocaleInfo with the LOCALE_SISO639LANGNAME parameter.
|
2,649,717 | 2,649,761 | C++ function for picking from a list where each element has a distinct probability | I have an array of structs and one of the fields in the struct is a float. I want to pick one of the structs where the probability of picking it is relative to the value of the float. ie
struct s{
float probability;
...
}
s sArray[50];
What is the fastest way to decide which s to pick? Is there a function for this? If I knew the sum of all the probability fields (Note it will not be 1), then could I iterate through each s and compare probability/total_probability with a random number, changing the random number for each s? ie
if( (float) (rand() / RAND_MAX) < probability)...
| float p = (rand() / static_cast<float>(RAND_MAX)) * total_probability;
s* current = &sArray[0];
while ( (p -= current->probability) > 0)
++current;
// `current` now points to your chosen target
|
2,650,034 | 2,650,141 | How to use mmap to point to STL type? | I have a mmap typecast to a char pointer
char *ptr;
ptr = (char *)mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
This was my earlier code. But now I want to use a map instead of char * as the requirements changed.
Now, my map is declared as
map < int, string > i_s_map;
How do I change my mmap call to point to the map?
| You don't want to store STL containers in shared memory, at least not share them. The reason is that they rely heavily on heap allocation, so out-of-the-box std::map will hold pointers from virtual address space of a different process.
Take a look at boost::interprocess for a way to deal with this situation in C++.
|
2,650,183 | 2,650,217 | Use auto_ptr in VC6 dll cause crash | // dll
#include <memory>
__declspec(dllexport) std::auto_ptr<int> get();
__declspec(dllexport) std::auto_ptr<int> get()
{
return std::auto_ptr<int>(new int());
}
// exe
#include <iostream>
#include <memory>
__declspec(dllimport) std::auto_ptr<int> get();
int main() {
{
std::auto_ptr<int> x = get();
}
std::cout << "done\n";
getchar();
}
The following code run perfectly OK under VC9. However, under VC6, I will experience an immediate crash with the following message.
Debug Assertion Failed!
Program:
C:\Projects\use_dynamic_link\Debug\use_dynamic_link.exe
File: dbgheap.c Line: 1044
Expression:
_CrtIsValidHeapPointer(pUserData)
Is it exporting auto_ptr under VC6 is not allowed?
It is a known problem that exporting STL collection classes through DLL.
Access Violation When Accessing an STL Object Through A Pointer or Reference In A Different DLL or EXE
However, I Google around and do not see anything mention for std::auto_ptr.
Any workaround?
| A DLL has its own heap, so you have to make sure you new and delete from the same context.
|
2,650,196 | 2,650,253 | Port Win32 DLL hook to Linux | I have a program (NWShader) which hooks into a second program's OpenGL calls (NWN) to do post-processing effects and whatnot.
NWShader was originally built for Windows, generally modern versions (win32), and uses both DLL exports (to get Windows to load it and grab some OpenGL functions) and Detours (to hook into other functions). I'm using the trick where Win will look in the current directory for any DLLs before checking the sysdir, so it loads mine. I have on DLL that redirects with this method:
#pragma comment(linker, "/export:oldFunc=nwshader.newFunc)
To send them to a different named function in my own DLL. I then do any processing and call the original function from the system DLL.
I need to port NWShader to Linux (NWN exists in both flavors). As far as I can tell, what I need to make is a shared library (.so file). If this is preloaded before the NWN executable (I found a shell script to handle this), my functions will be called. The only problem is I need to call the original function (I would use various DLL dynamic loading methods for this, I think) and need to be able to do Detour-like hooking of internal functions.
At the moment I'm building on Ubuntu 9.10 x64 (with the 32-bit compiler flags). I haven't been able to find much on Google to help with this, but I don't know exactly what the *nix community refers to it as. I can code C++, but I'm more used to Windows. Being OpenGL, the only part the needs modified to be compatible with Linux is the hooking code and the calls. Is there a simple and easy way to do this, or will it involve recreating Detours and dynamically loading the original function addresses?
| The library preloading can be done through LD_PRELOAD. From there you want to look at the dlopen and dlsym calls to get at the actual functions in the original library. This is all if you want to do things by hand.
You can also look at modifying ltrace in a way such that you provide the functions to hook (via the -e flag) and let ltrace handle the bookkeeping for you.
[Edit] An example of doing this by hand:
#include <dlfcn.h>
#include <stdio.h>
int (*orig_puts)(const char *);
int puts (const char * str) {
void * handle = dlopen("/lib/libc.so.6", RTLD_NOW | RTLD_GLOBAL);
orig_puts = dlsym(handle,"puts");
fprintf (stderr,"I have hooked your puts\n");
return orig_puts(str);
}
And with a program such as
#include <stdio.h>
int main () {
puts ("Hello World");
return 0;
}
You get the following:
$ ./a.out
Hello World
$ LD_PRELOAD=./libhook ./a.out
I have hooked your puts
Hello World
|
2,650,244 | 2,650,251 | formatting an integer output using ostream | I am trying to find the equivalence of %2d using cout << <<endl format. how can I do that?
| The header <iomanip> contains the stream manipuator setw:
cout << setw(2) << myint << endl
You may also be interested in setfill:
cout << setfill('0') << setw(2) << myint << endl
will pad with a 0 instead of a space.
|
2,650,345 | 2,650,569 | ImageMagick vs. Cairo on Vector Graphics rasterization | I am working on a project that needs rasterizing of drawings into image files. I have already got it work using GDI+. Wanting to create a portable solution, I am also looking into other solutions and found two - cairo and imagemagick. I am new to both, but it seems that ImageMagick can do almost all the stuff - drawing lines, arcs, circles, text etc.. plus many bitmap manipulation.
However, Cairo is mentioned as competitor to GDI+ in web sites. ImageMagick is never mentioned for this purpose.
I do not have time to invest on both libraries. I need to decide which one is worthy.
I prefer to ImageMagick, as it seems much more powerful.
What's your opinion on the two graphic libs?
| Cairo by itself can't do very much in the way of bitmap manipulation - at least in the sense that ImageMagick can. It is, however, a very powerful vector imaging library, and can do almost everything that GDI+ can do, up to the point where it's practically a suitable replacement for DirectDraw 2D. It can also produce and use bitmap images, and directly supports the PNG image format.
ImageMagick, on the other hand, is a bitmap image library. It has less of a focus on vector graphics than Cairo does, and instead directly produces bitmap representations of vector shapes. On the other hand, it also does a lot Cairo can't do natively, including text rasterization; IM also supports virtually every image format known to Man, and can import and export them with relative ease.
Use Cairo if you need to do scalable vector graphics.
Use ImageMagick if you are ouputting to bitmap or raster formats.
|
2,650,374 | 2,650,432 | c++ Initializing a struct with an array as a member | Edited again because it originally wasn't clear that I'm trying to initialize the arrays at compile time, not at run time...
I've got the following reduced testcase:
typedef struct TestStruct
{
int length;
int values[];
};
TestStruct t = {3, {0, 1, 2}};
TestStruct t2 = {4, {0, 1, 2, 3}};
int main()
{
return(0);
}
This works with Visual C++, but doesn't compile with g++ under linux. Can anyone help me make this specific kind of initializer portable?
Additional details: the actual structure I'm working with has several other int values, and the array can range in length from a single entry to over 1800 entries.
EDIT: I think (but am not sure) that this is not a VLA issue. To clarify, I'm trying to get the compiler to do the work for me at compile-time. The length of the array at run-time is constant. Apologies if I'm wrong; I'm primarily a c#/Perl/Ruby programmer who is stuck maintaining this legacy app...
Any help much appreciated. Thanks!
| c++ doesn't have the same flexible array member as last element as c99. You should use a std::vector if you don't know how many elements or you should specify how many if you do.
EDIT: You have said in your edit that the array is a runtime constant, so specify the size and it should work fine. g++ has no problem with the following code:
struct TestStruct { // note typedef is not needed */
int length;
int values[3]; // specified the size
};
TestStruct t = {3, {0, 1, 2}};
int main() {
// main implicitly returns 0 if none specified
}
EDIT: to address your comment, you could use templates like this:
template <int N>
struct TestStruct {
int length;
int values[N];
};
TestStruct<3> t3 = {3, {0, 1, 2}};
TestStruct<2> t2 = {2, {0, 1}};
int main() {}
The only problem is that there is no easy way to put both t2 and t3 in a container (like a list/vector/stack/queue/etc because they have different sizes. If you want that, you should use std::vector. Also, if you are doing that, then it isn't necessary to store the size (it is associated with the type). So you could do this instead:
template <int N>
struct TestStruct {
static const int length = N;
int values[N];
};
TestStruct<3> t3 = {{0, 1, 2}};
TestStruct<2> t2 = {{0, 1}};
int main() {}
But once again, you cannot put t2 and t3 in a "collection" together easily.
EDIT:
All in all, it sounds like you (unless you store more data than just some numbers and the size) don't need a struct at all, and can't just use a plain old vector.
typedef std::vector<int> TestStruct;
int t2_init[] = { 0, 1, 2 };
TestStruct t3(t3_init, t3_init + 3);
int t2_init[] = { 0, 1 };
TestStruct t2(t2_init, t2_init + 2);
int main() {}
Which would allow you to have both t2 and t3 in a collection together. Unfortunately std::vector doesn't (yet) have array style initializer syntax, so i've used a shortcut. But it's simple enough to write a function to populate the vectors in a nice fashion.
EDIT: OK, so you don't need a collection, but you need to pass it to a function, you can use templates for that to preserve type safety!
template <int N>
struct TestStruct {
static const int length = N;
int values[N];
};
TestStruct<3> t3 = {{0, 1, 2}};
TestStruct<2> t2 = {{0, 1}};
template <int N>
void func(const TestStruct<N> &ts) { /* you could make it non-const if you need it to modify the ts */
for(int i = 0; i < N; ++i) { /* we could also use ts.length instead of N here */
std::cout << ts.values[i] << std::endl;
}
}
// this will work too...
template <class T>
void func2(const T &ts) {
for(int i = 0; i < ts.length; ++i) {
std::cout << ts.values[i] << std::endl;
}
}
int main() {
func(t2);
func(t3);
func2(t2);
}
|
2,650,614 | 2,650,792 | How to use/manipulate return value from nested boost::bind | I have two functions:
1. A & DataSource();
2. void DataConsumer( A * );
What I want to achieve: Using one statement to assemble them into one functor.
I have tried:
1. boost::function< void()> func( boost::bind( DataConsumer, & boost::bind( DataSource ) ) );
certainly it didn't work, compiler says it can not convert 'boost::_bi::bind_t ' to 'A *'
2. boost::function< void()> func( boost::bind( DataConsumer, boost::addressof( boost::bind( DataSource ) ) ));
compiler says cannot convert parameter 1 from 'boost::_bi::bind_t' to 'A &'
Question: how to use return value from the nested boost::bind ? or if you want to use boost::lambda::bind.
| guys, I just found the answer, like following:
boost::function< void()> func(
boost::bind( DataConsumer,
boost::bind( boost::addressof< A >, boost::bind< A& >( DataSource ) )
) );
The theory should be: since we call DataSource later, we need a functor that uses the return value later as well.
|
2,650,634 | 2,650,690 | void foo(int &x) -> Ruby? Passing integers by reference? | as a way to spice up my C++ programming homework, I've decided to instead of typing the C++ from the book onto my computer, instead reforming it in Ruby. Yes it's a bit silly, but I'm bored.
Anyway, I'm having trouble converting this kind of function to Ruby
void swap(int &a,int &b){
int c=b;
b=a;
a=c
}
What would be the equivalent ruby code inside a function ?
| Ruby is strictly pass-by-value. Always. But sometimes those values are poointers.
Here's a couple of links:
Java is Pass-by-Value, Dammit! (Scott "JavaDude" Stanchfield)
Parameter passing in Java (Jon Skeet)
Does Java pass by reference?
Java, pass-by-value, reference variables
Note that while all of these say "Java", they should really say "Smalltalk and its descendants", which includes Java, Ruby and a ton of other languages.
I think most of the confusion stems from two problems:
Ruby passes references by value. But the word "reference" in that sentence is not the same as the word "reference" in "pass-by-reference". Maybe it is clearer when we disambiguate: let's replace "pass-by-reference" with "pass-by-variable" and "reference" with "pointer" (note that these are "good" well-behaved poointers, not the "bad" ones from C):
Fortran is pass-by-variable
Ruby is pass-by-value and the values it passes are mostly poointers
The references (poointers) that Ruby passes point to mutable objects. Therefore, while you cannot change the reference, you can mutate the objects that the reference points to. The problem here is that Ruby (like most imperative object-oriented languages) confuses the concepts of identity, state and value. You can learn more about that problem and how to fix it here (Note that while they say "Clojure", the concepts that are presented are universal and could be applied equally well to OO):
Persistent Data Structures and Managed References - Clojure's Approach to Identity and State - Rich Hickey - QCon London 2009
Are We There Yet? - A deconstruction of object-oriented time - Rich Hickey - JVM Language Summit
BTW: I deliberately misspelt "poointers" with an OO for object-orientation to make it clear that I am not talking about raw memory addresses, I am talking about opaque references to objects (and for obvious reasons I do not want to use the word "reference"; if you know a better word that is neither "pointer" nor "reference", I'd love to hear it).
|
2,650,644 | 2,651,014 | Why does forward declaration not work with classes? | int main() {
B bb; //does not compile (neither does class B bb;)
C cc; //does not compile
struct t tt; //compiles
class B {}; //HERE is the class B defination
struct s { struct t * pt; }; //compiles
struct t { struct s * ps; };
return 0;
}
class C {};
I just modified the example given here.
Why is that the struct forward declarations work but not the class forward declarations?
Does it have something to do with the namespaces - tag namespace and typedef namespace? I know that the structure definitions without typedefs go to tag namespace.
Structures are just classes with all public members. So, I expect them to behave similarly.
| Forward declaration works for classes, but other then you have expected.
First, you have to write class B; before the code of your main routine.
Then you have to write B * bb; instead of B bb;. You can construct an object of type B only after class definition.
The reason for this behavior is as follows: The compiler does not know how many bytes it has to allocate on the stack for an instance of class B, as this information depends on the definition of the class (which you have not given at that time). A pointer to an instance of class B however can be constructed after a forward declaration of B, since the size of a pointer is previously known (and the normally the same for all pointer types).
|
2,650,663 | 2,650,679 | Possible to convert list of #defines into strings | Suppose I have a list of #defines in a header file for an external library. These #defines represent error codes returned from functions. I want to write a conversion function that can take as an input an error code and return as an output a string literal representing the actual #define name.
As an example, if I have
#define NO_ERROR 0
#define ONE_KIND_OF_ERROR 1
#define ANOTHER_KIND_OF_ERROR 2
I would like a function to be able to called like
int errorCode = doSomeLibraryFunction();
if (errorCode)
writeToLog(convertToString(errorCode));
And have convertToString() be able to auto-convert that error code without being a giant switch-case looking like
const char* convertToString(int errorCode)
{
switch (errorCode)
{
case NO_ERROR:
return "NO_ERROR";
case ONE_KIND_OF_ERROR:
return "ONE_KIND_OF_ERROR";
...
...
...
I have a feeling that if this is possible, it would be possible using templates and metaprogramming, but that would only work the error codes were actually a type and not a bunch of processor macros.
| I normally do it the giant switch case way, although I make it somewhat easier with:
#define STR(code) case code: return #code
switch (errorCode)
{
STR(NO_ERROR);
STR(ONE_KIND_OF_ERROR);
}
This is a good question, I'm interested to see what better ways people have
|
2,650,800 | 2,650,978 | Use one single DLL library to import other libraries at runtime | I am writing a Win32 DLL library that can be redistributed. I am using different versions of the windows API because I want to support Windows 7 functions, but still have support for Windows 2000 (with some function disabled). What I have currently is MyLib2000.dll, MyLibXP.dll, and MyLibVista.dll, and my application chooses which library to load at runtime. I want a way to have a single DLL (MyLib.dll) that stores the other three in itself and when it's being loaded, it extracts the correct DLL out of itself and loads it.
I know this is not the best way to do this, so suggestions on another method of doing this is welcome.
| Use delayloading and implement the dliNotePreLoadLibrary notification hook to load the correct version of your DLL. The linker-provided delay load logic will then pull in all the functions from whichever DLL you loaded.
http://msdn.microsoft.com/en-us/library/z9h1h6ty(v=VS.100).aspx
Or use delay-loading and implement your functions to check the OS version before calling any function that could fail to be loaded (since it doesn't exist on the old OS).
|
2,650,816 | 2,650,833 | C++: Should I use strings or char arrays, in general? | I'm a bit fuzzy on the basic ways in which programmers code differently in C and C++. One thing in particular is the usage of strings in C++ over char arrays, or vice versa. So, should I use strings or char arrays, in general, and why?
| In C++ you should in almost all cases use std::string instead of a raw char array.
std::string manages the underlying memory for you, which is by itself a good enough reason to prefer it.
It also provides a much easier to use and more readable interface for common string operations, e.g. equality testing, concatenation, substring operations, searching, and iteration.
|
2,650,893 | 2,651,406 | What are good RPC frameworks between a Java server and C++ clients? | I am looking for a RPC stack that can be used between a Java Server and C++ clients.
My requirements are:
Ease of integration (for both C++ and Java)
Performance, especially number of concurrent connections and response time. Payload are mostly binaries (8-100kb)
I found some like:
http://code.google.com/p/protobuf-socket-rpc/
http://code.google.com/p/netty-protobuf-rpc/
Are there any other good alternatives?
| Thrift might be worth investigating.
|
2,651,062 | 2,651,089 | friendship and operator overloading help | I have the following class
#ifndef Container_H
#define Container_H
#include <iostream>
using namespace std;
class Container{
friend bool operator==(const Container &rhs,const Container &lhs);
public:
void display(ostream & out) const;
private:
int sizeC; // size of Container
int capacityC; // capacity of dynamic array
int * elements; // pntr to dynamic array
};
ostream & operator<< (ostream & out, const Container & aCont);
#endif
and this source file
#include "container.h"
/*----------------------------*********************************************
note: to test whether capacityC and sizeC are equal, must i add 1 to sizeC?
seeing as sizeC starts off with 0??
*/
Container::Container(int maxCapacity){
capacityC = maxCapacity;
elements = new int [capacityC];
sizeC = 0;
}
Container::~Container(){
delete [] elements;
}
Container::Container(const Container & origCont){
//copy constructor?
int i = 0;
for (i = 0; i<capacityC; i++){ //capacity to be used here?
(*this).elements[i] = origCont.elements[i];
}
}
bool Container::empty() const{
if (sizeC == 0){
return true;
}else{
return false;
}
}
void Container::insert(int item, int index){
if ( sizeC == capacityC ){
cout << "\n*** Next: Bye!\n";
return; // ? have return here?
}
if ( (index >= 0) && (index <= capacityC) ){
elements[index] = item;
sizeC++;
}
if ( (index < 0) && (index > capacityC) ){
cout<<"*** Illegal location to insert--"<< index << ". Container unchanged. ***\n";
}//error here not valid? according to original a3? have i implemented wrong?
}
void Container::erase(int index){
if ( (index >= 0) && (index <= capacityC) ){ //correct here? legal location?
int i = 0;
while (i<capacityC){ //correct?
elements[index] = elements[index+1]; //check if index increases here.
i++;
}
sizeC=sizeC-1; //correct? updated sizeC?
}else{
cout<<"*** Illegal location to be removed--"<< index << ". Container unchanged. ***\n";
}
}
int Container::size()const{
return sizeC; //correct?
}
/*
bool Container::operator==(const Container &rhs,const Container &lhs){
int equal = 0, i = 0;
for (i = 0; i < capacityC ; i++){
if ( rhs.elements[i] == lhs.elements[i] ){
equal++;
}
}
if (equal == sizeC){
return true;
}else{
return false;
}
}
ostream & operator<< (ostream & out, const Container & aCont){
int i = 0;
for (i = 0; i<sizeC; i++){
out<< aCont.elements[i] << " " << endl;
}
}
*/
I dont have the other functions in the header file (just a quikie). Anyways, the last two functions in "/* */" I cant get to work, what am I doing wrong here?
the first function is to see whether the two arrays are equal to one another
| When you declare a function as a friend inside of a class, the function is a non-member function and is as if it was declared in the enclosing namespace. So, in your case, your declaration of a friend operator==,
class Container
{
friend bool operator==(const Container &rhs,const Container &lhs);
};
is a non-member function as if you had declared it outside of the class, like so:
class Container
{
};
bool operator==(const Container &rhs,const Container &lhs);
Note that when you declare a friend function, the function has access to the private members of the class as well, so this isn't exactly the same.
So, your definition of operator== as if it were a member function is incorrect:
bool Container::operator==(const Container &rhs,const Container &lhs) { ... }
should be
bool operator==(const Container &rhs,const Container &lhs) { ... }
As for your operator<< overload, it is not a friend of Container, so it does not have access to the private elements member of Container. Either make operator<< a friend or add public accessors to the class such that it can access the private members through them.
|
2,651,101 | 3,565,124 | C/C++-Library for EEPROM wear-leveling under Linux? | does anybody know of a library for storing data securely in an 8k-EEPROM, which is attached over the I2C-interface? I am especially interested in wear-leveling as I have a write-intensive application where the EEPROM should/must be used as a NVRAM for often-chaning measurement data.
Thanks in advance, Martin
| The only wear levelling code I've ever come across is in the MTD drivers in the kernel - either in the old JFFS2 filesystem or in the UBI level. These are designed for much larger FLASH devices, with correspondingly larger block sizes (typically 64KB). However, you might get some idea from the code (e.g. see drivers/mtd/ubi/wl.c in the kernel tree).
Otherwise, for your measurement data, you'll probably just have to maintain a ring buffer, as large as you can, and write each measurement into consecutive locations, along with a timestamp so that you can later come along and locate the latest one.
|
2,651,170 | 2,651,349 | Immutable classes in C++ | In one of my projects, I have some classes that represent entities that cannot change once created, aka. immutable classes.
Example : A class RSAKey that represent a RSA key which only has const methods. There is no point changing the existing instance: if you need another one, you just create one.
My objects sometimes are heavy and I enforced the use of smart pointers to avoid deep copy.
So far, I have the following pattern for my classes:
class RSAKey : public boost::noncopyable, public boost::enable_shared_from_this<RSAKey>
{
public:
/**
* \brief Some factory.
* \param member A member value.
* \return An instance.
*/
static boost::shared_ptr<const RSAKey> createFromMember(int member);
/**
* \brief Get a member.
* \return The member.
*/
int getMember() const;
private:
/**
* \brief Constructor.
* \param member A member.
*/
RSAKey(int member);
/**
* \brief Member.
*/
const int m_member;
};
So you can only get a pointer (well, a smart pointer) to a const RSAKey. To me, it makes sense, because having a non-const reference to the instance is useless (it only has const methods).
Do you guys see any issue regarding this pattern ? Are immutable classes something common in C++ or did I just created a monster ?
Thank you for your advices !
| Looks good to me.
Marking every object const from the factory obviates marking every data member const, but in this example there is only one anyway.
|
2,651,586 | 2,651,658 | boost::dynamic_pointer_cast with const pointer not working? | Let's say I have two classes, A and B, where B is a child class of A.
I also have the following function:
void foo(boost::shared_ptr<const A> a)
{
boost::shared_ptr<const B> b = boost::dynamic_pointer_cast<const B>(a); // Error !
}
Compilation with gcc gives me the following errors:
C:\Boost\include/boost/smart_ptr/shared_ptr.hpp: In constructor 'boost::shared_ptr< <template-parameter-1-1> >::shared_ptr(const boost::shared_ptr<Y>&, boost::detail::dynamic_cast_tag) [with Y = const A, T = const B]':
C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:522: instantiated from 'boost::shared_ptr<X> boost::dynamic_pointer_cast(const boost::shared_ptr<U>&) [with T = const B, U = const A]'
src\a.cpp:10: instantiated from here
C:\Boost\include/boost/smart_ptr/shared_ptr.hpp:259: error: cannot dynamic_cast 'r->boost::shared_ptr<const A>::px' (of type 'const class A* const') to type 'const class B*' (source type is not polymorphic)
What could possibly be wrong ?
Thank you.
EDIT
Actually, I found out how to avoid this, but I'm not sure to understand.
My A class was empty (and thus had no virtual destructor). If I add a virtual destructor, the error goes out. But I don't get it, why is this required ?
| dynamic_pointer_cast uses the C++ dynamic_cast internally and dynamic_cast requires your classes to have at least one virtual method. No virtual methods means no vtable and without vtable dynamic_cast would not be able to figure which casts are doable at run-time.
|
2,651,598 | 2,651,621 | Finding the left-most and right-most points of a list. std::find_if the right way to go? | I have a list of Point objects, (each one with x,y properties) and would like to find the left-most and right-most points. I've been trying to do it with find_if, but i'm not sure its the way to go, because i can't seem to pass a comparator instance. Is find_if the way to go? Seems not. So, is there an algorithm in <algorithm> to achieve this?
Thanks in advance.
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
typedef struct Point{
float x;
float y;
} Point;
bool left(Point& p1,Point& p2)
{
return p1.x < p2.x;
}
int main(){
Point p1 ={-1,0};
Point p2 ={1,0};
Point p3 ={5,0};
Point p4 ={7,0};
list <Point> points;
points.push_back(p1);
points.push_back(p2);
points.push_back(p3);
points.push_back(p4);
//Should return an interator to p1.
find_if(points.begin(),points.end(),left);
return 0;
}
| Use std::min_element and std::max_element instead.
list<Point>::iterator left = std::min_element(points.begin(), points.end(), left);
list<Point>::iterator right = std::max_element(points.begin(), points.end(), left);
I would also change the signature of left to:
bool left(const Point& p1, const Point& p2)
|
2,651,663 | 2,652,420 | C++: Binding to a base class | EDIT:
In the following code container::push takes an object of type T that derives from base as argument and stores in a vector a pointer to the method bool T::test().
container::call calls each of the stored methods in the context of to the member object p, which has type base, not T. It works as long as the called method does not refer to any member outside base and if test() is not declared virtual.
I know this is ugly and may not be even correct.
How can I accomplish the same thing in a better way?
#include <iostream>
#include <tr1/functional>
#include <vector>
class base {
public:
base(int v) : x(v)
{}
bool test() const { // this is NOT called
return false;
}
protected:
int x;
};
class derived : public base {
public:
bool test() const { // this is called instead
return (x == 42);
}
};
class container {
public:
container() : p(42)
{}
template<typename T>
void push(const T&) {
vec.push_back((bool (base::*)() const) &T::test);
}
void call() {
std::vector<bool (base::*)() const>::iterator i;
for(i = vec.begin(); i != vec.end(); ++i) {
if( (p .* (*i))() ) {
std::cout << "ok\n";
}
}
}
private:
std::vector<bool (base::*)() const> vec;
base p;
};
int main(int argc, char* argv[]) {
container c;
c.push(derived());
c.call();
return 0;
}
| To the updated question:
Calling a derived member function on a base object is Undefined Behavior. What you are trying to achieve (code) is wrong. Try to post what you need and people will help with a sensible design.
|
2,651,730 | 2,651,745 | Equivalent for Java's System.getProperty("java.io.tmpdir") in C? | As the title says, the java.io.tmpdir property in Java is really nice, and I can't find an equivalent for C. I'm writing for Windows and in Visual Studio. I don't want to just use something like C:\Temp because in later versions of windows the appropriate directory could be something like C:\Users\[UserName]\AppData\Local\Temp and a way to retrieve this would be much easier. I want a directory and not just a temp file because I'm downloading and executing a file from the internet.
As a side note, if anyone can give me tips about how to better google for C stuff it would be much appreciated :)
| If you're using the Win32 API, you can use GetTempPath().
|
2,651,850 | 2,651,859 | Can func get the lineno who call itself? (C/C++) | I've a problem , as the following code discribe itself.
1 #include<stdlib.h>
2 #include<stdio.h>
3 void log()
4 {
5 printf("Log [Line:%d]\n",__LINE__);
6 }
7 int main()
8 {
9 log();
10 log();
11 }
The expected result is
Log [Line:9]
Log [Line:10]
But, the fact is
Log [Line:5]
Log [Line:5]
No surprising, LINE has been substituted at the pre-process stage as 5.
My Question is, how to design the log function to get the expected result?
Thanks!
| You need to write a macro:
#define LOG printf("Log [Line:%d]\n",__LINE__)
then use it:
int main() {
LOG;
LOG;
}
This works because the macro is expanded at its point of use, giving the __LINE__ macro the correct value.
|
2,651,896 | 2,651,919 | Why doesn't free(p) set p to NULL? | Any reasons why this can not be standard behavior of free()?
multiple pointers pointing to the same object:
#include <stdlib.h>
#include <stdio.h>
void safefree(void*& p)
{
free(p); p = NULL;
}
int main()
{
int *p = (int *)malloc(sizeof(int));
*p = 1234;
int*& p2 = p;
printf("p=%p p2=%p\n", p, p2);
safefree((void*&)p2);
printf("p=%p p2=%p\n", p, p2);
safefree((void*&)p); // safe
return 0;
}
assignment from malloc demands cast from void*
vice versa:
safefree() demands cast to void*& (reference)
| If it did, you would have to pass a pointer to a pointer to the function:
int * p = malloc( sizeof( int ));
free( & p );
which I'm sure many people would get wrong.
|
2,652,034 | 2,656,438 | A simple hello world NPAPI plugin for Google Chrome? | I am trying to make a chrome plugin but Chrome API doesn't give me enough power. I want to use NPAPI but I have no idea how to use it but I do have experience in Visual C++.
Can someone show me a 'Hello world' in C++ application so I can get started?
| Note: Both Firefox and Chrome will default most plugins to click-to-play soon, with Chrome planning to phase out NPAPI entirely. NPAPI for new projects is discouraged at this point.
NPAPI plugins shouldn't be browser specific (at least as far as possible). Seamonkeys npruntime sample can be considered a basic Hello World for NPAPI. If you care about up-to-date Mac support, you need to take a look at WebKits or Apples samples.
Reading material to get you started:
Building a FireFox plugin - 3 part introduction to NPAPI
Gecko Plugin API reference - NPAPI documentation at MDC
Mac specific info on MDC
There is also the FireBreath project: It is a framework aiming at lowering the entry barrier to browser plugin development and already takes care of most common tasks and issues.
|
2,652,037 | 3,132,134 | How to get the quickfix timestamp? | I've seen in quickfix doxygen documentation that it generates an utc timestamp as soon as it has received a FIX message from a socket file. Have a look in ThreadedSocketConnection::processStream(), it calls then
m_pSession->next( msg, UtcTimeStamp() );
I would like to get that timestamp, because I need it to screen network and QuickFix lib latencies.
I didn't find a way to get it from FixApplication::fromApp() callback or 'Log::onIncoming()' callback.
As I am newbie with quickfix I would like to know if I missed something in the Quickfix documentation. Did anybody ever done that before?
Of course there is other solutions, but for homogeneity with others market acces applications I maintain, I would prefer to avoid them. For instance, I would prefer not to modify QuickFix code source.
And I would like to avoid re-write the application logic that quickfix provide me, quickfix helpping me only for message decoding.
| FIX::SendingTime st;
message.getHeader().getField(st);
Try this out.
|
2,652,164 | 2,652,639 | Compile time Meta-programming, with string literals | I'm writing some code which could really do with some simple compile time metaprogramming. It is common practise to use empty-struct tags as compile time symbols. I need to decorate the tags with some run-time config elements. static variables seem the only way to go (to enable meta-programming), however static variables require global declarations. to side step this Scott Myers suggestion (from the third edition of Effective C++), about sequencing the initialization of static variables by declaring them inside a function instead of as class variables, came to mind.
So I came up with the following code, my hypothesis is that it will let me have a compile-time symbol with string literals use-able at runtime. I'm not missing anything I hope, and that this will work correctly, as long as I populate the runtime fields before I Initialize the depending templates classes ? .
#include <string>
template<class Instance>
class TheBestThing {
public:
static void set_name(const char * name_in) {
get_name() = std::string(name_in);
}
static void set_fs_location(const char * fs_location_in) {
get_fs_location() = std::string(fs_location_in);
}
static std::string & get_fs_location() {
static std::string fs_location;
return fs_location;
}
static std::string & get_name() {
static std::string name;
return name;
}
};
struct tag {};
typedef TheBestThing<tag> tbt;
int main()
{
tbt::set_name("xyz");
tbt::set_fs_location("/etc/lala");
ImportantObject<tbt> SinceSlicedBread;
}
edit:
Made community wiki.
| I've finally understood what the problem was... and your solution does not solve much, if any.
The goal of using local static variable is to provide initialization on first use, thus being safe from the "Initialization Order Fiasco" (by the way, it does not solve the "Destruction Order Fiasco").
But with your design, if you effectively prevent the crash you do not however prevent the issue of using a variable before its value is used.
ImportantObject<tbt> SinceSliceBread; // using an empty string
tbt::set_name("xyz");
Compare with the following use:
std::string& tbt::get_name() { static std::string MName = "xyz"; return MName; }
Here the name is not only created but also initialized on first use. What's the point of using a non initialized name ?
Well, now that we know your solution does not work, let's think a bit. In fact we would like to automate this:
struct tag
{
static const std::string& get_name();
static const std::string& get_fs_location();
};
(with possibly some accessors to modify them)
My first (and easy) solution would be to use a macro (bouh not typesafe):
#define DEFINE_NEW_TAG(Tag_, Name_, FsLocation_) \
struct Tag_ \
{ \
static const std::string& get_name() { \
static const std::string name = #Name_; \
return name; \
} \
static const std::string& get_fs_location() { \
static const std::string fs_location = #FsLocation_; \
return fs_location; \
} \
};
The other solution, in your case, could be to use boost::optional to detect that the value has not been initialized yet, and postpone initialization of the values that depend on it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.