我正在C中寻找一种简单,快速和描述性的方法来检查某个值是否包含在其他一组固定值中。就像在Python中一样,

if some_function() in (2, 3, 5, 7, 11):
    do_something()
一些明显的选择是:
  • switch/case:如果有问题的值是整数,则可以这样写:
    switch (some_function()) {
        case 2: case 3: case 5: case 7: case 11: do_something();
    }
    
    不幸的是,这仅适用于整数,我敢说它不是很漂亮。
  • 使用局部变量来保留临时结果:
    const auto x = some_function();
    if (x == 2 || x == 3 || x == 5 || x == 7 || x == 11) do_something();
    
    我想避免使用命名的临时变量。此外,这很麻烦编写并且容易出错。
  • 使用std::set:可以这样写(至少在C++ 20中):
    if (std::set({ 2, 3, 5, 7, 11 }).contains(some_function())) do_something();
    
    挺好的,但是我担心它有一些沉重的STL开销。

  • 还有其他更便宜的方法吗?也许一些可变参数的模板解决方案?

    最佳答案

    是的,您确实可以编写一个可变参数模板函数,并结合一个折叠表达式,如下所示:

    namespace my
    {
      template<typename T, typename ... Vals>
      bool any_of(T t, Vals ...vals)
      {
         return (... || (t == vals));
      }
    }
    
    然后像这样使用它:
    if (my::any_of(some_function(), 2, 3, 5, 7, 11))
    {
        do_something();
    }
    

    请注意,我已将any_of放在命名空间中,以避免与std::any_of完全不同的功能混淆。

    09-10 03:54
    查看更多