Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;基本模板问题_C++_Templates_Specialization - Fatal编程技术网

C++ C++;基本模板问题

C++ C++;基本模板问题,c++,templates,specialization,C++,Templates,Specialization,我对模板专门化有点困惑 我有类Vector2,Vector3,其中包含运算符+=(定义如下) 现在我想添加一般的加法行为,并说: template <typename V> const V operator+(const V& v1, const V& v2) { return V(v1) += v2; } 在我看来,这很好,但不幸的是,将这两段代码放在一起会导致编译失败 (链接器显示错误LNK2005:“Vector2常量运算符+(Vector2常量和,Ve

我对模板专门化有点困惑

我有类
Vector2
Vector3
,其中包含
运算符+=
(定义如下)

现在我想添加一般的加法行为,并说:

template <typename V> const V operator+(const V& v1, const V& v2) {
   return V(v1) += v2;
}
在我看来,这很好,但不幸的是,将这两段代码放在一起会导致编译失败

(链接器显示错误
LNK2005:“Vector2常量运算符+(Vector2常量和,Vector2常量和)”(??$?HVVector2@core@lf@@@core@lf@@是吗?BVVector2@01@ABV201@0@Z) 已在中定义…

我的错误是什么?哪里出错了?


谢谢。

如果专业是在头文件中,那么您需要将其声明为
内联
,以允许它包含在多个编译单元中

请注意,在这里您实际上不需要模板专业化;一个简单的重载也会做同样的事情。

把这个

template<> const Vector2 operator+(const Vector2& v1, const Vector2& v2);
模板常量向量2运算符+(常量向量2和v1,常量向量2和v2);
标题中文件和

template<> const Vector2 operator+(const Vector2& v1, const Vector2& v2) {
   return Vector2(v1.x() + v2.x(), v1.y() + v2.y());
}
模板常量向量2运算符+(常量向量2和v1,常量向量2和v2){
返回向量2(v1.x()+v2.x(),v1.y()+v2.y());
}

.cpp文件中。

我不确定您是否要遵循该路径。您定义为模板的
运算符+
将匹配任何和所有类型,可能会产生冲突。为什么不为每个向量提供一个简单的非模板
操作符+

还有其他风格问题:

Vector2& operator+=(const Vector2& v) {
   x() += v.x(); // you don't need operator, here and it might
                 // be confusing if you don't have operator, priorities clear
   y() += v.y();
   return *this;
}
此外:


重载总是一个更好的选择。这可能比在头文件中内联定义它效率更低。
template<> const Vector2 operator+(const Vector2& v1, const Vector2& v2) {
   return Vector2(v1.x() + v2.x(), v1.y() + v2.y());
}
Vector2& operator+=(const Vector2& v) {
   x() += v.x(); // you don't need operator, here and it might
                 // be confusing if you don't have operator, priorities clear
   y() += v.y();
   return *this;
}
// This should not be a template!!!
template <typename V> const V operator+(V v1, const V& v2) {
   return v1 += v2;
}
struct non_sumable {};
int main() {
   non_sumable a,b;
   a + b;           // matches the template, tries to instantiate
                    // compiler error says that non_sumable does not 
                    // have operator+=, which might be confusing
}