为什么在这段C++代码中不能实例化模板?

YHS*_*SPY 5 c++

如题,为什么main函数中的模板实例化出错了?我使用带有标志“-std=c++2a”的 Clang++。我在这里以错误的方式使用了什么吗?

template<int, int>
void f(int) { std::cout << "int"; };

template<class T> 
void g() {  // dependent-name.
  f<0, T()>(0);
}

int main() {
  g<int>();  // wrong here, why?
}
Run Code Online (Sandbox Code Playgroud)

来自 Clang 的错误消息:

test.cc:41:3: error: no matching function for call to 'f'
  f<0, T()>(0);
  ^~~~~~~~~
test.cc:48:3: note: in instantiation of function template specialization 'g<int>' requested here
  g<int>(); // "int";
  ^
test.cc:35:6: note: candidate template ignored: invalid explicitly-specified argument for 2nd
      template parameter
void f(int) { std::cout << "int"; };
     ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

cig*_*ien 8

这个实例化:

f<0, T()>(0);
Run Code Online (Sandbox Code Playgroud)

forT=int给出int()第二个显式模板参数。这基本上是一个令人烦恼的解析,因此参数被视为函数类型。这与int对象不同,这是f对其模板参数的期望。

相反,您可以像这样实例化它:

f<0, T{}>(0);
Run Code Online (Sandbox Code Playgroud)

这样第二个模板参数是一个int对象。

这是一个演示