c++ - 模板化类的成员函数的特化不起作用

标签 c++ templates template-specialization

我正在尝试为模板化 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;
}

我面临两个问题:

  • 编译器无法为两个专门的 % 找到任何匹配的声明运算符

    error: template-id ‘operator%<>’ for ‘vec2<int> vec2<int>::operator%(int) const’ does not match any template declaration

  • 编译器无法使用默认模板参数来声明 vec2 v1并期望它的模板参数

    error: missing template arguments before ‘v1’

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

如何解决?

最佳答案

template<> template<>是尝试将成员专门化到另一个特化中。自 operator%不是函数模板,你只需要一个template<>表示 vec2 的完全特化,例如:

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

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

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

或者为它创建一个 typedef:

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

关于c++ - 模板化类的成员函数的特化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509157/

相关文章:

C++ 链表使用智能指针

c++ - 检查类是否在继承层次结构中明确定义成员类型

c++ - 使用 &front() 修改 std::string 中的底层字符数组

c++ - gdb 7.0 警告 : Wrong size fpregset in core file

c++ - 奇怪的链接错误

基类的c++模板特化

c++ - Template 模板方法的特化

c++ - 模板特化 VS 函数重载

c++ - 为什么这个三角形重新排序算法会导致随机连接?

c++ - Boost signals.hpp 在 Visual Studio 2010 上导致多个编译时错误