class 方法的模板特化。 "Function template already defined"

Template Specialization of class method. "Function template already defined"

我已经看到很多关于方法上下文专业化的 SO 问题,但不是属于 classes 的函数。我很难将这些问题传递的知识转化为我这里的问题。

我正在研究我过去创建的 class 来学习,我想专攻算术类型。

template <typename T>
class Vector3
{
public:
    T x;
    T y;
    T z;

public:
    operator std::string() const;
}

这是我想做的专业:

template<typename T = std::enable_if<std::is_arithmetic<T>::value, T>::type>
inline Vector3<T>::operator std::string() const {

    std::stringstream ss;
    ss << "NOT NUMBER {" << x << ", " << y << ", " << z << "}";

    return ss.str();
}

template<typename T = std::enable_if<!std::is_arithmetic<T>::value, T>::type>
inline Vector3<T>::operator std::string() const {

    std::stringstream ss;
    ss << "NUMBER {" << x << ", " << y << ", " << z << "}";

    return ss.str();
}

但是当我尝试编译时,我得到

error C2995: 'Vector3::operator std::string(void) const': function template has already been defined

当我google这个时,通常情况下人们已经在CPP文件和头文件中定义了他们的class/method。因为我只在头文件中这样做,所以我只能假设 enable_if 不正确。当我查看其他示例时,他们只是对 , 进行专业化,但我想使用 is_arithmitic 方式。

我做错了什么?提前致谢

此处默认:

template<typename T = XXX>
inline Vector3<T>::operator std::string() const { ... }

根本没关系,此时没有推导,T已经定义好了。这是合法的,但这只是噪音。

现在,您也不能在 class 模板中部分特化成员函数,但我们可以根据特征分派:

template <class T>
class Vector3 {
public:
    // ...
    operator std::string() const {
        return as_string(std::is_arithmetic<T>{});
    }

private:
    std::string as_string(std::true_type ) {
        // implementation for arithmetic types
    }

    std::string as_string(std::false_type ) {
        // implementation for non-arithmetic types
    }
};

Barry 的回答很完美。

这里有一些解释和建议:

http://en.cppreference.com/w/cpp/types/enable_if

"A common mistake is to declare two function templates that differ only in their default template arguments. This is illegal because default template arguments are not part of function template's signature, and declaring two different function templates with the same signature is illegal."