Optimize Conditions

后端 未结 1 494
难免孤独
难免孤独 2020-12-19 21:05

I\'ve a simple question about conditions in if and for or while loops. Is there any way that lets me verify this condition with less l

相关标签:
1条回答
  • 2020-12-19 21:34

    You can write a lot less code, and make it more readable, if you have a function that does that for you:

    if (none_of( are_you_sure, "Si", "si", "No", "no"))
      // ...
    

    Of course, that function has to be written, but it's not too much code with c++17 fold-expressions:

    template<typename T, typename ...Opts>
    auto none_of(T val, Opts ...opts)
    {
        return (... && (val != opts));
    }  
    

    This has some nice properties; it can take any number of arguments, and also be used with types other than strings:

    int n = 42;
    if (none_of( n, 1, 2, 3))
      // ...
    

    Make sure to name the function well, as that affects readability a lot.

    0 讨论(0)
提交回复
热议问题