C++ 如果我们使用;decltype(自动)f();作为带有“的函数声明”;decltype(f())结果“0”;在定义中?

C++ 如果我们使用;decltype(自动)f();作为带有“的函数声明”;decltype(f())结果“0”;在定义中?,c++,c++11,c++14,C++,C++11,C++14,这确实是一个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值引用,那么

这确实是一个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
来修复它。)一个问题随机出现在我的脑海中:如果我使用新的C++14特性“
decltype(auto)
”作为返回类型怎么办?!我们会得到一个递归黑洞吗?还是一个不允许的错误?在“a”中添加初始值设定项会使一切正常吗

我脑海中突然冒出一个问题:如果我使用新的C++14会怎么样 返回类型为“decltype(auto)”的功能

OP所指的示例是:

auto f( int x, int y ) // using C++1y's return type deduction
{
    decltype( f(x,y) )  a;
    //...
    return a;
}
我们会得到一个递归黑洞吗?还是一个不允许的错误

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

如果需要具有未减少占位符类型的实体类型 要确定表达式的类型,程序的格式不正确。 但是,一旦在函数中看到return语句,则 从该语句推导出的返回类型可用于 函数,包括在其他返回语句中


a
中添加初始值设定项会使一切正常吗

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

auto a = 42;
在评论中:

因此,我可以在函数的开头使用快速且脏的
if
&
return
块,然后在函数的其余部分使用
decltype(f(X))
构造

是的,例如

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


[dcl.spec.auto]/11“如果需要具有未简化占位符类型的实体类型来确定表达式的类型,则程序的格式不正确。但是,一旦在函数中看到返回语句,则从该语句推导出的返回类型可用于函数的其余部分,包括其他返回语句。”呃-那
decltype(f(x,y))
太可怕了-让它变得不必要是我见过的自动返回类型推断的最好理由@DyP,这样我就可以在函数的开头有一个快速且脏的
if
&
return
块,然后在之后(对于函数的其余部分)使用
decltype(f(X))
构造了?@CTMacUser是的,我想是这样的@DyP,你能不能把你的工作以常规答案的形式写下来,这样我就可以结束这篇文章,给你打分?
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;
}