【问题标题】:Is the template syntax in c++ just template <typename T>?c++ 中的模板语法只是模板 <typename T> 吗?
【发布时间】:2018-10-24 00:47:26
【问题描述】:

我正在努力理解这个Function passed as template argument。事实证明,在我读过的有关模板的某些地方,您可以这样声明它们:

template <typename MyTypeName>
class ...

现在是什么

template <void (*T)(int &)>

究竟是什么意思?这更像是一个关于 语法 的问题,而不是代码的作用。据我了解,它创建了一个接受函数指针的模板函数,并且该函数接收对整数的引用作为参数。

但是,我认为它不符合模板的语法。 typename 关键字在哪里?一般的模板语法是什么?

我找到的最接近的是:Why must we do template <class/typename> T instead of just template T。显然,您可以定义“常量”模板参数。所以我猜模板语法是这样的:

template <arguments>

参数可以是以下类型:typename Tint Nvoid T(int),等等。如果是这样,定义有什么好处

template <void (*T)(int &)>
void doOperation()
{
  int temp=0;
  T(temp);
  std::cout << "Result is " << temp << std::endl;
}

像这样,而不是这样做

void doOperation(void (*T)(int &))
{
  int temp=0;
  T(temp);
  std::cout << "Result is " << temp << std::endl;
}

?

【问题讨论】:

  • “非类型模板参数”
  • 对于您的最后一个问题,比较如果您在两个版本中添加一个 static 局部变量并使用至少两个不同的参数调用会发生什么。
  • 您很可能正在查看模板专业化。

标签: c++ templates


【解决方案1】:

c++中的模板语法只是template &lt;typename T&gt;吗?

没有。 template parameters一共有三种,

  • 非类型模板参数;
  • 类型模板参数;
  • 模板模板参数。

声明类型模板参数需要typename关键字,声明模板模板参数需要templatetypename关键字。给定template &lt;void (*T)(int &amp;)&gt;T 被声明为非类型模板参数(函数指针)。

关于为什么不直接使用void doOperation(void (*T)(int &amp;)),因为我们必须将T 声明为模板参数,否则它只是一个函数参数名称。

【讨论】:

  • 这可能都不是这些,而是​​一种专业化。
  • @SamVarshavchik 哪一个? template &lt;void (*T)(int &amp;)&gt; void doOperation() ?
猜你喜欢
  • 2013-04-05
  • 2022-01-04
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 2017-06-22
  • 1970-01-01
相关资源
最近更新 更多