这有用吗?

时间:2010-05-13 17:16:53

标签: c++ templates template-meta-programming

我试图在一个函数指针作为其参数之一的类型上专门化一个元函数。代码编译得很好,但它与类型不匹配。

#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();
}

输出始终是传入的类型,绝不是bool _。

1 个答案:

答案 0 :(得分:3)

作为一种工作替代方案,没有评论中提到的转换问题:

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;

或者,metafield_fun也可以typedef读取 - / readonly-tags,具体取决于其参数,并field_writable有条件地推导,例如使用boost::mpl::if_