如何以更 C++ 的方式重写它?
建议:为它制作一个可变参数模板函数,使其成为泛型(非仅用于int 值)并使其成为constexpr;这样你就可以检查集合中的值是否存在,编译时间。
您标记了 C++14,但我首先展示了 C++11 的递归方式,包括递归情况和基本情况
template <typename T>
constexpr bool is_in_list_11 (T const &)
{ return false; }
template <typename T, T t0, T ... ts>
constexpr bool is_in_list_11 (T const & t)
{ return (t == t0) || is_in_list_11<T, ts...>(t); }
从 C++14 开始,constexpr 函数可能要复杂得多,因此不再需要递归,您可以编写如下内容
template <typename T, T ... ts>
constexpr auto is_in_list_14 (T const & t)
{
using unused = bool[];
bool ret { false };
(void)unused { false, ret |= t == ts ... };
return ret;
}
从C++17开始你也可以使用auto模板类型和模板折叠,所以(就像user2079303之前展示的那样)函数变得非常简单
template <auto ... ts, typename T>
constexpr auto is_in_list_17 (T const & t)
{ return ( (t == ts) || ... ); }
以下是所有版本的完整工作示例
#include <iostream>
template <typename T>
constexpr bool is_in_list_11 (T const &)
{ return false; }
template <typename T, T t0, T ... ts>
constexpr bool is_in_list_11 (T const & t)
{ return (t == t0) || is_in_list_11<T, ts...>(t); }
template <typename T, T ... ts>
constexpr auto is_in_list_14 (T const & t)
{
using unused = bool[];
bool ret { false };
(void)unused { false, ret |= t == ts ... };
return ret;
}
template <auto ... ts, typename T>
constexpr auto is_in_list_17 (T const & t)
{ return ( (t == ts) || ... ); }
int main ()
{
constexpr auto b11a { is_in_list_11<int, 1, 3, 7, 42, 69, 5550123>(7) };
constexpr auto b11b { is_in_list_11<int, 1, 3, 7, 42, 69, 5550123>(8) };
constexpr auto b14a { is_in_list_14<int, 1, 3, 7, 42, 69, 5550123>(7) };
constexpr auto b14b { is_in_list_14<int, 1, 3, 7, 42, 69, 5550123>(8) };
constexpr auto b17a { is_in_list_17<1, 3, 7, 42, 69, 5550123>(7) };
constexpr auto b17b { is_in_list_17<1, 3, 7, 42, 69, 5550123>(8) };
std::cout << b11a << ' ' << b11b << std::endl;
std::cout << b14a << ' ' << b14b << std::endl;
std::cout << b17a << ' ' << b17b << std::endl;
}