[英]How can I refactor my library to include templates?
我已经在整个项目中不使用模板的情况下尝试将模板功能添加到我的矢量类中。
旧版本使用硬编码的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
};
}
我希望现在可以通过告诉模板在未提供模板参数的情况下默认使用float
来编译我的项目,而无需更改其中的代码。
但是,我仍然会收到有关缺少模板参数的错误...
#include "vector.hpp"
int main() {
alg::vector a;
return 0;
}
-
$ 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’
如何在不更改test.cpp
情况下使此代码正常工作? 最好不要修改struct
名称并使用typedef
不幸的是,引用没有尖括号的类模板是非法的。
STL使用std::string
做到这一点的方式是这样的,即使您的请求是“无麻烦的”:
template <typename T> class basic_string { ... };
...
typedef basic_string<char> string;
对于您的情况,您将不得不在任何地方编写vector<>
或重命名模板:
template <class T>
struct basic_vector {
...
};
typedef basic_vector<float> vector;
不幸的是,即使您具有默认类型名,也必须编写alg::vector<>
。
以我的经验来看,你做不到。 您需要将alg::vector
更改为alg::vector<>
,这是默认参数的语法。 尽管单个查找和替换应该执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.