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
. What I am trying to do now is to make 开发者_StackOverflowthe class also be able to use double through a template.
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.
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
? Preferably without mangling the struct
name and using 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":
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:
template <class T>
struct basic_vector {
...
};
typedef basic_vector<float> vector;
Unfortunately you have to write alg::vector<>
even if you have a default typename.
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. although single find and replace should do this.
精彩评论