gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:18:31 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com