uchar
uchar

Reputation: 2590

How to check if all of variadic template arguments have special function?

Explanation:

Checking if a special operator exist in a template parameter is easy (with help of this answer).

The following code checks if char operator[] exists in Type or not:

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

Problem:

Now I want to check if all of my variadic template parameters have that operator. I can't figure out how to send them one by one to HasStringOperator and check the whole result.

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

What should I do?

Upvotes: 8

Views: 1690

Answers (2)

Khurshid
Khurshid

Reputation: 2724

I want simplify @polkovnikov.ph's answer:

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 ... >{};

Upvotes: 4

polkovnikov.ph
polkovnikov.ph

Reputation: 6632

Just apply it to every type and compare it to an array of trues.

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");
};

Upvotes: 6

Related Questions