Violet Giraffe
Violet Giraffe

Reputation: 33589

Fold expression: iterate over variadic template type parameter to check compile-time conditions on the comprising types

The idea I have in mind is simple: in a variadic class template, I want to check some compile-time condition on the types. In this case, I want to find out if a certain type is in the pack or not. This is what the code might have looked like with C++17's fold expressions, but obviously that's not the valid syntax. How to implement this?

#include <type_traits>

template <class... Types>
struct TypesPack
{
    template <typename T>
    static constexpr bool hasType() {
        return std::is_same<T, Types>::value || ... || false;
    }
};

Upvotes: 2

Views: 2384

Answers (1)

Brian Bi
Brian Bi

Reputation: 119219

static constexpr bool hasType() {
    return (std::is_same<T, Types>::value || ...);
}

A fold-expression must be parenthesized, and you're allowed to omit the false when using || as the operator.

Upvotes: 10

Related Questions