Reputation: 1137
I want to declare a vector in my .h
file but depending on the precision of the data I send in I might want the vector to be of type double
or I might want it to be of type float
.
//tolerances.h
class verySimple{
public:
verySimple();
~verySimple();
void processTolerances(std::vector<double or float> tolerances);
};
Could I get a quick lesson, please? Thanks.
Upvotes: 0
Views: 129
Reputation: 66449
It isn't entirely clear what you want to accomplish, but judging by your example you want a function that can accept either float or double vectors.
You can overload functions in C++:
class verySimple{
public:
void processTolerances(std::vector<float> tolerances);
void processTolerances(std::vector<double> tolerances);
};
Then the appropriate one will be called depending on the argument.
Or, you can make the function a template:
template<typename T>
void processTolerances(std::vector<T> tolerances);
Or, if verySimple
as a whole depends on the type:
template<typename T>
class verySimple{
public:
void processTolerances(std::vector<T> tolerances);
};
Which way to choose depends on the natures of verySimple
and processTolerances
- there's no general "best solution".
Upvotes: 0
Reputation: 2491
And if you're new to templates get everything working with something that isn't a template (either float or double) before converting it to a template. Most compiler warnings and errors are less informative when templates are involved.
Upvotes: 0
Reputation: 16300
This is what template
is for.
You can say template <typename T> class verySimple
and then void processTolorances(std::vector<T> tolorances);
to do what you want.
You should check out a tutorial though as templates have a lot of gotchas for the uninitiated.
Upvotes: 4