我正在寻找一种在C++中易于快速描述的方法,用于检查一个值是否包含在其他一组固定值中。就像在Python中一样,可以写成
if some_function() in (2, 3, 5, 7, 11):
do_something()
一些明显的选项包括:
switch
/case
: If the values in question are integers, then one can write something like this:switch (some_function()) { case 2: case 3: case 5: case 7: case 11: do_something(); }
Unfortunately, this only works for integers, and I daresay it's not very pretty.
Use a local variable to keep the temporary result:
const auto x = some_function(); if (x == 2 || x == 3 || x == 5 || x == 7 || x == 11) do_something();
I would like to avoid the named temporary variable. Furthermore, this is tedious to write and error-prone.
Use
std::set
: This can be written (at least in C++20) as:if (std::set({ 2, 3, 5, 7, 11 }).contains(some_function())) do_something();
That's kinda nice, but I fear it has some heavy STL overhead.
还有其他更便宜的方法吗?也许一些可变参数模板的解决方案?