template <typename T>
void foo(int i)
{
//nothing inside
}
int main()
{
foo(5); //fails
foo<int>(5); //works
}
为什么 foo(5) 失败但 foo< int >(5) 有效?
最佳答案
你可能想写
template <typename T>
void foo(T i) // note the type of i
{
//nothing inside
}
更新
完整代码如下
#include <iostream>
using std::cout;
template <typename T>
void foo( T i ) {
cout << __PRETTY_FUNCTION__ << " called with " << i << "\n";
}
int main() {
foo( 5 );
foo<int>( 7 );
}
和输出:
void foo(T) [with T = int] called with 5
void foo(T) [with T = int] called with 7
关于c++ - 模板参数推导错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3846653/