C++ Variadic template AND and OR

前端 未结 2 1530
孤独总比滥情好
孤独总比滥情好 2021-01-02 11:01

Can you use C++11 variadic templates to complete /* ??? */ in:

template struct var_and { static bool constexpr value = /* ??? */         


        
相关标签:
2条回答
  • 2021-01-02 11:32

    I just needed something similar, but I have the luxury of using C++14, so I've ended up going with the following, which is probably faster (to compile) than the accepted answer:

    template <size_t N>
    constexpr bool and_all(const bool (&bs) [N]) {
      for(bool b: bs) if(!b) return false;
      return true;
    }
    

    Now, this is constexpr, so it can be used in compile time contexts as well as runtime. So we can, for instance, use it in a context like some_struct<and_all({true, false, arg_pack...})>

    0 讨论(0)
  • 2021-01-02 11:50

    You don't want value to be a typedef.

    template<bool head, bool... tail>
    struct var_and {
        static constexpr bool value = head && var_and<tail...>::value;
    };
    
    template<bool b> struct var_and<b> {
        static constexpr bool value = b;
    };
    

    Obviously the same can be done for ||.

    Short circuit evaluation doesn't matter because this only deals with constant expressions which won't have any side effects.

    Here's another method which stops recursively generating types as soon as it find a false value, emulating a kind of short circuiting:

    template<bool head, bool... tail>
    struct var_and { static constexpr bool value = false; };
    
    template<bool... tail> struct var_and<true,tail...> {
        static constexpr bool value = var_and<tail...>::value;
    };
    
    template<> struct var_and<true> {
        static constexpr bool value = true;
    };
    

    Update for C++17: Using a fold expression makes this much simpler.

    template<bool...v> struct var_and {
        static constexpr bool value = (v && ...);
    };
    

    Or also using a template variable as enobayram suggests:

    template<bool... b> constexpr bool var_and = (b && ...);
    
    0 讨论(0)
提交回复
热议问题