Class template output for data type pointer

I have the following shell class:

template <typename T> class Remap { public: Remap(T *data, int *remap) : data(data), remap(remap){}; T &operator[](std::size_t idx) const { return data[remap[idx]]; } private: T *data; int *remap; }; 

It works fine if I call it:

 Remap<double> remap(data, remap); 

where the data is of type double * . If I try to let the compiler (intel icc 15.0.3, with -std = C ++ 11) infer the type of the template:

 Remap remap(data, remap); 

Error with error message:

argument list for class template "Remap" is missing

I try not to violate the DRY principle and, therefore, would like to fix this problem.

+7
c ++ c ++ 11 templates c ++ 14 type-deduction
source share
1 answer

Prior to C ++ 17, there were no deductions for class template arguments.

A workaround is to use some kind of get_remap template function that creates Remap objects:

 template<typename T> Remap<T> get_remap(T* data, int* remap) { return Remap<T>(data, remap); } 

and then use it like:

 double* data = nullptr; int* remap = nullptr; auto remap_obj = get_remap(data, remap); 

Example

In addition, C ++ 14 get_remap can be reduced to:

 template<typename T> auto get_remap(T* data, int* remap) { return Remap<T>(data, remap); } 

letting the compiler infer the return type.


With C ++ 17, you can use the output of the template template argument and simply write:

 double* data = nullptr; int* remap = nullptr; Remap remap_obj(data, remap); 

Example

+10
source share

All Articles