如何在 C++ 的 main 函数中使用模板数据类型?
How to use template data type inside main function in C++?
#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;
}
我想使用模板数据类型声明结果变量的数据类型,以便我的加法程序是通用的,但编译器给我这个错误 "result was not declared in this scope."
你想做的事是不可能的。您只能在添加函数中使用 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 完美解释:
José 的优秀建议的替代方案是:
decltype(add(first, second)) result = 0;
result = add(first, second);
但是,显然,讨厌。
#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;
}
我想使用模板数据类型声明结果变量的数据类型,以便我的加法程序是通用的,但编译器给我这个错误 "result was not declared in this scope."
你想做的事是不可能的。您只能在添加函数中使用 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 完美解释:
José 的优秀建议的替代方案是:
decltype(add(first, second)) result = 0;
result = add(first, second);
但是,显然,讨厌。