【发布时间】:2021-01-24 10:04:57
【问题描述】:
我对 c++ 很陌生,但想尝试做一些花哨的模板。我不确定这是否可能,但我相当有信心有办法实现这一目标。
所以问题来了: 我正在调用各种硬件函数,这些函数需要多个参数,并且只有一种参数类型不同:
int Read(HANDLE handle, int location, char* Name, int startindex1, int endindex1,
int startindex2, int endindex2, int* rval, Astruct* callback) ;
int Read(HANDLE handle, int location, char* Name, int startindex1, int endindex1,
int startindex2, int endindex2, double* rval, Astruct* callback) ;
硬件接口根据索引的值返回一个标量、数组或矩阵。我真正想要实现的是一个函数,它根据我传递的参数数量返回T 或vector<T> 或vector<vector<T>>。:
T MyReadFunction<T>(HANDLE handle, int location, char* Name,int index)
vector<T> MyReadFunction<T>(HANDLE handle, int location, char* Name,int startindex1,
int endindex1 )
vector<vector<T>> MyReadFunction<T>(HANDLE handle, int location, char* Name,int startindex1,
int endindex1
int startindex2,
int endindex2)
其中T 是基本类型,如int、real、float、double 等。
使用 3 个具有专业化的不同模板没有问题,但我很想以某种方式将它们结合起来。
我的假设是,这可以使用模板专业化来实现,但我无法理解它。我想我应该是这样的:
template<typename T ,int... Indexes>
T MyReadFunction (HANDLE handle, int location, char* Name, Indexes... myIndex){}
template<>
int MyReadFunction (HANDLE handle, int location, char* Name, int myindex)
{
int rval = 0;
Read (handle,location,name,myindex,myindey,0,0,&rval, NULL) ;
return rval;
}
这是一个两头野兽。我大概需要明确地实现我的 3 个案例以避免误用,但也想知道,我如何根据参数包的大小来实现模板专业化,参数包的大小不同。
我在 VS 2019 中使用最新的 msvc++
【问题讨论】:
标签: c++ template-specialization parameter-pack