2

我正在尝试将元函数专门用于具有函数指针作为其参数之一的类型。代码编译得很好,但它根本不匹配类型。

#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_。

4

1 回答 1

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根据其参数进行 readwrite-/readonly-tags 并field_writable有条件地派生,例如使用boost::mpl::if_.

于 2010-05-14T07:44:49.347 回答