这个C ++模板代码出错的原因是什么?

时间:2011-03-13 10:09:23

标签: c++

此代码导致编译时错误:

#include <iostream>
#include <vector>
#include <cmath>

template <unsigned short n>
class Vector {
    public:
        std::vector<float> coords;

        Vector();
        Vector(std::vector<float> crds);


        float distanceFrom(Vector<n> v);

        template <unsigned short m>
        friend std::ostream& operator <<(std::ostream& out, const Vector<m>& v);
};



    template <unsigned short n>
Vector<n>(vector<float> crds) {  // HERE IS ERRRO

}

编译错误:

C:\CodeBlocks\kool\praks3\vector.h|29|error: expected ')' before '<' token|
||=== Build finished: 1 errors, 0 warnings ===|

5 个答案:

答案 0 :(得分:8)

以下是如何在类外定义构造函数的方法:

template <unsigned short n>
Vector<n>::Vector(std::vector<float> crds) {
//also notice this ^^^^                 
}

答案 1 :(得分:4)

template <unsigned short n>
Vector<n>::Vector(vector<float> crds) {
}

编辑:正如其他人所说,如果你不是using namespace std;,你还需要std::vector<float>

答案 2 :(得分:0)

您可能会错过vector<float>中的std ::前缀。

答案 3 :(得分:0)

Vector :: Vector(构造函数args) 你只是忘了构造函数的范围

答案 4 :(得分:0)

应该这样吗?

template <> Vector<unsigned short>::Vector(Vector<float> crds) 
{
    // BLAH
}

在我看来,你对模板专业化感到困惑。