c++ - 如何使用enable_if作为专门化的模板参数

标签 c++ templates

为什么第二个函数无法匹配类定义中的模板?

    Class C {        
            template <typename T, typename T2 = T>
            T val() const;
        };

        template <>
        std::string C::val() const { 
             //OK
        }

        template <typename T, typename std::enable_if<std::is_arithmetic<T>::value>::type>
        T C::val() const {
            //Not OK
        }

编辑: 这是我想要实现的目标的概述。基本上我正在编写一个函数来根据模板类型解析并返回对象。我有一些自己定义的类,也就是说我必须解析它们的成员。我还需要解析数字类型和字符串。因此,我为每个定义的类编写了一个专门的版本。解析为数字类型并返回给定类型的版本(当然我必须确保给定类型是数字,因此启用 if)

最佳答案

要利用 SFINAE,请在模板声明中使用它,而不是专门化:

class C {
    template <typename T, typename T2 = typename std::enable_if<std::is_arithmetic<T>::value>::type>
    T val() const;
};

如果您想区分算术类型和非算术类型(允许两者),您可以使用标记:

class C {
public:
    struct arithmetic_tag {};
    struct non_arithmetic_tag {};

    template <typename T>
    T val(typename std::conditional<std::is_arithmetic<T>::value, arithmetic_tag, non_arithmetic_tag>::type tag = {}) const
    {
        return get_val<T>(tag);
    }

private:
    template <typename T>
    T get_val(C::non_arithmetic_tag) const;

    template <typename T>
    T get_val(C::arithmetic_tag) const;
};

或者将专门化委托(delegate)给辅助类:

class C {
public:
    template <typename T>
    T val() const
    {
        return ValGetter<T>::get(this);
    }

private:
    template <typename T, bool is_arithmetic = std::is_arithmetic<T>::value>
    struct ValGetter;
};

// Arithmetic
template <typename T>
struct C::ValGetter<T, true>
{
    static T get(C const* c);
};

// Non-arithmetic
template <typename T>
struct C::ValGetter<T, false>
{
    static T get(C const* c);
};

编辑:部分特化(bool 参数)不适用于方法,而是显示标记和辅助类

关于c++ - 如何使用enable_if作为专门化的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36598054/

相关文章:

c++ - 确保 VS 2008 将我的项目视为 C++ 而不是 C++/CLI

javascript - polymer 、模板不会评估 true 和绑定(bind)

c++ - 为模板特化提供*隐式*转换运算符

c++ - 计算斐波那契数的模板元编程

c++ - 作为模板参数传递的函数

c++ - 我收到错误 c++ assertion failure heap corruption detected

c++ - 将已经围绕另一个枢轴变换的 GL 对象的枢轴居中?

c++ - QListView项目具有复选框选择行为

c# - C++ 比 C# 快多少?

c++ - `typename` 参数化模板和整数类型模板之间的差异