Is there a reason to use std::conjunction/std::disjunction instead of a fold expression over “&&”/“||”?

后端 未结 1 812
刺人心
刺人心 2021-02-01 16:39

Is there any specific cases you cannot correctly do with std::conjunction/std::disjunction and not using the more \"fundamental\" (i.e. language featur

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 17:09

    std::conjunction short-circuits ::value instantiation, while the fold expression doesn't. This means that, given:

    template  
    struct valid_except_void : std::false_type { };
    
    template <> 
    struct valid_except_void { };
    

    The following will compile:

    template 
    constexpr auto test = std::conjunction_v...>;
    
    constexpr auto inst = test;
    

    But the following won't:

    template 
    constexpr auto test = (valid_except_void::value && ...);
    
    constexpr auto inst = test;
    

    live example on godbolt.org


    From cppreference:

    Conjunction is short-circuiting: if there is a template type argument Bi with bool(Bi::value) == false, then instantiating conjunction::value does not require the instantiation of Bj::value for j > i.

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