enable_if method specialization

前端 未结 3 757
栀梦
栀梦 2020-12-28 20:36
template
struct A
{
    A operator%( const T& x);
};

template
A A::operator%( const T& x ) {          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 21:09

    With C++20

    You can achieve that simply by adding requires to restrict the relevant template function:

    template // the generic case, no restriction
    A operator% ( const Q& right ) const {
        return A(std::fmod(x, right));
    }
    
    template requires std::is_integral_v && std::is_integral_v
    A operator% ( const Q& right ) const {
        return A(x % right);
    }
    

    The requires clause gets a constant expression that evaluates to true or false deciding thus whether to consider this method in the overload resolution, if the requires clause is true the method is preferred over another one that has no requires clause, as it is more specialized.

    Code: https://godbolt.org/z/SkuvR9

提交回复
热议问题