【问题标题】:Specilization of a member function of a templated class is not working模板类的成员函数的特化不起作用
【发布时间】:2016-05-29 11:10:48
【问题描述】:

我正在尝试为模板化 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%&lt;&gt;’ for ‘vec2&lt;int&gt; vec2&lt;int&gt;::operator%(int) const’ does not match any template declaration

  • 编译器不能使用默认模板参数来声明vec2 v1 并且需要模板参数

    error: missing template arguments before ‘v1’

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

如何解决?

【问题讨论】:

    标签: c++ templates template-specialization


    【解决方案1】:

    template&lt;&gt; template&lt;&gt; 试图将成员特化到另一个特化中。由于operator% 不是函数模板,因此您只需要一个template&lt;&gt; 即可表示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);
    

    【讨论】:

    • 只是好奇,构造函数参数不应该帮助编译器推断模板参数类型吗,double 在这种情况下?
    • @Samik 类模板参数永远不会从构造函数参数表达式中推导出来,它也与您的情况无关。正如我所说的vec2,是一个引用类模板的名称,而不是类型
    猜你喜欢
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2013-12-20
    相关资源
    最近更新 更多