enable_if method specialization

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

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


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 20:52

    Use overloading instead of explicit specialization when you want to refine the behavior for a more specific parameter type. It's easier to use (less surprises) and more powerful

    template
    struct A
    {
        A operator%( const T& x) { 
          return opModIml(x, std::is_floating_point()); 
        }
    
        A opModImpl(T const& x, std::false_type) { /* ... */ }
        A opModImpl(T const& x, std::true_type) { /* ... */ }
    };
    

    An example that uses SFINAE (enable_if) as you seem to be curious

    template
    struct A
    {
        A operator%( const T& x) { 
          return opModIml(x); 
        }
    
        template::value>::type>
        A opModImpl(U const& x) { /* ... */ }
    
        template::value>::type>
        A opModImpl(U const& x) { /* ... */ }
    };
    

    Way more ugly of course. There's no reason to use enable_if here, I think. It's overkill.

提交回复
热议问题