[英]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 *
. 其中数据的类型为
double *
。 If I try to let the compiler (intel icc 15.0.3, with -std=c++11) deduce the template type: 如果我试图让编译器(intel icc 15.0.3,-std = c ++ 11)推导出模板类型:
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. 我尽量不违反DRY原则,因此想解决这个问题。
Before C++17 there is no deduction for class template arguments. 在C ++ 17之前,没有类模板参数的推论。
The workaround is to use some kind of get_remap
template function which produces Remap
objects: 解决方法是使用某种
get_remap
产生模板函数Remap
对象:
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);
Moreover, with C++14 support get_remap
might be shortened to: 此外,使用C ++ 14支持,
get_remap
可能会缩短为:
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: 从C ++ 17开始,您可以使用类模板参数推导并简单地写:
double* data = nullptr;
int* remap = nullptr;
Remap remap_obj(data, remap);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.