#include <iostream>
using namespace std;
template <class U>
U add (U a, U b)
{
U c = 0 ;
c = a + b;
return c;
}
int main()
{
int first = 2;
int second = 2;
U result = 0;
result = add(first, second);
cout << result << endl;
return 0;
}
我想使用模板数据类型声明结果变量的数据类型,以便我的加法程序是通用的,但编译器给我这个错误“结果未在此范围内声明。”
最佳答案
你想做的事是不可能的。您只能在 add 函数中使用 U。
但是,您可以改为这样做
auto result = add(first, second);
或者
decltype(auto) result = add(first, second);
在你的情况下,两者都会做同样的事情。然而,它们是完全不同的。简而言之,decltype(auto)
将始终为您提供 add
返回的确切类型,而 auto
可能不会。
简单示例:
const int& test()
{
static int c = 0;
return c;
}
// result type: int
auto result = test();
// result type: const int&
decltype(auto) result = test();
如果您想了解更多关于汽车的知识,Scott Meyers 完美地解释了它:
关于c++ - 如何在 C++ 的 main 函数中使用模板数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928624/