Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

c++ - Check if a type is passed in variadic template parameter pack

I've heard somewhere, that using new C++1z syntax, it is really easy to check if a type is passed in variadic template parameter pack - apparently you can do this with code that is near one-line long. Is this true? What are those relevant features? (I tried looking through fold expressions but I can't see how to use them in that problem...)

Here's how I solved the problem in C++11 for reference:

#include <type_traits>


template<typename T, typename ...Ts>
struct contains;

template<typename T>
struct contains<T> {
    static constexpr bool value = false;
};

template<typename T1, typename T2, typename ...Ts>
struct contains<T1, T2, Ts...> {
    static constexpr bool value = std::is_same<T1, T2>::value ? true : contains<T1, Ts...>::value;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're looking for std::disjunction. It's specified in N4564 [meta.logical].

#include <type_traits>

template<typename T, typename... Ts>
constexpr bool contains()
{ return std::disjunction_v<std::is_same<T, Ts>...>; }

static_assert(    contains<int,      bool, char, int, long>());
static_assert(    contains<bool,     bool, char, int, long>());
static_assert(    contains<long,     bool, char, int, long>());
static_assert(not contains<unsigned, bool, char, int, long>());

Live demo


Or, adapted to a struct

template<typename T, typename... Ts>
struct contains : std::disjunction<std::is_same<T, Ts>...>
{};

Or, using fold expressions

template<typename T, typename... Ts>
struct contains : std::bool_constant<(std::is_same<T, Ts>{} || ...)>
{};

Live demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...