c++ - 如何在 C++ 的 main 函数中使用模板数据类型?

标签 c++ templates typing

#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 完美地解释了它:

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

关于c++ - 如何在 C++ 的 main 函数中使用模板数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35928624/

相关文章:

c++ - 动态模板实例化

typescript - 如何在 typescript 2.0 中为 d3-tip 使用打字

c++ - DirectX 部分屏幕捕获

C# 按引用传递(ref 关键字)问题

c++ - 用于初始化引用的指针引用的值

c++ - CLR中 native 堆的内存管理

c++ - 在测试已声明但未定义的运算符是否存在时,static_assert 真的应该成功吗?

c++ - 优化 c++/gcc 中的模板编译时间

scala - 为什么 Scala 允许嵌套数据结构,如 List 或 Array

python - 打字,自定义集合类型