将boost :: mpl :: find_if与自定义谓词一起使用

时间:2017-06-23 12:49:27

标签: c++ typetraits boost-mpl

鉴于

struct A {};
struct B {};
struct C {C(B) {}};
struct D : B {};
struct E {operator A() const {return A();}};
struct F {};

using AllowedTypes = boost::mpl::vector<A, C>;

我正在尝试实现谓词is_allowed_type,以便

static_assert(is_allowed_type<A>::value, "A is in AllowedTypes");
static_assert(is_allowed_type<B>::value, "C is constructible from B");
static_assert(is_allowed_type<C>::value, "C is in AllowedTypes");
static_assert(is_allowed_type<D>::value, "D inherits from B, from which C is constructible");
static_assert(is_allowed_type<E>::value, "E is convertible to A");
static_assert(!is_allowed_type<F>::value, "F is not convertible to A nor C");

如果谓词的参数可转换为AllowedTypes中的某个类型,则谓词必须返回true。

以下是我的想法。

template <typename T>
struct is_allowed_type
{
    using I = boost::mpl::find_if<AllowedTypes, std::is_convertible<T, boost::mpl::_>>;
    using End = boost::mpl::end<AllowedTypes>;
    enum {value = !std::is_same<I, End>::value};
};

最后一个断言失败了。我的is_allowed_type有什么问题?

1 个答案:

答案 0 :(得分:1)

我在写这个问题时找到了答案,但由于我很难找到关于这个主题的材料我发布了。

is_allowed_type中的迭代器定义缺失::type。正确的实施是

template <typename T>
struct is_allowed_type
{
    using I = typename boost::mpl::find_if<AllowedTypes, std::is_convertible<T, boost::mpl::_>>::type;
    using End = typename boost::mpl::end<AllowedTypes>::type;
    enum {value = !std::is_same<I, End>::value};
};
相关问题