c++ - 没有使用模板功能从 `int` 到 `float` 的自动转换

标签 c++ c++11 template-function

经过多年的 C++ 编码,今天我被问到一个简单的问题,但我确实找不到答案,所以我在这里。

除了想知道为什么会发生这个错误之外,我想知道如何我可以通过仅修改 模板函数(无需改变 main() 函数)

template <class T>
T Add(T first, T second)
{
    return first + second;
}

int main()
{
    auto sample_1 = Add(1, 2); // Works
    auto sample_2 = Add(1.f, 2.f); // Works
    auto sample_3 = Add(1.f, 2); // Error: no instance matches the argument types: (double, int)
    return 0;
}

最佳答案

Besides wondering why this error is happening,

当你调用 Add(1.f, 2) 时,第一个参数类型是 float,第二个参数类型是 int

编译器必须将第一个参数转换为 int 或将第二个参数转换为 float。由于它们都需要转换,因此它们同样是不错的候选者。一个不能优于另一个。

I want to know how I can solve below error by modifying just the template function

您可以将函数模板更改为:

template <class T1, class T2>
auto Add(T1 first, T2 second)
{
    return first + second;
}

或致(感谢@PiotrSkotnicki):

template <class T>
T Add(T first, decltype(first) second)
{
    return first + second;
}

在这种情况下,second 的类型不是从传递给函数的参数中推断出来的。 first 的类型是从第一个参数推导出来的,second 的类型被强制与 first 的类型相同。

Add(1.2f, 2);  // The first argument is deduced to be float
               // The second argument is forced to be float.

Add(2, 1.2f);  // The first argument is deduced to be int
               // The second argument is forced to be int.

关于c++ - 没有使用模板功能从 `int` 到 `float` 的自动转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32914496/

相关文章:

c++ - 如何在 C++ 中定义采用两个迭代器的模板函数?

c++ - 模板类类型特定的函数

c++ - 与 boost::python 的链接错误

c++ - 连接Broadcom设备解析云

c++11 - Emscripten C++ 11 标准库支持

boost - boost phoenix什么时候有用?

C++ STL 随机数生成返回相同的数字

c++ - 在 Rcpp 中使用 3rd 方头文件

python - numpy python openCv 重新映射

c++ - 从 C 文件调用模板函数