enable_if方法专业化 [英] enable_if method specialization

查看:121
本文介绍了enable_if方法专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

template<typename T>
struct A
{
    A<T> operator%( const T& x);
};

template<typename T>
A<T> A<T>::operator%( const T& x ) { ... }

我如何使用enable_if作如下分工发生任何浮点类型(is_floating_point)?

How can I use enable_if to make the following specialization happen for any floating point type (is_floating_point)?

template<>
A<float> A<float>::operator%( const float& x ) { ... }

编辑:
以下是我想出了一个答案是从下面贴的有所不同...

Here's an answer I came up which is different from the ones posted below...

template<typename T>
struct A
{
    T x;

    A( const T& _x ) : x(_x) {}

    template<typename Q>
    typename std::enable_if<std::is_same<Q, T>::value && std::is_floating_point<Q>::value, A<T> >::type operator% ( const Q& right ) const
    {
        return A<T>(fmod(x, right));
    }

    template<typename Q>
    typename std::enable_if<std::is_convertible<Q, T>::value && !std::is_floating_point<Q>::value, A<T> >::type operator% ( const Q& right ) const
    {
        return A<T>(x%right);
    }
};

像下面的海报说,使用enable_if可能不适合这个问题很理想(这是非常难读)

Like the below posters say, using enable_if may not be ideal for this problem (it's very difficult to read)

推荐答案

使用超载而不是明确的分工时,要细化行为更具体的参数类型。它更容易使用(不惊喜)和更强大的

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<typename T>
struct A
{
    A<T> operator%( const T& x) { 
      return opModIml(x, std::is_floating_point<T>()); 
    }

    A<T> opModImpl(T const& x, std::false_type) { /* ... */ }
    A<T> opModImpl(T const& x, std::true_type) { /* ... */ }
};

使用SFINAE一个例子( enable_if ),你似乎很好奇。

template<typename T>
struct A
{
    A<T> operator%( const T& x) { 
      return opModIml(x); 
    }

    template<typename U, 
             typename = typename 
               std::enable_if<!std::is_floating_point<U>::value>::type>
    A<T> opModImpl(U const& x) { /* ... */ }

    template<typename U, 
             typename = typename 
               std::enable_if<std::is_floating_point<U>::value>::type>
    A<T> opModImpl(U const& x) { /* ... */ }
};

之路更丑,当然。没有理由使用 enable_if 在这里,我想。这是矫枉过正。

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

这篇关于enable_if方法专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆