Boost logo

Boost :

Subject: Re: [boost] [any] Multimethod for boost::any
From: Nowake (nowake_at_[hidden])
Date: 2009-02-18 10:06:44


Hi everyone.

I update Multimethod to enhance flexibility of return value.
https://svn.boost.org/trac/boost/attachment/ticket/2749/Multimethod.3.hpp

Now, I can modify return value without changing the function objects.
______________________________________________________________________
// Multimethod's return value's traits
// specialize template class in shared_ptr<any> (return type)
template<>
struct Multimethod::ReturnTraits<shared_ptr<any> > {
   template<typename from_t>
   static shared_ptr<any> result(from_t& value) {
      return shared_ptr<any>(new any(value));
   };
   template<typename from_t>
   static shared_ptr<any> result(const from_t& value) {
      return shared_ptr<any>(new any(value));
   };
   // specialize template function in shared_ptr<any>
   // If target function object's return value is shared_ptr<any>,
   // Multimethod::apply returns value directly.
   template<>
   static shared_ptr<any>
   result<shared_ptr<any> >(shared_ptr<any>& value) {
      return value;
   };
   template<>
   static shared_ptr<any>
   result<shared_ptr<any> >(const shared_ptr<any>& value) {
      return value;
   };
};

struct TestAnyMethod0 { // Multi method
   string operator()() const { return string("string()"); };
   string operator()(int value) const { return string("string(int)"); };
   shared_ptr<any> operator()(double value) const {
      return shared_ptr<any>(
            new any(string("shared_ptr<any>(string(double))")));
   };
};
bool m00(Multimethod::entry<shared_ptr<any>, any, TestAnyMethod0>());
bool m01(Multimethod::entry<shared_ptr<any>, any, TestAnyMethod0, int>());
bool m02(Multimethod::entry<shared_ptr<any>, any, TestAnyMethod0, double>());

TestAnyMethod0 m;
any mm(m);

// Multimethod::apply fits TestAnyMethod0's return value
// to shared_ptr<any> using Multimethod::ReturnTraits::result.
shared_ptr<any> r(Multimethod::apply<shared_ptr<any> >(mm));
BOOST_CHECK_EQUAL(any_cast<string>(*r), "string()");

any a0(0);
r = Multimethod::apply<shared_ptr<any> >(mm, a0);
BOOST_CHECK_EQUAL(any_cast<string>(*r), "string(int)");

any a1(0.0);
r = Multimethod::apply<shared_ptr<any> >(mm, a1);
BOOST_CHECK_EQUAL(any_cast<string>(*r), "shared_ptr<any>(string(double))");
// r's content is not shared_ptr<any>.
// Multimethod::apply return shared_ptr<any> directly.
______________________________________________________________________

Regards.
Nowake


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk