【问题标题】:How to use template data type inside main function in C++?如何在 C++ 的主函数中使用模板数据类型?
【发布时间】: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 的答案。

标签: c++ templates typing


【解决方案1】:

您尝试做的事情是不可能的。您只能在 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 完美解释:

CppCon 2014: Scott Meyers "Type Deduction and Why You Care"

【讨论】:

    【解决方案2】:

    José 出色提案的替代方案是:

    decltype(add(first, second)) result = 0;
    result = add(first, second);
    

    但是,显然,很糟糕。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2011-09-20
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多