我正在尝试将模板化函数传递给另一个函数,如下所示:
template<typename T = bool>
void fun() {}
template<typename F>
void higher_order_fun( const F & f) {
f();
}
int main () {
//higher_order_fun(fun<>); //works
higher_order_fun(fun);
}
在gcc10.2
我能够通过 fun
(模板原型(prototype))以同样的方式
作为指定类型 fun<>
.
请注意,如果我没有默认模板参数 T=bool,这将不起作用。
在Clang11
这行不通。
参见 https://godbolt.org/z/9WfMdc .
这是怎么回事?
最佳答案
以下所有标准引用均引用 N4659: March 2017 post-Kona working draft/C++17 DIS .
这可以说是一个 GCC 错误(/扩展功能),尽管我还没有找到它的票证。
根据 [temp.names]/1 ,您可以通过 template-id 引用模板特化。后者的语法不允许省略尖括号 <>
,即使其中的 template-argument-list 可能为空 (opt):
A template specialization can be referred to by a template-id:
simple-template-id: template-name < template-argument-list_opt > template-id: simple-template-id operator-function-id < template-argument-list_opt > literal-operator-id < template-argument-list_opt >
在您的情况下,您希望引用特化 fun<bool>
函数模板 fun
,这与您可以通过使用 fun
的单一类型模板参数的默认模板参数来引用相同的特化。 ,即 fun<>
.但是,您不能引用 fun<bool>
仅通过指定 fun
进行特化;后者不涉及特化,因此,您的程序格式错误。
关于c++ - 将函数模板原型(prototype)作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64872397/