[英]How can I use template template type as an function argument?
I want to implement the following code:我想实现以下代码:
template <int i>
void f() {
...
}
template <template <int i> typename Func>
void g(Func func, int i) {
if (i == 0) func<0>();
else if (i == 1) func<1>();
else if (i == 2) func<2>();
else assert(false);
}
int main() {
g(f, 0);
}
However, this code can not be compiled.但是,此代码无法编译。 It says "error: argument list for template template parameter "Func" is missing".
它说“错误:缺少模板模板参数“Func”的参数列表”。 I don't know how to fix it.
我不知道如何修复它。 Thank you very much!
非常感谢!
Templates can be used as arguments to templates, but they cannot be used as arguments to functions.模板可以用作模板的参数,但不能用作函数的参数。 Hence the error;
因此错误; when you tried to use a template name (
Func
) as the type of a function parameter, the compiler complained that a template name by itself is not enough.当您尝试使用模板名称 (
Func
) 作为函数参数的类型时,编译器会抱怨模板名称本身是不够的。 A template argument list is needed to get a type out of the template, and only then can it be the type of a function parameter.从模板中获取类型需要模板参数列表,只有这样它才能成为函数参数的类型。
It looks like you are trying to replicate the template parameter as a function parameter.看起来您正在尝试将模板参数复制为函数参数。 Don't do that.
不要那样做。 Use the template parameter directly.
直接使用模板参数。
template <template<int> typename Func>
void g(int i) {
if (i == 0) Func<0>();
else if (i == 1) Func<1>();
else if (i == 2) Func<2>();
else assert(false);
}
However, there is a further problem with your setup.但是,您的设置还有一个问题。 As suggested by the
typename
keyword, a template template argument cannot be a function template.正如
typename
关键字所建议的那样,模板模板参数不能是函数模板。 So this does not work.所以这是行不通的。 See Can a template template parameter be of a variable or function?
请参阅模板模板参数可以是变量还是函数?
An alternative (brought up by the OP) might be to use a class template and operator()
.另一种选择(由 OP 提出)可能是使用类模板和
operator()
。 One caveat is that operator()
cannot be static, so there is another syntactical change to g
.一个警告是
operator()
不能是静态的,因此g
有另一种语法变化。
template <template<int> typename Func>
void g(int i) {
if (i == 0) Func<0>{}(); // <
else if (i == 1) Func<1>{}(); // < -- Invoke operator() on a temporary
else if (i == 2) Func<2>{}(); // <
else assert(false);
}
Given a class template f
, this could be invoked via g<f>(0)
.给定一个类模板
f
,这可以通过g<f>(0)
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.