Boost logo

Boost Users :

Subject: [Boost-users] static reflection
From: James Pritts (jbpritts_at_[hidden])
Date: 2008-09-17 21:26:22


On a boost thread a while ago, I saw some code to query for the
existence of a member function of a class using SFINAE and
BOOST_STATIC. I guess you could call it static reflection. Below is
a code snippet that does not work using the aforementioned methods.
The culprit is the using Base::operator() statement in the Derived
class. Apparently the base class method void operator()(float u) is
not part of the type of Derived. This was a shock to me, because you
can call the overloaded method from the derived class. I'd appreciate
any advice on how to check for the existence of member functions in
this scenario. I fear it may be impossible. Thanks!

#include <iostream>
#include <boost/shared_ptr.hpp>

typedef char (&no_tag)[1];
typedef char (&yes_tag)[2];

template <typename Class, typename R, typename Arg1, R(Class::*)(Arg1)>
struct HasExactSignature
{ };

template<typename Class, typename R, typename Arg1>
no_tag
doesVisitorImplementHelper(...);

template<typename Class, typename R, typename Arg1>
yes_tag
doesVisitorImplementHelper(HasExactSignature<Class, R, Arg1,
&Class::operator()>* p=0);

template<typename Class, typename R, typename Arg1>
struct DoesVisitorImplement
{
 BOOST_STATIC_CONSTANT(bool,
                       value =
sizeof(doesVisitorImplementHelper<Class,R,Arg1>(0)) ==
sizeof(yes_tag));
};

struct Base {
 void
 operator()(float u) {
   std::cout << "aaaa";
 }

};

struct Derived : public Base {
 using Base::operator();

 void
 operator()(int u) {
   std::cout << "bbbb";
 }
};

int main()
{
 std::cout << DoesVisitorImplement<Derived,void,int>::value << std::endl;
 std::cout << DoesVisitorImplement<Derived,void,float>::value << std::endl;

 return 0;
}


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