开发者

C++ methods which take templated classes as argument

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 dimen开发者_如何转开发sions, 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
}


template <typename T, size_t N>
T find_step_size( const Vector<T,N>& v )
{
    return T(); // or something
}


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜