简体   繁体   English

如何重构我的库以包含模板?

[英]How can I refactor my library to include templates?

I am trying to add template functionality to my vector class, after already having used it without templates throughout my project. 我已经在整个项目中不使用模板的情况下尝试将模板功能添加到我的矢量类中。

The old version used hardcoded float to save the values for x , y and z . 旧版本使用硬编码的float来保存xyz What I am trying to do now is to make the class also be able to use double through a template. 我现在想做的是使类也可以通过模板使用double。

My class definition looks like this: 我的课程定义如下:

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
};

}

I was hoping to now be able to compile my project without making changes to the code in it, by telling the template to use float per default if no template parameter is given. 我希望现在可以通过告诉模板在未提供模板参数的情况下默认使用float来编译我的项目,而无需更改其中的代码。

However, I am still getting errors about missing template arguments... 但是,我仍然会收到有关缺少模板参数的错误...

#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’

How can I make this code work without changing test.cpp ? 如何在不更改test.cpp情况下使此代码正常工作? Preferably without mangling the struct name and using typedef 最好不要修改struct名称并使用typedef

Referring to a class template without angle brackets is illegal, unfortunately. 不幸的是,引用没有尖括号的类模板是非法的。

The way the STL does this with std::string is like this, even though your request was "no mangling": STL使用std::string做到这一点的方式是这样的,即使您的请求是“无麻烦的”:

template <typename T> class basic_string { ... };
...
typedef basic_string<char> string; 

In your case, you would have to write vector<> everywhere, or rename your template: 对于您的情况,您将不得不在任何地方编写vector<>或重命名模板:

template <class T>
struct basic_vector {
    ...
};

typedef basic_vector<float> vector;

不幸的是,即使您具有默认类型名,也必须编写alg::vector<>

in all of my experience you can't. 以我的经验来看,你做不到。 you need to change your alg::vector to alg::vector<> which is the syntax for the default argument. 您需要将alg::vector更改为alg::vector<> ,这是默认参数的语法。 although single find and replace should do this. 尽管单个查找和替换应该执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM