简体   繁体   English

如何使用enable_if作为具有特化的模板参数

[英]How to use enable_if as template parameter with specialization

Why the second function can't match the template in the class definition?? 为什么第二个函数不能匹配类定义中的模板?

    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
        }

EDIT: This is an overview of what I want to achieve. 编辑:这是我想要实现的概述。 Basically I'm writing a function to parse and return an object based on the template type. 基本上我正在编写一个函数来解析并返回一个基于模板类型的对象。 I have some defined classes of my own, that is I have to parse with respect to their members. 我有一些我自己定义的类,就是我必须对其成员进行解析。 I also need to parse numerical types and to strings. 我还需要解析数值类型和字符串。 So I wrote a specialized version for every of my defined classes. 所以我为每个定义的类编写了一个专用版本。 A version that parses to numerical types and return the given type (of course I have to make sure that the given type is numerical, hence the enable if) 一个解析为数字类型并返回给定类型的版本(当然我必须确保给定的类型是数字,因此启用if)

To utilize SFINAE, use it in the template declaration, not specialization: 要使用SFINAE,请在模板声明中使用它,而不是专门化:

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

If you want to differentiate between arithemtic and non-arithmetic types (allowing both), you can utilize tagging: 如果要区分arithemtic和非算术类型(允许两者),可以使用标记:

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;
};

Or delegate the specialization to a helper class: 或者将专门化委托给辅助类:

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);
};

EDIT: partial specializations ( bool parameter) do not work for methods, shown tagging and helper classes instead 编辑:部分特化( bool参数)不适用于方法,而是显示标记和辅助类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM