引用模板形参定义函数形参的类型

  • 本文关键字:形参 类型 函数 定义 引用 c++
  • 更新时间 :
  • 英文 :


我想这样做:

template <typename T, int Size>
struct config {
T field;
/* various other things */
}
template <typename C>  //  where C is a specific version of the 'config' object. 
void func(C arg0, C::T arg1, std::array<int, C::Size> &arg2) {
int i = C::Size;
}

即,我可以根据config的全类型来选择我的功能参数的类型吗?

我可以通过列出所有单独的类型来实现这一点:

template <typename T, int Size>
void func(config<T,Size> config, T arg1, std::array<int, Size> &arg2) { ... }

但是我的完整用例是获取相当大量的参数,包括编译时和运行时,我想把它们打包到我的配置对象中并传递它,而不必在几十个函数声明中复制许多模板定义。有办法做到这一点吗?

您当然可以为config添加类型别名/静态constexpr,但是保证函数的第一个参数是config的实例化的唯一方法是第二种选择。

使用类型别名/static const:

的解决方案
template <class T, int N>
struct config
{
using FieldType = T;
static constexpr int Size = N;
FieldType field;
};
template <typename C> 
void func(C arg0, typename C::FieldType arg1, std::array<int, C::Size> &arg2) {
int i = C::Size;
}