繁体   English   中英

以'auto &&'作为 function 返回类型的推导类型

[英]Deduced type with 'auto &&' as function return type

在以下代码段中, function B::f()是围绕 function 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; 
}

以下代码段让我感到困惑,因为我原以为f()g()的返回类型会是int ,但它是int & for f()int && for g() (我什至不明白为什么不一样)...如何解释?

#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";
   }
}

谢谢!

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM