【问题标题】:decltype and auto feature in C++11C++11 中的 decltype 和 auto 功能
【发布时间】: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 中引入了自动返回类型检测。在您的示例中,尾随返回类型 -&gt; decltype(a &lt; 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


【解决方案1】:

auto 和 decltype 都可以让编译器推断出一个类型,而无需你明确写出类型是什么,但它们之间有一些重要的区别:

auto根据变量的初始化值定义变量的类型。

请记住,您并不总是在声明它们的同一行中初始化值。 示例:

int main() {
    auto a = 5;
    // auto b;  // compile error - can't use auto without an initializing value

    decltype(a) b;  // OK, can declare b to be the same type as a.
    b = 6; // then in the next line you can assign it an int
}

在模板函数中,仅 auto 就足以让编译器推断返回类型。但是,您也可以将 decltype 添加到 auto 以覆盖编译器推导的值。例如:

template<class A, class B> auto add(A a, B b) -> decltype(b) {
    return a + b;
}

int main() {
    // sum will be double without the ->decltype(b) part in add, but int with it
    auto sum = add(5.0, 6); 
}

【讨论】:

    【解决方案2】:

    如果不使用 autostd::function,则无法声明 lambda 表达式。

    每个 lambda 表达式都有不同的类型,因为它们的类型是在声明时生成的。

    auto l = [] (int a, double b) {
        return a > b ? a : b;
    };
    

    decltype 不能这样做。


    我还发现了一件有趣的事情:

    给定int a; double b;,无论a是否大于ba &gt; b ? a : b的类型总是double

    【讨论】:

    • 这很正常,一个函数需要一个返回类型,而该类型在运行时无法推导出来,所以 int 被提升为 double。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 2011-10-15
    • 2023-03-28
    • 1970-01-01
    • 2014-06-18
    相关资源
    最近更新 更多