|
Boost Users : |
From: Julia Donawald (yg-boost-users_at_[hidden])
Date: 2002-09-03 12:00:04
Hi,
in compl.lang.c++ I got the following answer to my problem:
--------------------------------------------------------------------
On Tue, 3 Sep 2002 17:21:00 +0200, "Julia Donawald"
<julia.donawald_at_[hidden]> wrote:
>Hi,
>I have the following code:
[snipped 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
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 <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/any.hpp>
#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::map<std::string, boost::function<boost::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<std::string
const>(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<std::string const>(functions["Function4"]());
I always get an access violation..... any suggestions why?
Thanks in advance
Julia
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net