Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class template deduction for a pointer to a datatype

I have the following wrapper 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 perfectly fine if I call it like:

Remap<double> remap(data, remap);

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

Remap remap(data, remap);

It fails with the error message:

argument list for class template "Remap" is missing

I try not to violate the DRY principle and thus like to fix this issue.

like image 865
schorsch312 Avatar asked Jan 19 '18 08:01

schorsch312


1 Answers

Before C++17 there is no deduction for class template arguments.

The workaround is to use some kind of get_remap template function which produces 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

Moreover, with C++14 support get_remap might be shortened to:

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

by letting the compiler to deduce a return type.


Since C++17 you might make use of class template argument deduction and simply write:

double* data = nullptr;
int* remap = nullptr;

Remap remap_obj(data, remap);

Example

like image 73
Edgar Rokjān Avatar answered Oct 24 '22 00:10

Edgar Rokjān