下面代码中单个模板参数的类型和默认值是什么?
template<auto = {}>
int getInt();
用
-Xclang -ast-dump
发出叮叮声只表示:
| |-NonTypeTemplateParmDecl 0xcb77130 <line:1:10, col:18> col:15 'auto' depth 0 index 0
| | `-TemplateArgument expr
| | `-InitListExpr 0xcb77050 <col:17, col:18> 'void'
没有。
这不是一个语法错误(实际上我不确定),但这并不意味着它是一个有意义的模板声明。尝试实例化它,clang 会变得更健谈:
int main() {
getInt<>();
}
结果:
<source>:5:5: error: no matching function for call to 'getInt'
5 | getInt<>();
| ^~~~~~~~
<source>:2:5: note: candidate template ignored: substitution failure: non-type template parameter '' with type 'auto' has incompatible initializer of type 'void'
1 | template<auto = {}>
| ~
2 | int getInt();
| ^
不过,我们必须对错误消息持保留态度。
{}
没有类型,甚至 void
也没有。 {}
可用于初始化,但要使其起作用,必须知道类型。 auto
或一般类型推导不能从 {}
推导出类型。