“Inverse SFINAE” to avoid ambiguous overload

前端 未结 2 862
野性不改
野性不改 2020-12-21 17:36

How can I prevent the first template below from instantiating if the second template instantiates? (i.e. if both static_cast(0) and T::zero()

2条回答
  •  再見小時候
    2020-12-21 18:19

    If you need to extend it to multiple overloads with fine grained control of overload rank, a common technique is to use tag dispatching.

    template
    struct rank : rank {};
    
    template<>
    struct rank<0> {};
    
    template
    auto zero_impl(rank<0>) -> decltype(static_cast(0)) {
        return static_cast(0);
    }
    
    template
    auto zero_impl(rank<1>) ->decltype(T::zero()) {
        return T::zero();
    }
    
    template
    auto zero() { return zero_impl(rank<10>{}); }
    

    Derived to base conversions will prefer the closest base class. Which translates to calling the overload with the highest rank. Since that one will have the best implicit conversion sequence in the eyes of the compiler.

提交回复
热议问题