mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First of all, operators like comparison operators should usually be implemented as friend functions, not as member functions. In this case, that is not the problem.

The problem is that your member functions for operators < and == both take a const reference (which is correct), but the member functions are not marked as const themselves. Because member functions are called on an object of the class. If that object happens to be marked as 'const', then it should not be modified, which means that only member functions which don't modify the object can be called, and so, you need to mark those member functions which don't modify the object with the keyword 'const' at the end of the function prototype. As so:

bool operator< (const StrategyKey& stratKey) const //notice 'const' here.
	{
	  //..
        }

	bool operator== (const StrategyKey& StratKey) const //notice 'const' here.
	{
	  //..
	}

The error you are getting is simply because the function find() in map is marked as const, and thus, the constness propagates to all its elements, which means only const member functions can be called on them, which excluded your operator overloads (since they were not const).

Usually, the idiomatic way of implementing this is as follows, using friend functions instead:

class StrategyKey
{
public:
   //...
	friend bool operator< (const StrategyKey& stratKey1, const StrategyKey& stratKey2) 
	{
	  //..
        }

	friend bool operator== (const StrategyKey& StratKey1, const StrategyKey& StratKey2)
	{
	  //..
	}
  //...
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

No.

The methods are associated with the type of the object (i.e. the class), they are not associate with the object, so they require no extra storage space on a per object basis. In fact, you can easily test it, just apply the sizeof() operator on a class with and without methods, both with the same data members. The sizes will be the same.

However, if you have virtual functions in your class, then the objects of that class will have to store a pointer to the virtual table (the virtual table is a simple per-class look-up table of function pointers for all the virtual methods). In this case (if you have one or more virtual functions), the objects will be one "pointer-size" bigger, which is usually negligible (the size of a pointer is usually the same as an "int", i.e. the natural word size of the computer, e.g. 32bits or 64bits). But in the example you showed, you have no virtual functions, so, no virtual table pointer, and thus, it doesn't make a difference.

You can try the following to see for yourself:

#include <iostream>

class A {
public:
   void DoSomething();
   void DoSomethingelse();
private:
   int x, y;
};

class B {
private:
    int x, y;
};

class C {
public:
   virtual void DoSomething();     //notice the 'virtual' here,
   virtual void DoSomethingelse(); // and here.
private:
   int x, y;
};

int main() {
  std::cout << "the size of A is " << sizeof(A) << std::endl;
  std::cout << …
Jsplinter commented: wow, thank you for that great answer! +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you want your addition operator to take a pentathlete_team, it should take a pentathlete_team and return one too. As so:

pentathlete_team operator + ( const pentathlete_team& sec_comp ) const {
				if ( sum_res < 0 ) {
					results ( ) ;
				}
				sec_comp . results ( ) ;
				return pentathlete_team( 0, 0, 0, 0 ,0, 
					sum_res + sec_comp . sum_res ) ;
			}

Notice also that you should pass by const-reference, and mark the member function as const as well. Also, you are going to need a constructor similar to that of pentathlete to construct the result.

Frankly, I have no idea why you are using inheritance here. There really isn't any reasonable "is a" relationship between pentathlete and pentathlete_team.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As L7Sqr said. And, of course, since find_if/find only finds the first occurrence, it is a trivial matter to wrap it in a while loop to find all the occurrences:

int main() {
  std::vector<int> v;
  //populate v. Now, delete all 0 values:
  std::vector<int>::iterator vit = v.begin();
  do {
    vit = std::find(vit, v.end(), 0);
  } while ((vit != v.end()) && ((vit = v.erase(vit)) != v.end()));
};

Additionally, you can define a generic predicate to check a particular data member:

#include <iostream>
#include <vector>
#include <algorithm>

struct Foo {
    int val_;
    Foo(int v) : val_(v) {}
};

template <typename ClassType,typename DataType>
struct check_data_member {
    DataType want_;
    DataType ClassType::*pmember;
    bool operator() (const Foo& f) { return want_ == f.*pmember; }
    Pred (const DataType& x, DataType ClassType::*aPMember) : want_(x), pmember(aPMemeber) {}
};

template <typename ClassType,typename DataType>
check_data_member<ClassType,DataType> make_check(const DataType& val, DataType ClassType::*pmember) {
  return check_data_member<ClassType,DataType>(val,pmember);
};

int main () {
    std::vector< Foo > v;
    for (int i = 0; i < 5; ++i)
        v.push_back (Foo(i));
    std::cout << "length of vector: " << v.size () << std::endl;
    std::vector< Foo >::iterator vit;
    vit = std::find_if (v.begin (), v.end (), make_check(3,&Foo::val_));
    if (vit != v.end ()) {
        std::cout << "Found item to delete..." << std::endl;
        v.erase (vit);
    }
    std::cout << "length of vector: " << v.size () << std::endl;
    return 0;
}

However, if you want your look-ups to be fast, I suggest you use Boost.MultiIndex library to create efficient look-ups via different data members or methods. The library also includes standard generic …

munitjsr2 commented: Thanks, i get it +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Local * pLocal = *(Local**)0xE6EB54; // valid

English translation: Take the literal numeric value of the hexadecimal number E6EB54 and interpret that numeric value as the address of an address to an object of type Local. Dereference this numeric value to obtain value stored at the address it points to; that value is interpreted as the address of an object of type Local. Finally, store that address in a newly created variable called pLocal, of the same type.

NB: I guess you can see why we use a programming language to write programs, and not a regular language like English.. it would be much too verbose.

>>Local * pLocal = (Local**)0xE6EB54; // not sure if this is even valid

That's not valid, but this is: Local* pLocal = (Local*)0xE6EB56; .


Even if the above may compile (and are 'valid' in that sense), it doesn't mean that they are OK. In either cases 1 or 2, needless to say, the program will crash! You cannot just take some literal numeric value and fetch memory at that location, the OS forbids that (for many obvious and less obvious reasons). The only ways to get a valid pointer is by either taking the address of an object (with the & operator), or by getting a pointer in free-store (i.e. allocating a new chunk of memory with the 'new' operator, or equivalent).

NicAx64 commented: roger that , well answered +7
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

FreeImage is a simple open-source library which can do this, no problem. If you have used any other external library in the past, it will be a walk-in-the-park to use this one.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>no, I need to pass it by value.

You are passing it by pointer, not by value. Passing-by-pointer is just a (bad) way of doing passing-by-reference. Here is a simple piece of code that illustrates the three methods:

#include <iostream>

void pass_by_value(int val) {
  val = 42;    //val is a local variable now, so modifying it will not modify the caller's variable.
};

void pass_by_reference(int& val) {
  val = 42;     //val is an alias for the caller's variable, so it can be modified.
};

void pass_by_pointer(int* val) {
  *val = 42;    //val points to the caller's variable, so it can be modified, after dereferencing the pointer 'val'.
};

int main() {
  int i = 0;
  pass_by_value(i);
  std::cout << "Passed-by-value yields i = " << i << std::endl;
  int j = 0;
  pass_by_reference(j);
  std::cout << "Passed-by-ref yields j = " << j << std::endl;
  int k = 0;
  pass_by_pointer(&k); //take the address of k.
  std::cout << "Passed-by-ptr yields k = " << k << std::endl;

  return 0;
};

In the above, the type int is used for the passed parameter. In your case, the type of the passed parameter is 'avl' (pointer to nodo). Make sure you understand what is going on in the above example, it will surely help you understand what you are doing, or trying to do.


>>All this works perfectly, but on the moment I go out of Comprobar_equilibrio(), *r is still the same.

Then, all is NOT working perfectly. I …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

-- Here is a description of what you should NOT do --

You could do what firstPerson suggests, but that would just create an error at line 41 saying that you cannot convert a const T& to a T& (usually, the message for that is: "error: converting parameter of type 'const T&' to 'T&' discards qualifiers").

Now, you could also make the constructor of Node to take a const T& as well, as so:

Node(const T& rItem):pItem(&rItem),pNext(0){}

But, then you will get yet another conversion error at that line because taking the address of a 'const T&' yields a pointer of type 'const T*', and thus, the statement pItem(&rItem) will again say: "error: converting pointer of type 'const T*' to a pointer of type 'T*' discards qualifiers".

Now, you could then make the pointer stored in Node, also be a const pointer, that is, you could write const T* pItem; .

That will get rid of your compilation errors. But it's the worst thing you could do!


-- Here is why the above is so bad --

There is a rule in C++ that allows you to take a temporary variable via a const reference. In other words, this is valid:

void Foo(const int& bar); //some function takes a const reference

int main() {
  Foo(42);     //the function can be called and the const ref can be binded to the temporary value 42, even though that "variable" has no "real" address in …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
if(number == 7) continue;

This will skip the rest of the loop if the number is 7, and it will go back to the start of the loop (i.e. it will increment i, and check the end-condition).

if(number == 7) break;

This will terminate the loop if the number is 7, and it will resume execution after the closing } of the loop.

Loki55 commented: Thanks +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

One big red flag that I see in all your explanations is that you always stick the * next to the name of the pointer. This hints at a classic misunderstanding beginners have with pointers. Notice how I always stuck the * next to the type in the declarations, not next to the variable name (it makes no difference in compilation, but it makes a difference when it comes to understanding it right). Understand this:

int* ptr; //this declares a variable called 'ptr' which stores a pointer (i.e. the address) to an integer (not allocated here).

When you are not in a declaration, if you put the * next to the pointer's name, it will dereference the pointer, meaning it will fetch the value at the address stored in the pointer variable.

When you have a variable, and apply the & operator on it, it takes the address of the variable. The address of a variable is just a value, a temporary value, it is not a pointer variable, and it is certainly not the pointer variable from which the original variable was obtained by dereferencing with *. When you have something that is a value, but is not a variable, in C++ lingo, it is called an rvalue (because it is not a variable, you cannot store values in it, but since it is a value, you can assign that value to a variable, i.e. it can appear on the right-hand-side of an assignment).

>>and it …

Nick Evan commented: good posts in this thread +16
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

No worries, people often use "class" and "object" interchangeably with or without realizing it is wrong to do so. I believe in rigour when it comes to terminology because getting into the habit of using precise terminology improves understanding for yourself and for others.

predator78 commented: I appretiated mike pointing out my error so that I continue to convey what I am saying in a proper fasion. +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I am looking for something to compact the clear and push_back in one line..

I don't see any point in doing this, but what about:

v.clear(); v.push_back(4);

or, if you really want it to be one expression:

std::vector<int>(1,4).swap(v);
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Heard people say c# for big programs,

May I suggest that maybe those people only programmed very small textbook-example-style programs in C++, and then made from "big programs" in C# and found it pretty easy to do. They probably also say "big programs" to mean GUI programs. C# is a RAD language (Rapid Application Development), it isn't surprising, and expected, that people would find it easy to do GUI programs in it, and, as beginners, would be pretty impressed with how "big programs" can be developed rapidly and easily and thus, recommend C# for such tasks. There is probably some truth to it, but, generally, you should not trust some random guys' opinion. You should trust empirical evidence, or, if that is not available, expert opinion (not hear-say or random people).

>> c for fast programs

C is a smaller programming language and thus, it is often more appropriate for very modest hardware (like embedded systems). This may lead some people to think that it is faster, but that is a myth, routinely debunked. C is more light-weight and with less features. Nowadays, applications or systems that actually _require_ the light-weightness of C (or similar languages) are very rare (at least, I think..), but there is an enormous amount of legacy code (e.g. pretty much all major operating systems for example!). Under most benchmark tests out-there, C and C++ are essentially equal in speed and both the fastest out-there (with Java, about 70% slower, and the rest …

iamthwee commented: Good advice and tightly written up. +15
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Ok, so, you mean what is the difference between:

for(GlifPtrVec_t::iterator it = m_Array.begin(); it != m_Array.end(); ++it)
  delete *it;

And:

for(int i = 0; i < m_Array.size(); ++i)
  delete m_Array[i];

You should think of iterators as pointers, that is what they are meant to mimic in a generic way (and they might often be actual pointers). So, say that m_Array_ptr is the raw bits pointer to the start of the array contained in the vector (with type char*), then the two loops translate to this:

char* it = m_Array_ptr;
while( it != m_Array_ptr_end ) {
  delete *it; 
  it += sizeof(Foo*); //assuming Foo* is the type contained in the vector.
};

and:

int i = 0;
for( i < m_Array.size() ) {
  delete *(m_Array_ptr + i * sizeof(Foo*));
  ++i;
};

The former (with iterators) will involve, in each iteration, one condition evaluation and one add-and-assign operation (with a fixed size value). The latter will involve, in each iteration, one condition evaluation, one multiplication, one addition, and one increment (which is basically the same as add-and-assign). It's pretty obvious which is the fastest.

On a style point of view, both are totally fine in the sense that all programmers are very familiar with either styles, and many use a mix of both. But generally, for good practice, it is preferable to use the iterator-based version. The reason is simple. If your loop is not doing random-access, you should stick to a sequential-access format. Obviously, if your loop …

NathanOliver commented: good info +2
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>is there any advantage/disadvantage to doing everything as a template?
Advantages:
- You get truly generic, expendable implementations.
- You suffer no run-time overhead (and often a speed-up).
- Policy, Traits, and Concepts are much more flexible than base classes or interfaces in OOP.
- Inversion of Control (IoC) can be implemented with no overhead.
- Template specializations and special overloads allow you to write case-specific implementations, thus, improving performance.
- Etc. there are many more that I am forgetting.

Disadvantages:
- The implementation (or definition) of all algorithms and functions have to be distributed with the library (you are forced to provide an open-architecture library, you cannot have pre-compiled libraries).
- Increased compilation times.
- Code bloat, both in terms of having to often mix declarations and definitions, and in terms of creating larger executable with much "duplicated" code (although you are not duplicating that code yourself, the compiler does).
- It is more difficult to achieve run-time polymorphism (requires OOP wrappers).

>>Is there any overheads with writing everything as a template?
No. Except for increased compilation times, but the run-time code will be as efficient or more efficient than any non-templated procedural or OOP equivalent.

>>IS there any time it should be avoided?
If you can suffer the disadvantages mentioned above, then NO.

>>Or is it good practice to write everything as a template unless otherwise needed?
It is never …

eskimo456 commented: very helpful fast reply +1
jonsca commented: I always learn good things from your posts +8
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I doubt that any ABM library is able to provide the kind of performance needed for an image processing task (they don't tend to be that stream-lined, or provide the kind of muscle power needed).

If I were you, I would be looking more towards parallel processing frameworks. Like OpenMP or TBB (Intel's Thread Building Blocks, if you have the funds for it). Because, it seems, in your application, the main thing is to do concurrent processing, the agent-based part is accessory. ABMs are used to develop emergent complexity from the interaction of simple agents, it isn't tailored for high-performance parallel processing, it just isn't the right tool for that. There is significant overhead associated to ABMs which you should only cope with if you have a strong motivation for swarm, emergent behaviours. If your application is simply about doing independent processing concurrently, you don't need to suffer that overhead if you go for simpler parallel computing or distributed computing models with much less overhead.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

How you would need to do it is as follows (explanation will follow):

//header.h
#ifndef HEADER_H
#define HEADER_H

void test();

#endif
//main.cpp
#include <iostream>
#include "header.h"   //to find the test() function.

int main()
{
  test();

  return 0;
}
//declerations.cpp
#include "header.h"

#include <iostream> //for using std::cout.

void test()
{
  std::cout << "This is from the function test in declerations.cpp";
}

Each cpp file is what we formally call a "translation unit". They are compiled separately and then linked together. So, since each cpp is compiled separately, they need to #include all the headers that they need for the compilation to work (thus the #include <iostream> and "header.h" in both the main.cpp and declarations.cpp).

Since cpp files are compiled separately and alone, they will never be "included" twice in one compilation run (in one "translation unit"). So, the header-guards (i.e. the #ifndef HEADER_H) are not required for cpp files because their content are guaranteed to appear only once. For header files, this is not the case, and header-guards are needed. Imagine this simple situation:

//in header1.h
int global_value = 10;

//in header2.h
#include "header1.h"

//in main.cpp:
#include "header1.h"
#include "header2.h"    //which will, in turn, include "header1.h" a second time.

int main() {
  return global_value; //ERROR: Which "global_value" should be used? there are two declarations of the same variable, this will not compile due to the One-Definition-Rule in C/C++.
};

Because headers are meant to be included by different files (other headers or cpp files) there is …

thilinam commented: Nicely described the answer. Really easy to understand +3
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Your terminology is wrong, that is why your internet searches on the subject fails to yield anything. The correct term is "passed-by-value" and "passed-by-reference", i.e. "passed" not "call". Call-by-value makes no sense (those who use this terminology do so incorrectly).

In lay terms (similar to GaidinDaishan):
Imagine you are one worker ("function") and your friend is another worker ("function"). Your friend wants you to do something ("call" upon you), but you need a password to accomplish your task (a "parameter" needs to be "passed"). Your friend has the password written on a piece of paper ("variable"). Now, there are two options:

Pass-by-value: You could have your own piece of paper ("local variable") for your friend to write the password on ("copy" its "value"). In this case, you can accomplish your task and your friend preserves the original, unaltered and, more importantly, unalterable.

Pass-by-reference: Your friend could simply pass-on the piece of paper to you. This is cheaper since no-one has to waste time writing a copy. But, now, you hold the original paper with the password, and you can do whatever you like with it (which can be useful, or not). This can be useful if you happen to change the password, then you can just erase the old password on the paper and replace it by the new one, and when you are finished, you hand the paper back to your friend and thus informing him of the new password. This is, however, not useful …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@awie10007
Yeah, I'm pretty sure the OP is talking about either a hobbyist's robot, or some research-grade robot (mobile, or manip, or other), or high-level control on industrial-grade robots (like feeding in joint-space trajectories in real-time to the controller). In which case, C++ is probably the best bet in terms of a suitable programming language. But, of course, for simple operation of industrial robots, there is no C/C++ involved, it's all proprietary CNC-like programming languages (i.e. a DSL) (like KRC/RSI for Kuka), but the capabilities are very limited (but totally sufficient for most of what is done in industrial automation).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Can you give me a few tips about that?
code, code, then code some more. Do it until your fingers or brains are numb (whichever occurs first), then rest, then repeat. Find a project you like, and get cracking. Make sure the project is within your grasp, but does challenge you (i.e. the perfect project is one that has high interest for you and for which you can already tell, roughly, how it should be done, but with several (big) holes, these are the parts from which you will learn the most). Program it incrementally, doing unit-testing will save you a world of trouble at debugging.

>>What books should I read
Read this thread.

>>what websites should I hang out
Daniweb! I guess you can also browse sourceforge for some project ideas and maybe join one, or build a project upon some existing open-source library. Open-source software is a great resource to expose you to both very well programmed software (e.g. Boost) and very poorly written code (e.g. like 90% or so of open-source software). Learning to deal with other peoples code and interfacing with external libraries is a crucial part of programming experience (i.e. learning to weight the cost of rolling your own code for something versus doing contortions to interface an external library, and being able to do so), and there are no books that can teach you that.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

C++ is the language of choice in Robotics. C is also needed very often when dealing with drivers or small micro-controllers that don't provide any better option.

As far as I know, Assembly is not needed in robotics. But you could encounter some domain-specific languages (DSL) depending on the application, and often they are extremely low-level (or very high-level, depending on how you look at it). For example, if you deal with industrial manipulators, then they usually are programmed with a DSL that allows simple point-to-point or path-following commands, they are inspired from CNC machine tools. But, typically, if you deal with such a system you can interface the controller with an external PC with DAQ card and you are free to program it which ever way you like, i.e., using C++.

If you look in the AI department, you will find a lot of stuff in Java (like the various agent-based software platforms). But when you look in the "running robots" department, it is overwhelmed with C++ code (ROS, CLARAty, MaCI, Player/Stage, and many others, including my own). That's the divide between academics and pragmatists.

Frankly, in robotics, the programming language should be the least of your worries to start from. You need to start by designing the system architecture in a language agnostic, hardware agnostic and OS agnostic manner. Then, find hardware that matches your design requirements. Evaluate your software choices and programming language choices, and select. Very often, the programming language will turn out …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I don't think this will always work. If you look at the synopsis of min_element, you will see that it starts by using the first element as the lowest one. If the first element has really small distance but does not satisfy the predicate, you will be in trouble. You could probably find the first element that satisfies the predicate and start the min_element from there. But, in this case, I think it is easier to just make your own version of min_element that finds the min_distance or something like that. It will also be less wasteful in terms of distance computations.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>don't want to use boost or AfxBeginThread().

Good luck. So, I'm guessing that if you don't want to use AfxBeginThread() which is just a thin wrapper around CreateThread, then you don't want to use CreateThread either. And if you don't want to use Boost.Thread, then you probably won't want to use any other library solution for multi-threading in C++, since Boost is by far the best, fastest, easiest and most robust implementation for multi-threading in C++ (in fact, it will become part of the C++ standard library before the end of this year, that's how good it is).

You have asked a question, but you also ruled out all the possible answers, from the lowest-level functions (i.e. CreateThread from the win32 API), to the most user-friendly high-level library solution (i.e. Boost). What do you expect?

The only other solution I can think of is a parallel processing solution, that is, OpenMP or Intel's TBB. But that can easily be overkill, and won't be very easy to use (it is professional stuff).

Maybe you should give more details as to why you reject Boost or AfxBeginThread, and what you are looking for in a solution for multi-threading.

>>Oh, and it works in /MD[d], /MD, MFX.
Don't worry about that, they all will work fine with those (if fact, you need /MD, it is not optional if you want to do multi-threading).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For Line 3 (the last param of the function), here is a detailed explanation:

First, consider the following simple statement:

Foo Bar::*attr;

This statement declares a pointer-to-data-member. In the above, it declares a pointer with name 'attr', which points to a data member of 'Bar' which is of type 'Foo'. Here are a few declarations of the same kind of syntax that you may be more familiar with:

//A function pointer:
int (*fptr)(int, double); //fptr points to a function taking (int,double) -> int.
//A function pointer type:
typedef int (*fptr_t)(int, double); //fptr_t is the type of functions pointers (int,double) -> int.
//A member-function pointer (or pointer-to-member-function):
//mfptr points to a function taking (int,double) -> int, and which is a non-static member of class MyClass:
int (MyClass::*mfptr)(int, double);
//similarly, as a type:
typedef int (MyClass::*mfptr_t)(int,double); //type of mfptr (above).

//then, a pointer-to-data-member:
int MyClass::*mdptr; //mdptr is a pointer to a member of MyClass, with type int.
//similarly for the type:
typedef int MyClass::*mdptr_t; //type of mdptr (above).

So, by substitution, in your example, attr is a pointer-to-data-member to a member of class std::iterator_traits<ForwardIter>::value_type , which is of type T.

Now, for the std::iterator_traits<ForwardIter>::value_type . I guess you understand that this will be the class that your iterators will dereference to (i.e. your Voice class). By now, you should also understand its place and function in the declaration of the pointer-to-data-member (see above). So, all that remains is the std::iterator_traits business. This is just the standard way, in …

luislupe commented: Great help, I wish you can have in double how much you helped me! +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Can I build such a template?

You cannot. The reason this is a problem (and the reason for the errors) is because your function template, when instantiated with int, has to compile, all of it has to compile, including the parts that will not be executed (i.e. parts which insert elements that are not of type T). The compiler tries to compile it but it can't.

There are a few options.

First, you can specialize the function template for each type. As so:

class Voice
{
  public:
    template <typename T>
    std::multiset<T> getAtribDim(const std::vector<Voice>& v, std::string attr);
    int air_time;				// 115
    double charged_amount;			// 864
    std::string id_cell;			// "cell a"
};

template <>
std::multiset<int> Voice::getAtribDim<int>(const std::vector<Voice>& v, std::string attr);
{
  std::multiset<int> satrib;		//multiset
  for (std::vector<Voice>::const_iterator ci = v.begin(); ci != v.end(); ++ci) {
    if (attr == "air_time") {
      satrib.insert(ci->air_time);		//int member name
    } else if(//... for any other int-type attributes..
  }
  return satrib;
}


template <>
std::multiset<std::string> Voice::getAtribDim<std::string>(const std::vector<Voice>& v, std::string attr);
{
  std::multiset<std::string> satrib;		//multiset
  for (std::vector<Voice>::const_iterator ci = v.begin(); ci != v.end(); ++ci) {
    if (attr == "id_cell") {
      satrib.insert(ci->id_cell);		//string member name
    } else if(//... for any other string-type attributes..
  }
  return satrib;
}

//similarly for double and whatever else you have.

When you "call" the function template, it will instantiate only the appropriate specialization, and won't have trouble compiling it because all your inserts are of consistent type.

The other solution, which I think is much better, is to use a pointer …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@AD>>..C++ programs are pretty much operating system specific.
What on Earth are you talking about? There are robust cross-platform libraries for everything in C++ (you just have to stay clear of anything that bares the name Microsoft or Apple). The amount of platforms you can target with platform-independent code in C++ far exceeds anything found with Java. Not to mention that massively multi-threaded or parallel programming in C++ has far more powerful frameworks and better speed (e.g. TBB, OpenMP, OpenCL, CUDA, and to some extent C++0x).

@OP:
I have to admit, I never really understood the need for frameworks specifically targeted for ABM. It's so trivial to implement from scratch in C++ (or any other proper language), when you have the proper skills. I have done it a few times. But I did look around a bit and found EcoLab that is free and seems reasonable. Not surprisingly, the code-base is small (25k lines of code) (as I said, it is pretty trivial to implement). My guess as to why there are vastly more Java implementations is because ABM is more of an academic topic and academics (even though I am one) seem to cling to toy-languages like Java (sorry for the ranting.. couldn't help it).

EcoLab: Seems pretty good, it's C++ and TLC, and seems fairly recently maintained (2010).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Oh.. sorry, you're right. You can't do a partial specialization of only a member function (but you can do a full specialization). This is one of those annoying C++ template rules ("The members of a class template partial specialization are unrelated to the members of the primary template").

I should have known, I just answered a question on SO about this specific problem. To avoid having to redefine all the member functions for each partial specialization, the solution, besides using a mixin pattern, is to use a Sfinae method. As such:

#include <iostream>
#include <boost/utility/enable_if.hpp>
#include <boost/config.hpp>

template <typename T>
struct is_int { BOOST_STATIC_CONSTANT(bool, value = false ); };

template <>
struct is_int<int> { BOOST_STATIC_CONSTANT(bool, value = true ); };

template <typename T, typename U>
struct Point {
  void function1() { };
  void function2() { function2_impl<U>(); };

  template <typename B>
  typename boost::enable_if< is_int<B>, void>::type function2_impl() {
    std::cout << "'int' partial specialization" << std::endl;
  };

  template <typename B>
  typename boost::disable_if< is_int<B>, void>::type function2_impl() {
    std::cout << "primary template" << std::endl;
  };
};

int main() {
  Point<float,float> a;
  Point<float,int> b;

  a.function2();
  b.function2();
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>so does this mean that I indeed must partially specialize EVERY class member?

Yes. What you are doing is specializing the entire class, it redefines it completely, so function2 does not exist in the partial specialization unless you redeclare it. But you can specialize the member only (here is a good article):

template<typename T, typename U>
class Point<T, U>
{
  void function1();
  void function2();
};

template<typename T, typename U>
void Point<T, U>::function1() { ... };

template<typename T, typename U>
void Point<T, U>::function2() { ... };

template<typename T>
void Point<T, int>::function1() { ... specialization ... };

PS. auto_ptr has been deprecated by unique_ptr.

daviddoria commented: As always, an excellent response! +5
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Where is the copy-constructor in your Mascota class? That's the piece missing, and what an important one!

I highly, highly recommend that you use std::string instead of char* and that you store the integer edad by value, not by pointer. Pointers are evil and you are suffering it right now.

If you choose to keep pointers, there are a few errors in your code. First, your assignment operator does not check for self-assignment (which will cause a seg-fault as it is now). You should add a if(this != &x) to check for self-assignment. Better yet, use the copy-and-swap idiom.

Finally, your Set() function does not delete the old pointers before you reallocate memory.

flowerzink commented: Helped me solve my problem +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes, that will allow for the call to happen, but there is still the question of valid data. The cast takes away the guarantee that the value will be correct. I guess that it depends on the situation which is more appropriate.

Sure. That's another reason why casts are not desirable. The OP could also define a custom conversion function:

enum color { red = 0, green = 1, blue = 2 };

color to_color(const std::string& s, color default_value = color::red) {
  int i;
  std::stringstream(s) >> i;
  if((i >= 0) && (i <= 2))
    return static_cast<color>(i);
  else
    return default_value;
};

But that puts overhead. It's a matter of choice really, safety or performance. There is no way to convert an int whose value is determined at run-time, to an enum type without having to make that choice.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, first of all, my recommendation would be to throw away that incredibly stupid library that does this. I can't comprehend how retarded somebody must be to think that making a #define with the name "thread" is not going to cause tremendous name-clashes.

Anyways, if you really have to use it, you can undefine the define after including the other library. As so:

#include "other_stupid_library.h"
#ifdef thread
#undef thread
#endif

#include <boost/thread/thread.hpp>

//....

That should solve your problem.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Normally, you do need to lock both the reader and writer such that their operations are mutually exclusing (with a mutex or critical section(windows), personally I would recommend Boost.Thread since it uses the best mechanisms for whatever OS you use). And, if you lock all read and write operations, then there is, of course, no issue with having multiple readers and multiple writers. But be careful not to introduce deadlocks. Also make sure you don't lock for more time than needed, because you can easily destroy performance (i.e. you end up with a number of threads lined-up, sleeping, when they could be doing useful work).

You probably also want to use a condition_variable to wake up the reader when a new element is available (in fact you can use the same mutex in the condition_variable). This is going to avoid needless decisions on how to poll for new elements to read (do you use a tight loop that repeatedly checks for new elements, or do you sleep X amount of time between checks). The condition_variable will allow you to put the reader thread to sleep until the queue has a new element.

Finally, if this is anywhere near to being a performance-sensitive implementation, then there are alternatives that allow you to avoid locking (almost) completely. This article presents a nice and simple lock-free queue implementation. Operating systems often rely on a form of RCU to have lock-free readers in a single-writer / multiple-readers problem.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The find function returns a const_iterator in the map, you have to check that it is valid and then output it, and you also have to deal with the fact that the iterator might be invalid if the element does not exist in the map.

const std::vector<passenger*>& passenger_queue::passengers_at_floor(int floor_) const
{
  std::map< std::vector<passenger*> >::const_iterator it = _waiting_passengers.find(floor_);
  if(it != _waiting_passengers.end())
    return *it;
  else
    return std::vector<passenger*>(); //or throw an exception.
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think that the easiest way to do it is to simply use a functor with both overloads. Something like this for example:

struct adaptSR_type {
  typedef int result_type;

  template<typename accStrategy>
  int const operator()(int const MAX_AL, float const CONFIDENT_LV, int const OFFSET, accStrategy PLAN)
  {
    return 1; 
  }

  int const operator()(int const MAX_AL, float const CONFIDENT_LV, int const OFFSET)
  {
    return 1;  
  }
} adaptSR;

template<typename T>
void testArg(T haha)
{
  int const MAX_AL = 10;
  float const CONFIDENT_LV = 10;
  int const OFFSET = 10;
  haha(MAX_AL, CONFIDENT_LV, OFFSET);
}

int main()
{
  float a = 3;
  testArg(boost::bind(adaptSR, _1, _2, _3) );
  testArg(boost::bind(adaptSR, _1, _2, _3, a) );
}

Of course, your template overloads have to be callable without explicit template arguments, so you need to make sure they can be deduced from the parameter types. And if you need to use explicit template arguments, you can simply make the functor a class template. I think that solution makes it a lot nicer on the user-side code.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Oh, that's right, if you use a std::map, the operator[] does not exist in the const form because if the index (or key value) does not exist, a new element will be created. So, for the const version, you need to use the find() function instead which will just find the element corresponding to a key (or an invalid iterator if the key does not exist).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

When the const is at the leftmost place, it is attached to the return value. In that = operator, it means that the function returns a const reference to itself.

When the const is at the rightmost place (after the parentheses), it is attached to the object to which to member function is called on (i.e. the this pointer). This means that the object and its data members cannot be modified in the body of the function.

The error you get is from the fact that when you have a const object, you can only call const member functions on it (with the const at the end), to guarantee that it will not be modified.

For the = operator, you cannot put it as const (at the end) because, by definition, the assignment operator will modify the data members within the function (i.e. to assign new values to them). Similarly, your [] operator is wrong. If you declare it const (at the end), you cannot return a non-const reference to one of its elements, so typically, it is implemented as follows:

const T& operator[] (int i) const   //takes a const "this" and returns a const ref.
    {
      return component[i];
    }
    T& operator[] (int i)      //takes a non-const "this" and return a non-const ref. 
    {
      return component[i];
    };

The difference between returning a const reference and a non-const reference in the case of the assignment operator is that if you return a non-const reference, the following would …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>they could be solve at compile times?

Well, it goes without saying that you have to turn on all the optimizations (-03), and hope for the best. Inspecting assembly listings (with option -S ) is the way to check it out (but you have to know assembly though..).


>>But according to the link at below, looks like this is not a common technique between those compiler vendors yet

Yes, of course, compilers don't support C++0x yet (it is not yet the standard after all). When it comes to early feature-full support, only GCC really matters. The other vendors are historically bad at keeping their compilers standard and feature-full. The only other exception is probably Comeau. I would guess that ICC won't take too long to comply either (especially for all the concurrent programming features). I would be surprised if the MSVC compiler gets to full compliance with C++0x by the time the next standard after that is coming out (circa 2016+), since only the 2010 version is of decent quality with respect to C++98.

I personally use GCC 4.6.0 experimental (that I compile from source on roughly a monthly basis), this guarantees as much C++0x support as possible and fast template meta-programming compilations. But otherwise, version 4.5.2 is pretty good too and is available on most platforms as binary distribution.

BTW, without variadic templates, you can still do the manual coding for each different number of arguments (up to maybe 10 or something …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think that a good old dictionary can give you a pretty good start: "auxiliary" and "helper" are synonyms in English. And, as far as I know, they are synonymous in programming terminology as well. "Utility functions" are similar in some sense but slightly different.

A "nonmember" function is obviously in opposition to a member function. A member function belongs to a class, i.e., tied to the class. By opposition, a nonmember function is not tied to a class, i.e., it is "free". So, "nonmember function" is a synonym of "free function". The only reason one might use the "nonmember" term is to emphasize the contrast to a member function, e.g., you might hear things like "this kind of operator should be a nonmember function" (to emphasize a case where it is better to define the function outside the class, when both are possible).

So, we are down to two main concepts: "free functions" and "helper functions". Are they the same? No. A helper function, as its name implies, is there to help, which means that it does not do something useful by itself, but rather helps another function to do something. Very often, especially with more complex algorithms, there are sub-problems that the algorithm solves many times in a loop and that sub-problem is not really useful to the user, but it is useful to a few other variants of the same algorithm. Then, that sub-problem can be put in a "helper function" to be used by …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>is there any additional overhead for the first case?
Yes, of course. In the first case, you needlessly create an instance of the Log class. And then, when you call the member function, the this pointer is implicitly passed as a first "hidden" parameter to the function, so that's a small additional overhead. In the second case, neither of those things happen and thus, it would be more efficient (not to mention that if createLog() does not need a Log object to work on, then, it is, semantically, more appropriate for createLog() to be a static function).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The non-copyable is implemented as follows:

private:
    building& operator= (const building& other); //notice & at return and no {}
    building (const building& other); //notice no {}

If the above triggers a compilation error, then it means that some part of your code (from where the error was triggered) does indeed do a copy of a building object, which is incorrect. I think you should post all the code for the building class. I'm sure the error will be obvious (to an experienced programmer).

fibbo commented: patient and very helpful. gave me some good tips. would instantly return the favor if i could! +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>On the >> issue, it did compile (used xcode and g++ via terminal - I'm on a mac atm).

It is possible that your compiler accepts this >> use. It's just that many compilers don't accept it currently. The upcoming standard will fix that little problem and require that compilers compile the >> correctly in this use-case. But the current standard prescribes that this should not compile (but since it is more of a little annoying syntax glitch in the standard, many compiler makers choose to ignore that requirement).

>>its just strange then that my compiler never said anything about it - or what am I missing?

The leading underscore (and double underscore anywhere) is clearly stated in the standard as being reserved for compiler-specific things. The reason why the compiler will not complain is because the compiler compiles all the code, without distinction of what code is from a standard library it provides (like #include <something>) and user-code. The standard reserves the leading underscore for things that are used/provided by compiler-specific implementations in its standard libraries.

>>Should I go and tell the professor/teaching assistant about the leading underscore?

Yes. You can refer them to section 17.4.3.1.2/1 of the C++98 Standard, which states:

C++98 Standard section 17.4.3.1.2/1: (Global names)
Certain sets of names and function signatures are always reserved to the implementation:
— Each name that contains a double underscore (_ _) or begins with an underscore followed …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>thinking about it made me come up with this. could this work?

Yes it does. (well, you are missing one closing parenthesis)

But, there is a better way. The problem with your implementation is that you are doing a lot of useless copying (you create a "large" vector and push it to the _assignments vector). You should try to favor pre-allocation whenever possible, like so:

_assignments.resize(number_of_floors); //preallocate for the number of floors
for (int i = 0; i<number_of_floors; ++i) {
  _assignments[i].resize(_number_of_rooms); //resize each vector to the number of rooms.
  for (int j = 0; j<number_of_rooms; ++j)
     _assignments[i][j] = NULL;           //you should also set everything to NULL.
}

Also, this line:

std::vector<std::vector<person*>> _assignments //this represents the building

Should not compile for two reasons. First, you are missing the semi-colon at the end of the line. Second, when you have nested < > declarations, you need to leave a space between the > > signs, otherwise, the compiler interprets those as the operator >>

One final and important note: It is forbidden, in C/C++, to use a leading underscore in an identifier or any occurrence of a double underscore. These special names are reserved for the compiler for special purposes and cannot be used by the programmer. So, you need to change your habit and get rid of the _ at the start of the names. You can use either nothing at the start, or an "m" for "data member" (I often also use a leading "a" …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This actually depends on the architecture of the processor. For x86 and x86_64, all primitive types of 64bits or less guarantee that read/write operations are atomic (meaning they cannot be interrupted half-way by a context switch). At least, it is a pretty safe assumption. You can also use CAS (Compare-and-swap) to ensure integrity. But, frankly, I think locks are overkill for primitive types. You can always use platform-specific atomicity functions and a CAS, and you should be pretty safe.

As for this little thread_safe_var, here is the working version I cooked up:

#include <iostream>
#include <boost/thread/thread.hpp>
#include <string>

template<typename T>
class lockable_var {
  mutable boost::mutex mut;
  T value;

  class const_lock_impl; //forward-decl
  class lock_impl {
    private:
      mutable boost::unique_lock<boost::mutex> l;
      T* ptr;
      lock_impl(const lock_impl& rhs) : l(), ptr(rhs.ptr) { l.swap(rhs.l); };
      lockable_var<T>::lock_impl& operator=(const lockable_var<T>::lock_impl&); //non-assignable. 
    public:
      friend class lockable_var<T>;
      friend class const_lock_impl;
      explicit lock_impl(lockable_var<T>& tsv) : l(tsv.mut), ptr(&tsv.value) { };
      operator T&() const { return *ptr; };
      T& value() const { return *ptr; };
      const lockable_var<T>::lock_impl& operator=(const T& val) const { *ptr = val; return *this; };
  };
  class const_lock_impl {
    private:
      mutable boost::unique_lock<boost::mutex> l;
      const T* ptr;
      const_lock_impl(const const_lock_impl& rhs) : l(), ptr(rhs.ptr) { l.swap(rhs.l); };
      lockable_var<T>::const_lock_impl& operator=(const lockable_var<T>::const_lock_impl&); //non-assignable. 
    public:
      friend class lockable_var<T>;
      explicit const_lock_impl(const lockable_var<T>& tsv) : l(tsv.mut), ptr(&tsv.value) { };
      const_lock_impl(const lock_impl& rhs) : l(), ptr(rhs.ptr) { l.swap(rhs.l); };
      operator const T&() const { return *ptr; };
      const T& value() const { return *ptr; };
  };
public:
  typedef const lock_impl& lock_type;
  lock_impl lock() { return lock_impl(*this); …
pseudorandom21 commented: +1 for excellence in daniweb-ness. +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is expected. That is exactly why the volatile keyword exists.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Do I need to protect the variable?
No. I'm guessing your sensitivity values are of a primitive type like double or int. All read-only operations are thread-safe, period (that is also valid for a non-primitive POD types). As for writing, storing a double or int value is essentially a single operation, I mean, at one clock cycle the value stored will be the previous value, and at the next clock cycle the value will have changed. Where can there be a thread-switch between the two that would cause the reading of an invalid value? That's why primitives are considered "lock-free thread-safe", because they are thread-safe without requiring a mutex lock (as far as I know, only primitives are like that, or near-primitives like smart-pointers).

The only case where it would matter is if you have a function that reads the value multiple times and expects it to be the same every time. In that case, just read it once into a local variable at the start of the function (or loop).

Mutex locking in multi-threaded software is only really needed when you have some data structure that has to go in a momentarily invalid state and might remain so for a little while. For example, resizing an array would usually involve resetting the "size" variable, then allocating a new array, copying the content, deleting the old array, and resetting pointer to its new location. The problem with this is that as soon as the size variable is …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The win32 API requires wide-char strings. You need to add a leading L in front of the literal string to tell the compiler to create a wide-char literal string:

windowClass.lpszClassName = L"WindowClass"; //notice the L in front.

And similarly for the other place where the error occurs.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, primitives are generally thread-safe just by the virtue of value-semantics and their primitive nature (as in, any read/write operation on them is atomic, i.e. it's extremely unlikely that a thread switch would occur in the middle of the operation, which is really where mutexes are required).

For larger classes, the thread-safety should really be implemented as part of the particular class. boost::shared_ptr are lock-free and thread-safe, like a primitive type, and dereferencing the underlying pointer is as thread-safe as the class of the object it's pointing to.

If you do want to implement this template you posted, may I suggest that you use more natural semantics instead of this ugly get/set:

template<typename var_type>
class ThreadSafeVariable {
  mutable boost::mutex mut;
  var_type value;
public:
  operator var_type() const {
    boost::mutex::scoped_lock(mut);
    return value;
  }
  ThreadSafeVariable<var_type>& operator =(const var_type& newValue){
    boost::mutex::scoped_lock(mut);
    value = newValue;
    return *this;
  }
};

This should allow you to basically substitute an object of type double for an object of type ThreadSafeVariable<double> without changing anything on the user-side (all arithmetic operations and what-not will be unchanged by trigger an implicit, thread-safe local copy of value to be used). Obviously, this will have a lot of overhead because lock and unlock mutexes is an expensive operation, so you will almost always be better off locking a mutex externally to avoid any repetitive locking and unlocking. To solve this, you can also use a mechanism similar to the weak_ptr/shared_ptr relationship. With weak_ptr/shared_ptr, the weak_ptr can only lock a shared_ptr …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>Do I need to pass it as arguments if I want to implement it by std::tr1::bind?

If the AnyFunctor needs arguments when called, you need to get those arguments from somewhere. So the idea, like in your last piece of code, to create some temporary variable with some arbitrary value and passing them to the function is kind of ridiculous (unless this is a concept-check, in which case, there are far better ways to do this). So, yes, you will need to pass those parameters to the testFunctor() function and then forward them to the functor call.

1 : if type anyFunctor need 3 arguments to initialize it, what should I do?
Do I have another way to make this become more adaptable except
of passing strategies like parameter(the way of stl did)

The way STL does it is pretty much the only scalable way to do this. You can also use the Boost.Lambda constructor/destructor templates to bind the constructor call with some parameters, but I doubt it will help much.


2 : if type anyFunctor need to accept different number of variables, how could I make it adaptable?

Just like std::tr1::bind did it (or as I would refer to it as Boost.Bind). With C++0x, the coming standard, the support for variadic templates will allow you to do this in one shot:

template <typename anyFunctor, typename... Args>
void testFunctor(Args... args) {
  anyFunctor f;
  f(args...);
}; //all of this …
StuXYZ commented: I learnt stuff, thanks +4
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

>>I am not clear as to what a seed is
I think the easiest way to think about it, from a beginner's perspective, is that, since a computer is deterministic (it can't actually produce truly random numbers), the best it can do is use a formula that produces "very wacky" results. In other words, the numbers generated by the formula make a very jumpy sequence of numbers where each number doesn't really seem (to the naked eye) as having anything to do with the previous one. But this is still a deterministic sequence, because if you start at the same place in the sequence, you will always get the same sequence of following numbers. The seed is, simply put, where you start in that sequence. And to get "random" number sequences, you need to start with a "random" seed. Since the exact time at which a program is started is pretty unpredictable and arbitrary, it's a fairly good "random" number to start with.


[edit]
for any comments that seem to be made without a previous post in this thread, see this discussion
[/edit]

@AD:>>Its up to you to disprove it.
No. You are claiming that all implementations of time() are the same, you have the burden of proof (a pretty heavy one too).

@Narue:>>I wouldn't recommend putting the ball in my court.
Well said!

Smartflight commented: Well explained! +1
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

AD is right, because of name-mangling in C++ (and ABI), you have to wrap all your C++ code into a C API (C functions). For example, say I wanted to "export" the following class from a DLL:

class Foo {
  private:
    double value;
  public:
    double GetValue() const { return value; };
    void SetValue(double NewValue) const { value = NewValue; };
};

My exported DLL functions could look like this:

typedef Foo* FOO_HDL;

extern "C" { 

__declspec(dllexport) FOO_HDL __stdcall FooCreate() {
  return new Foo();
};

__declspec(dllexport) void __stdcall FooDestroy(FOO_HDL obj) {
  delete obj;
};

__declspec(dllexport) double __stdcall FooGetValue(FOO_HDL obj) {
  return obj->GetValue();
};

__declspec(dllexport) void __stdcall FooSetValue(FOO_HDL obj, double NewValue) {
  obj->SetValue(NewValue);
};

};

But, to be really safe, you also need to make sure that no exceptions leave the DLL boundary. So, in theory, you would need to wrap all the bodies of all the exported functions with a catch-all clause, as such, for example:

void __stdcall FooSetValue(FOO_HDL obj, double NewValue) {
  try {
    obj->SetValue(NewValue); //if this operation throws an exception, it must not propagate further.
  } catch(...) {             //so, catch all exceptions.
    //do something.. or not.
  };
};

But, the above is a bit tedious and few people do it. If an exception occurs and you don't catch it before the boundary of the DLL is traversed back during stack unwinding, you will get a crash (in some case that's acceptable, in others, it is not).