【发布时间】:2021-12-15 17:37:03
【问题描述】:
在下面的 sn-p 中,函数 B::f() 是函数 A::f() 的“包装器”。但我假设 A::f() 返回类型是“不透明”类型,我不知道它是否具有值或引用语义。所以我不能使用auto 或const 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 && 对于 @ 它是 int & 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