views:

190

answers:

1
+2  Q: 

Should this work?

I am trying to specialize a metafunction upon a type that has a function pointer as one of its parameters. The code compiles just fine but it will simply not match the type.

#include <iostream>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/identity.hpp>

template < typename CONT, typename NAME, typename TYPE, TYPE (CONT::*getter)() const, void (CONT::*setter)(TYPE const&) >
struct metafield_fun {};

struct test_field {};

struct test
{
  int testing() const { return 5; }
  void testing(int const&) {}
};

template < typename T >
struct field_writable : boost::mpl::identity<T> {};

template < typename CONT, typename NAME, typename TYPE, TYPE (CONT::*getter)() const >
struct field_writable< metafield_fun<CONT,NAME,TYPE,getter,0> > : boost::mpl::false_
{};

typedef metafield_fun<test, test_field, int, &test::testing, 0> unwritable;

int main()
{
  std::cout << typeid(field_writable<unwritable>::type).name() << std::endl;

  std::cin.get();
}

Output is always the type passed in, never bool_.

+2  A: 

As a working alternative without the conversion problems mentioned in the comments:

struct rw_tag {};
struct ro_tag {};

template<typename CONT, typename NAME, typename TYPE,
         TYPE (CONT::*getter)() const, void (CONT::*setter)(TYPE const&)>
struct metafield_fun_rw : rw_tag {};

template<typename CONT, typename NAME, typename TYPE,
         TYPE (CONT::*getter)() const>
struct metafield_fun_ro : ro_tag {};

template<class T> struct field_writable 
  : boost::mpl::bool_< boost::is_base_of<rw_tag, T>::value >
// or just derive directly from: boost::is_base_of<rw_tag, T>::value
{};

typedef metafield_fun_ro<test, test_field, int, &test::testing> unwritable;

Alternatively metafield_fun could also typedef readwrite-/readonly-tags depending on its arguments and field_writable derive conditionally, say using boost::mpl::if_.

Georg Fritzsche
Yeah, this will obviously work. I should have been more careful a month ago when I just tried passing 0 to the setter to see if it worked the first time I wanted to use that feature. I had planned on making ro metafields but hadn't gotten to it and didn't want to modify a stable package if I could help it.
Noah Roberts