Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ methods which take templated classes as argument

Tags:

c++

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)

?

like image 606
Nils Avatar asked Dec 12 '22 22:12

Nils


2 Answers

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.

like image 93
Johannes Schaub - litb Avatar answered Jan 01 '23 19:01

Johannes Schaub - litb


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
}
like image 20
M. Williams Avatar answered Jan 01 '23 21:01

M. Williams