C++ 如何重构库以包含模板?
在我的项目中已经使用过vector类,但没有使用模板,我正在尝试将模板功能添加到vector类中 旧版本使用硬编码浮点来保存x、y和z的值。我现在试图做的是使类也能够通过模板使用double 我的类定义如下所示:C++ 如何重构库以包含模板?,c++,templates,C++,Templates,在我的项目中已经使用过vector类,但没有使用模板,我正在尝试将模板功能添加到vector类中 旧版本使用硬编码浮点来保存x、y和z的值。我现在试图做的是使类也能够通过模板使用double 我的类定义如下所示: namespace alg { template <class T=float> // <- note the default type specification struct vector { T x, y, z; vector() : x(0)
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
};
}
-
如何在不更改test.cpp的情况下使此代码正常工作?最好不要弄乱结构名并使用typedef,不幸的是,即使您有默认的typename,您也必须编写alg::vector。根据我的经验,您不能这样做。您需要将alg::vector更改为alg::vector,这是默认参数的语法。尽管单次查找和替换可以做到这一点。不幸的是,引用没有尖括号的类模板是非法的 STL使用std::string执行此操作的方式如下,即使您的请求没有损坏:
template <typename T> class basic_string { ... };
...
typedef basic_string<char> string;
在您的情况下,您必须在任何地方写入向量,或者重命名
模板:
template <class T>
struct basic_vector {
...
};
typedef basic_vector<float> vector;
这不是你问题的答案,但是你考虑过从alg::vector到alg::vector的直接搜索和替换吗?谢谢你的快速回复和很好的示例。我想没有别的办法了,我认为代码的最上面一行应该是模板类basic_string{…};
template <typename T> class basic_string { ... };
...
typedef basic_string<char> string;
template <class T>
struct basic_vector {
...
};
typedef basic_vector<float> vector;