【发布时间】:2021-06-27 11:55:38
【问题描述】:
为什么同时使用 auto 和 decltype。不能自动解决目的?? 这个程序的输出是什么 有人可以举例说明如何在模板中使用 auto 和 decltype
template <class A, class B>
auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
return (a < b) ? a : b;
}
// driver function to test various inference
int main()
{
// This call returns 3.44 of doubale type
cout << findMin(4, 3.44) << endl;
// This call returns 3 of double type
cout << findMin(5.4, 3) << endl;
return 0;
}
【问题讨论】:
-
你有没有机会阅读decltype vs auto?
-
在 C++14 中引入了自动返回类型检测。在您的示例中,尾随返回类型
-> decltype(a < b ? a : b)在 C++11 中是必需的,并且从 C++14 开始是可选的。 -
它在两种情况下都返回 double 。为什么,,为什么不只自动
-
auto不是类型,它是声明语法元素。decltype(something)是一种类型。如果你需要写下一个表达式的类型,你不能使用auto,你只能使用decltype。这一切都在decltype vs auto问题中进行了解释。 -
因为如果您在非模板代码中编写相同的表达式,则表达式的结果是
double。有时不是int,否则不是double。 C++ 不能以这种方式工作。给定表达式的类型始终相同。
标签: c++ c++11 c++14 auto decltype