谢谢你的问题,现在我找到了一个解决方案(我敢说是一个优雅的解决方案),我会自己使用它。
与使用 std::find 的解决方案不同:a ) 是否会在编译时展开到 N 次比较 b) 适用于 X 可以与之比较的任何类型
struct TagAnyOf {};
template <typename... Args>
std::tuple <TagAnyOf, Args...> AnyOf (Args&&... args)
{
return std::tuple <TagAnyOf, Args...> (TagAnyOf(), std::forward<Args>(args)...);
}
template <class X, class Tuple, size_t Index, size_t ReverseIndex>
struct CompareToTuple
{
static bool compare (const X& x, const Tuple& tuple)
{
return x == std::get<Index> (tuple) || CompareToTuple<X, Tuple, Index+1, ReverseIndex-1>::compare (x, tuple);
}
};
template <class X, class Tuple, size_t Index>
struct CompareToTuple <X, Tuple, Index, 0>
{
static bool compare (const X& x, const Tuple& tuple)
{
return false;
}
};
template <typename X, typename... Args>
bool operator == (const X& x, const std::tuple<TagAnyOf, Args...>& any)
{
typedef std::tuple <TagAnyOf, Args...> any_of_type;
return CompareToTuple <X, any_of_type, 1, std::tuple_size<any_of_type>::value-1>::compare (x, any);
}
用法
int main()
{
int x = 1;
if (x == AnyOf (1, 2, 3, 4))
{
std::cout << "Yes!" << std::endl;
}
else
{
std::cout << "No!" << std::endl;
}
if (x == AnyOf (4, 3, 2, 1))
{
std::cout << "Yes!" << std::endl;
}
else
{
std::cout << "No!" << std::endl;
}
if (x == AnyOf (2, 3, 4, 5))
{
std::cout << "Yes!" << std::endl;
}
else
{
std::cout << "No!" << std::endl;
}
return 0;
}