【发布时间】:2016-03-10 22:28:27
【问题描述】:
#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;
}
我想使用模板数据类型声明结果变量的数据类型,以便我的加法程序是通用的,但编译器给我这个错误“结果未在此范围内声明”。
【问题讨论】:
-
U是一个模板参数。它是模板函数的本地函数,在它之外没有任何意义。你希望从U result = 0;得到什么?您希望U在此行中成为什么类型?您应该将该行替换为int result = 0。 -
我想将函数返回的结果存储在这个变量中。如果函数返回 double,则此变量的类型应变为 double,如果返回 int,则结果变量的类型应变为 int。有可能吗?
-
合理的问题,但标题需要一些工作。不过我现在想不出一个好的替代品。
-
@AbdulMoizFarooq 然后使用 Jose 的答案。