模板化 class 的成员函数的特化不起作用

Specilization of a member function of a templated class is not working

我正在尝试为模板化 struct 的成员运算符定义特化,如下所示:

template<typename T = double>
struct vec2 {
    T x, y;

    vec2(const T x,
         const T y)
    : x{x}, y{y} {}

    vec2(const T w)
    : vec2(w, w) {}

    vec2()
    : vec2(static_cast<T>(0)) {}

    friend ostream& operator<<(ostream& os, const vec2& v) {
        os << "vec2<" << v.x << ", " << v.y << ">";
        return os;
    }

    vec2<T> operator%(const T f) const;
};

template<> template<>
vec2<int> vec2<int>::operator%(const int f) const {
    return vec2(x % f, y % f);
}

template<> template<>
vec2<double> vec2<double>::operator%(const double f) const{
    return vec2(std::fmod(x, f), std::fmod(y, f));
}

int main() {
    vec2 v1(5.0, 12.0);
    vec2<int> v2(5, 12);
    cout << v1 % 1.5 << v2 % 2 << endl;
    return 0;
}

我面临两个问题:

现在这些不是 struct vec2 的完全专业化吗?所以我也应该能够专门化成员函数吗?

如何解决?

template<> template<> 是在另一个专业化中对成员进行专业化的尝试。由于 operator% 不是函数模板,因此您只需要一个 template<> 来表示 vec2 的完全特化,例如:

template <>
vec2<int> vec2<int>::operator%(const int f) const
{
    return vec2(x % f, y % f);
}

vec2 是一个 class 模板,不是类型。为了从默认模板参数的 class 模板创建类型,您需要一对空括号:

vec2<> v1(5.0, 12.0);
// ~^^~ 

或者为它创建一个 typedef:

typedef vec2<> vec2d;
vec2d v1(5.0, 12.0);