【问题标题】:Deduced type with 'auto &&' as function return type以 'auto &&' 作为函数返回类型的推导类型
【发布时间】:2021-12-15 17:37:03
【问题描述】:

在下面的 sn-p 中,函数 B::f() 是函数 A::f() 的“包装器”。但我假设 A::f() 返回类型是“不透明”类型,我不知道它是否具有值或引用语义。所以我不能使用autoconst auto & 作为B::f() 的返回类型。我认为auto && 可以解决问题,但事实并非如此,因为auto && 被推断为A::OpaqueType &...这里可以避免写A::OpaqueType吗?

#include <iostream>

struct A {
    using OpaqueType=int; // But it could have been `const int &`

    OpaqueType f() const {
        return i;
    }

    int i=42;
};

struct B {
    // how could I use `auto` here to avoid writing the `A::OpaqueType`?
    // I would have expected that `auto &&` would do the trick but it does not
    A::OpaqueType f() const { 
        return a.f();
    }

    A a;
};

int main()
{
    B b;
    std::cout << b.f() << std::endl; 
}

下面的 sn-p 让我感到困惑,因为我原以为 f()g() 的返回类型将是 int,但对于 f()int &amp;&amp; 对于 @ 它是 int &amp; 987654338@(我什至不明白为什么不一样)...这怎么解释?

#include <iostream>
 
auto &&f() {
    int i=42;
    return i;
}

struct A {
    int f() {return i;}

    int i=42;
};

auto &&g() {
    A a;
    return a.f();
}

int main()
{
   if (std::is_same_v<decltype(f()), int &>) {
       std::cout << "f() return type is 'int &'\n";
   }
   if (std::is_same_v<decltype(g()), int &&>) {
       std::cout << "g() return type is 'int &&'\n";
   }
}

谢谢!

【问题讨论】:

    标签: c++ c++17 auto type-deduction return-type-deduction


    【解决方案1】:

    很确定您正在寻找的是decltype(auto)。如果return语句中的表达式按值返回,这将按值返回,如果return语句中的表达式按引用返回,它将按引用返回。那会给你

    decltype(auto) f() const { 
        return a.f();
    }
    

    【讨论】:

    • 谢谢,这正是我所需要的! (但我发现语法很丑……)
    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多