模板化类的成员函数的规范化不起作用
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;
}
我面临 2 个问题:
编译器找不到两个专用
%
运算符的任何匹配声明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 vec2<> vec2d;
vec2d v1(5.0, 12.0);
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 通过规范化 // 函数来调整数组
- 模板化类的成员函数的规范化不起作用