gpt4 book ai didi

c++ - 如果我们将 "decltype(auto) f()"用作定义中包含 "decltype(f()) result"的函数声明,会发生什么情况?

转载 作者:行者123 更新时间:2023-11-30 04:12:19 27 4
gpt4 key购买 nike

这确实是一个 C++14 问题。而且它的理论性多于实践性。

有时您会零碎地构建一个函数的结果:

int f( int x, int y )
{
int a;
//...
return a;
}

但是如果你改变返回类型,你也必须改变“a”的类型。我通过一个特殊的声明来解决这个问题:

int f( int x, int y )
{
decltype( f(x,y) ) a;
//...
return a;
}

(对于新手:如果函数参数使用 r 值引用,有什么陷阱?提示:我们需要 std::forward 来修复它。)一个问题随机出现在我的脑海中:如果我使用“decltype(auto)”的新 C++14 功能作为返回类型怎么办?!我们会得到一个递归黑洞吗?还是不允许的错误?向“a”添加一个初始值设定项会让一切都好吗?

最佳答案

A question randomly popped into my head: what if I use the new C++14 feature of "decltype( auto )" as the return type?!

OP 所指的示例是:

auto f( int x, int y ) // using C++1y's return type deduction
{
decltype( f(x,y) ) a;
//...
return a;
}

Will we get a recursive black hole? Or an error that it's not allowed?

不允许 [dcl.spec.auto]/11:

If the type of an entity with an undeduced placeholder type is needed to determine the type of an expression, the program is ill-formed. Once a return statement has been seen in a function, however, the return type deduced from that statement can be used in the rest of the function, including in other return statements.


Would adding an initializer to a make everything all-right?

例如

decltype( f(x,y) )  a = 42;

没有; decltype 的使用需要确定 f 的返回类型。但是,以下是可能的:

auto a = 42;

来自评论:

so I could have a quick-and-dirty if & return block at the beginning of the function, then use the decltype(f(X)) construct afterwards (for the rest of the function)?

是的,例如

auto f( int x, int y ) // using C++1y's return type deduction
{
if(false) return int();

decltype( f(x,y) ) a;
//...
return a;
}

但是,我更喜欢:

auto f( int x, int y ) // using C++1y's return type deduction
{
int a; // specifying the return type of `f` here
//...
return a;
}

auto f( int x, int y ) // using C++1y's return type deduction
{
auto a = 42; // specifying the return type of `f` via the initializer
//...
return a;
}

关于c++ - 如果我们将 "decltype(auto) f()"用作定义中包含 "decltype(f()) result"的函数声明,会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19875092/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com