|
Boost : |
Subject: [boost] [any] Multimethod for boost::any
From: Nowake (nowake_at_[hidden])
Date: 2009-02-20 06:58:57
Hi,
I update Multimethod.
I make Multimethod::ApplyTraits to control method's dispatching.
https://svn.boost.org/trac/boost/attachment/ticket/2749/Multimethod.4.hpp
Samples:
______________________________________________________________________
struct Method10 { // MultiMethod
string operator()(const int a) const {
return string("int: "+lexical_cast<string>(a));
};
string operator()(const double a) const {
return string("double: "+lexical_cast<string>(a));
};
};
struct Method11 : public Method10 {};
struct Apply10 { // ApplyTraits to change int <-> double
template<typename A00>
string operator()(A00& a00, const double a01) {
return a00(static_cast<int>(a01));
};
template<typename A00>
string operator()(A00& a00, const int a01) {
return a00(static_cast<double>(a01));
};
};
// you can set ApplyTraits to each type combination.
// custom ApplyTraits
bool m10(Multimethod::entry<string, any, Method10, const int>(Apply10()));
bool m11(Multimethod::entry<string, any, Method10, const double>(Apply10()));
// use default ApplyTraits
bool m12(Multimethod::entry<string, any, Method11, const int>());
bool m13(Multimethod::entry<string, any, Method11, const double>());
BOOST_AUTO_TEST_CASE(test01) {
Method10 m10;
any mm(m10);
BOOST_CHECK_EQUAL(Multimethod::apply<string>(mm, 1), "double: 1");
BOOST_CHECK_EQUAL(Multimethod::apply<string>(mm, 1.0), "int: 1");
Method11 m11;
mm = m11;
BOOST_CHECK_EQUAL(Multimethod::apply<string>(mm, 1), "int: 1");
BOOST_CHECK_EQUAL(Multimethod::apply<string>(mm, 1.0), "double: 1");
}
// you can also use ApplyTraits to fit functions to multi methods.
struct Method00 { // MultiMethod
string operator()() const { return string("string()"); };
};
struct Apply00 { // ApplyTraits
template<typename A00>
shared_ptr<any> operator()(A00& a00) {
return shared_ptr<any>(new any(a00()));
};
};
// entry Method00::operator()() with ApplyTraits
bool m00(Multimethod::entry<shared_ptr<any>, any, Method00>(Apply00()));
BOOST_AUTO_TEST_CASE(test00) {
Method00 m;
any mm(m);
shared_ptr<any> r(Multimethod::apply<shared_ptr<any> >(mm));
BOOST_CHECK_EQUAL(any_cast<string>(*r), "string()");
}
_____________________________________________________________________
Regrads.
Nowake
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk