【发布时间】: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 T、int N、void 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局部变量并使用至少两个不同的参数调用会发生什么。 -
您很可能正在查看模板专业化。