如何检查所有可变参数模板参数是否具有特殊功能?

时间:2014-06-08 17:32:01

标签: c++ function templates c++11 variadic-templates

说明:

检查模板参数中是否存在特殊运算符很简单(借助此answer)。

以下代码检查char operator[]中是否存在Type

template <class Type>
class HasStringOperator
{
    template <typename T, T> struct TypeCheck;

    typedef char Yes;
    typedef long No;
    template <typename T> struct operator_{
        typedef char (T::*fptr)(int);
    };

    template <typename T> static Yes HasOperator(TypeCheck< typename operator_<T>::fptr, &T::operator[] >*);
    template <typename T> static No  HasOperator(...);

public:
    static bool const value = (sizeof(HasOperator<Type>(0)) == sizeof(Yes));
};

ideone

问题:

现在我想检查我的所有可变参数模板参数是否都有该运算符。我无法弄清楚如何将它们逐个发送到HasStringOperator并检查整个结果。

template < class... Word>
class Sentence
{
    static_assert(Do all of Words have 'char operator[]'?);
};

我该怎么办?

2 个答案:

答案 0 :(得分:6)

只需将其应用于每种类型,并将其与true s的数组进行比较。

template <bool... b>
struct BoolArray {};

template <class... TS>
struct DenyType : true_type {};

template <class... World>
class Sentence {
    static_assert(is_same<
        BoolArray<(HasStringOperator<World>::value)...>,
        BoolArray<(DenyType<World>::value)...>
    >::value, "WUT");
};

答案 1 :(得分:4)

我想要简化@ polkovnikov.ph的答案:

template< bool ... b> struct BoolArray{};
template< bool ... b> struct ctx_all_of: std::is_same< BoolArray<b...>, BoolArray<(b,true)...> >{};


template< class... World>
struct Sentence: ctx_all_of< HasStringOperator<World>::value ... >{};
相关问题