C ++ - methods that take template classes as an argument

I have a template class

Vector<class T, int N> 

Where T is the type of components (e.g. double) and n is 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 or higher dimensional vectors. Of course, I could just introduce additional methods for higher dimensions, but the methods will have a lot of redundant code, so I want a more general solution. Is there a way to create a method that accepts a template class without further specializing (in this case, without specifying T or N)? how

 double findStepsize(Vector<T,N> v) 

?

+4
source share
4 answers

Yes this

 template<typename T, int N> double findStepsize(Vector<T,N> v) {..} 

If you call it using a specific Vector<T, N> , the compiler outputs T and N to the appropriate values.

 Vector<int, 2> v; // ... fill ... findStepsize(v); /* works */ 

The above parameter-parameter corresponds to your example, but it is better to pass custom classes that must do the work in their copy constructors using the const link ( Vector<T, N> const& ). This way you avoid copies, but you cannot change the caller's argument.

+11
source

Implement it as follows:

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

Your second question:

You do not have a template pointer to a function, which does not make 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 indicates a template function whose template argument is explicitly set to int )

0
source

Source: https://habr.com/ru/post/1308159/


All Articles