c++ - 模板参数推导错误

标签 c++ templates

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/

相关文章:

c++ - 为什么模板函数调用不明确?

c++ - 解决方案对命名空间/ADL 事物的标准一致性

c++ - 麻烦数词

c++ - 如何清理(析构函数)动态指针数组?

C++ 约束 enable_if 与 requires

C++检测类型是否具有模板参数

c++ - 根据模板参数选择函数名

c++ - QComboBox 信号未触发

C++ 传递对象的拷贝还是传递指向对象的指针?

c++ - 按位比较效率