模板返回类型函数如何在C++中工作

How does template return type function work in C++?

本文关键字:C++ 工作 返回类型 函数      更新时间:2023-10-16

在下面的示例中:

template<typename T>
T Get()
{
    T t = 10;
    return t;
}
int main()
{
    int i = Get<int>(); // will work
    float f = Get<float>(); // will work
}

函数重载不适用于不同的返回类型。那么,在这种情况下,编译器最终会生成什么?

当你通过Get<int>Get<double>调用函数时,编译器不需要推导返回类型。代码T t = 10将执行强制转换操作以键入 T 。如果将10替换为非整数,例如1.5,则这一点更清楚:

template<typename T>
T Get()
{
    T t = 1.5;
    return t;
}
main()
{
    int i = Get<int>(); // returns 1
    double f = Get<double>(); // returns 1.5
}

但是,对于某些编译器,此代码确实会生成警告

warning: implicit conversion from 'double' to 'int' changes value from 1.5 to 1 [-Wliteral-conversion]

在这种情况下,T t = static_cast<T>(1.5);可能是更好的选择。