Hi,
in compl.lang.c++ I got the following answer to my problem:
--------------------------------------------------------------------
On Tue, 3 Sep 2002 17:21:00 +0200, "Julia Donawald"
wrote:
Hi,
I have the following code:
Calling the correct function with the entries in the map is no problem, but
how can I get the return value. I tried something like that:
"unsigned int i = functions["Function5"]();" but sadly it doesnt work,
maybe
cause in the map I declared for the return value "void"?
How can I have such a map where to have functions with different return
types in it and to get the return value after a call of the function
[snipped code]
through
the map?
Boost has another lovely library called "any". An "any" can hold any
time, with the unfortunate exception of void. Below is a partial
solution to your problem that will work with any function that returns
something other than void. (tested with gcc 3.2)
#include
#include
#include
#include <map>
#include <string>
#include <iostream>
class Foo {
public:
void Function3() const
{
int i =2;
};
const std::string Function4() const
{
return "Function4";
};
unsigned int Function5() const
{
return 2;
};
};
int main()
{
std::mapboost::any > functions;
Foo foo;
//functions["Function3"] = boost::bind(&Foo::Function3, &foo);
//void won't work :o(
functions["Function4"] = boost::bind(&Foo::Function4, &foo);
functions["Function5"] = boost::bind(&Foo::Function5, &foo);
// call the functions
std::string s;
try
{
//any_cast throws if you attempt a cast that isn't to the
//original type
s = boost::any_cast(functions["Function4"]());
std::cout << s << '\n';
}
catch(std::exception const& ex)
{
std::cerr << "Wasn't a string!\n";
}
std::cin.ignore();
}
As a final point, there isn't really a good reason to return a
cv-qualified object by value. Your const string return could be a
non-const return without any break in const correctness.
----------------------------------------------------------------
Sadly it doesnt work. At this position:
s = boost::any_cast(functions["Function4"]());
I always get an access violation..... any suggestions why?
Thanks in advance
Julia