如何检查类型T是否在参数包Ts中?

时间:2019-06-23 00:00:18

标签: c++ variadic-templates

如果TTs...之一,我想编写一个返回true的函数

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

例如,is_one_of<int, double, int, float>返回true,而is_one_of<int, double, std::string, bool, bool>返回false

我自己的实现是

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...>();
    }
}

这种检查对我来说似乎很常见,所以我想知道标准库中是否已经有这样的功能。

4 个答案:

答案 0 :(得分:40)

在您自己的实现中,一个问题是C ++不允许对函数模板进行部分专业化。

您可以使用fold表达式(在C ++ 17中引入)而不是递归函数调用。

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

如果您使用的C ++ 11中没有折叠表达式和std::disjunction,则可以像这样实现is_one_of

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

答案 1 :(得分:30)

您也可以使用std::disjunction来避免不必要的模板实例化:

template <class T0, class... Ts>
constexpr bool is_one_of = std::disjunction_v<std::is_same<T0, Ts>...>;

找到匹配类型后,其余模板不会被实例化。相反,fold表达式将所有实例实例化。根据您的用例,这可能在编译时间上有很大的不同。

答案 2 :(得分:10)

检查类型T是否在参数包Ts中:

template<class T0, class... Ts>
constexpr bool is_one_of = (std::is_same<T0, Ts>{}||...);

模板变量。

替代:

template<class T0, class... Ts>
constexpr std::integral_constant<bool,(std::is_same<T0, Ts>{}||...)> is_one_of = {};

有细微的差别。

答案 3 :(得分:2)

其他答案显示了几种正确,简洁的方法来解决此特定问题。以下是不建议用于此特定问题的解决方案,但演示了一种替代技术:在constexpr函数中,您可以使用普通的循环和简单逻辑,以便在编译时计算结果。这样可以摆脱递归和尝试对OP代码进行部分模板专门化的过程。

#include <initializer_list>
#include <type_traits>

template<class T, class... Ts>
constexpr bool is_one_of() {
  bool ret = false;

  for(bool is_this_one : {std::is_same<T, Ts>::value...}) {
    ret |= is_this_one;// alternative style: `if(is_this_one) return true;`
  }

  return ret;
}

static_assert(is_one_of<int, double, int, float>(), "");
static_assert(!is_one_of<int, double, char, bool, bool>(), "");

至少需要 C ++ 14