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
178 views
in Technique[技术] by (71.8m points)

c++ - How can I check type T is among parameter pack Ts...?

I want to write a function to return true if T is one of Ts...

template<class T, class... Ts>
bool is_one_of<T, Ts...>();

For example, is_one_of<int, double, int, float> returns true, and is_one_of<int, double, std::string, bool, bool> returns false.

My own implementation is

template<class T1, class T2>
bool is_one_of<T1, T2>() {
    return std::is_same<T1, T2>;
}

template<class T1, class T2, class... Ts>
bool is_one_of<T1, T2, Ts...>() {
    if (std::is_same<T1, T2>) {
        return true;
    }
    else {
        return is_one_of<T1, Ts...>();
    }
}

This check seems common to me so I wonder if there's already such a function in the standard library.

question from:https://stackoverflow.com/questions/56720024/how-can-i-check-type-t-is-among-parameter-pack-ts

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

1 Answer

0 votes
by (71.8m points)

In your own implementation, one issue is that C++ doesn't allow partial specialization on function templates.

You can use the fold expression (which is introduced in C++17) instead of recursive function call.

template<class T1, class... Ts>
constexpr bool is_one_of() noexcept {
    return (std::is_same_v<T1, Ts> || ...);
}

If you are using C++11 where fold expression and std::disjunction are not available, you can implement is_one_of like this:

template<class...> struct is_one_of: std::false_type {};
template<class T1, class T2> struct is_one_of<T1, T2>: std::is_same<T1, T2> {};
template<class T1, class T2, class... Ts> struct is_one_of<T1, T2, Ts...>: std::conditional<std::is_same<T1, T2>::value, std::is_same<T1, T2>, is_one_of<T1, Ts...>>::type {};

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

...