我试图在我的矢量类中添加模板功能,之后在我的项目中使用它而没有模板.
旧版本使用硬编码float来保存值x,y和z.我现在要做的是让类也能够通过模板使用double.
我的类定义如下所示:
namespace alg {
template <class T=float> // <- note the default type specification
struct vector
{
T x, y, z;
vector() : x(0), y(0), z(0) {}
explicit vector(T f) : x(f), y(f), z(f) {}
vector(T x, T y, T z) : x(x), y(y), z(z) {}
// etc
};
}
Run Code Online (Sandbox Code Playgroud)
我希望现在能够编译我的项目而不更改其中的代码,通过告诉模板float默认情况下使用,如果没有给出模板参数.
但是,我仍然遇到有关缺少模板参数的错误...
#include "vector.hpp"
int main() {
alg::vector a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
-
$ g++ -O3 -Wall -Wextra -std=gnu++0x test.cpp
test.cpp: In function ‘int main()’:
test.cpp:4:17: error: missing template arguments before ‘a’
test.cpp:4:17: error: expected ‘;’ before ‘a’
Run Code Online (Sandbox Code Playgroud)
如何在不更改的情况下使此代码正常工作test.cpp?最好不要破坏struct名称和使用typedef
不幸的是,引用没有尖括号的类模板是非法的.
STL执行此操作的方式std::string是这样的,即使您的请求是"没有损坏":
template <typename T> class basic_string { ... };
...
typedef basic_string<char> string;
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您必须在vector<>任何地方写,或重命名您的模板:
template <class T>
struct basic_vector {
...
};
typedef basic_vector<float> vector;
Run Code Online (Sandbox Code Playgroud)