我試圖添加模板功能到我的矢量類,已經在整個我的項目中使用它沒有模板後。我如何重構我的圖書館以包含模板?
舊版本使用硬編碼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
這不是你的問題的答案,但你有沒有考慮過從'alg :: vector'到'alg :: vector'的直接搜索和替換? –