I have a templated class
Vector<class T, int N>
Where T is the type of the components (double for example) and n the number of components (so N=3 for a 3D vector)
Now I want to write a method like
double findStepsize(Vector<double,2> v)
{..}
I want to do this also for three and higher dimensional vectors. Of course I could just introduce further methods for higher dimensions, but the methods would have a lot of redundant code, so I want a more generic solution. Is there a way to create a method which takes a templated class without further specializing it (in this case without specifying T or N)? Like
double findStepsize(Vector<T,N> v)
?
Yes it is
template<typename T, int N>
double findStepsize(Vector<T,N> v)
{..}
If you call it with a specific Vector<T, N>
, the compiler will deduce T
and N
to the appropriate values.
Vector<int, 2> v;
// ... fill ...
findStepsize(v); /* works */
The above value-parameter matches your example, but it's better to pass user defined classes that need to do work in their copy constructors by const reference (Vector<T, N> const&
instead). So you avoid copies, but still can't change the caller's argument.
Implement it this way:
template <typename A, int B>
class Vector {
};
template <typename T, int N>
void foo(Vector<T, N>& v) {
}
template <>
void foo(Vector<int, 3>& v) {
// your specialization
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With