tags:

views:

122

answers:

4

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)

?

+12  A: 

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.

Johannes Schaub - litb
+1  A: 

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
}
Kotti
+1  A: 
template <typename T, size_t N>
T find_step_size( const Vector<T,N>& v )
{
    return T(); // or something
}
Nikolai N Fetissov
A: 

Your second question answer:

You can't have a templated pointer to function, that makes no sense. But what you can do is

#include <vector>

template <typename T>
void foo(const std::vector<T>& v) {
   // do something
}

void (*ptr_foo)(const std::vector<int>&) = &foo<int>;

(here the function pointers a templated function, which template argument is explicitly set to int)

Kotti