【问题标题】:How can I use template template type as an function argument?如何使用模板模板类型作为函数参数?
【发布时间】:2020-09-12 03:21:46
【问题描述】:

我要实现以下代码:

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);
}

但是,此代码无法编译。它说“错误:模板模板参数“Func”的参数列表丢失”。我不知道如何解决它。非常感谢!

【问题讨论】:

  • 不清楚你想要实现什么。模板模板可能不是你需要的。

标签: c++


【解决方案1】:

模板可以用作模板的参数,但不能用作函数的参数。因此错误;当您尝试使用模板名称 (Func) 作为函数参数的类型时,编译器抱怨模板名称本身是不够的。需要模板参数列表才能从模板中获取类型,然后才能成为函数参数的类型。

您似乎正在尝试将模板参数复制为函数参数。不要那样做。直接使用模板参数。

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);
}

但是,您的设置还有一个问题。正如typename 关键字所建议的,模板模板参数不能是函数模板。 所以这行不通。Can a template template parameter be of a variable or function?


另一种选择(由 OP 提出)可能是使用类模板和 operator()。需要注意的是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);
}

给定一个类模板f,这可以通过g&lt;f&gt;(0) 调用。

【讨论】:

  • 谢谢!如果我使用一个类并重载运算符(),上面的代码应该工作吗?
  • @zbh2047 有一些警告,但基本上是的。我已添加到我的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多