是否允许在初始化程序中为decltyped的变量使用decltype? [英] Is it allowed to use decltype in an initializer for the variable that is decltyped?

查看:88
本文介绍了是否允许在初始化程序中为decltyped的变量使用decltype?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题触发,我想知道是否允许:

Triggered by this question, I was wondering if, this is allowed:

template <typename T>
T foo(){return T{};}

struct bar {};

int main()
{

    bar a = foo<decltype(a)>();
}

我尝试过的编译器在没有任何抱怨的情况下接受了它,但是我不确定这是否真的合法,或者我是否遗漏了任何陷阱(并且在声明时使用a类型看起来很奇怪).

Compilers I tried took it without complaints, but I am not sure if this is really legal or if I am missing any pitfalls (and it looks weird to use the type of a during its declaration).

对于背景:在链接的问题中,OP希望避免auto并同时拼写两次类型(此处是该问题中的barSomeComplexTypeAndNotAuto),因此他们使用了(未使用)推导T的参数.我不喜欢只是为了推断类型而滥用参数,所以我的第一个想法是decltype.

For background: in the linked question OP wants to avoid auto and spelling out the type (here it is bar, SomeComplexTypeAndNotAuto in that question) twice at the same time, hence they use a (unused) parameter to deduce T. I didn't like misusing a parameter merely to deduce the type so my first idea was decltype.

推荐答案

没问题了.

[basic.scope.pdecl]

1 名称的声明点紧随其后它的 完整的声明器([dcl.decl])并在其初始值设定项(如果有)之前, 除非另有说明. [示例:

1 The point of declaration for a name is immediately after its complete declarator ([dcl.decl]) and before its initializer (if any), except as noted below. [ Example:

unsigned char x = 12;
{ unsigned char x = x; }

在这里,第二个x的初始化具有未定义的行为, 因为初始化程序会在其生存期之外访问第二个x ([basic.life]). —结束示例]

Here, the initialization of the second x has undefined behavior, because the initializer accesses the second x outside its lifetime ([basic.life]). — end example ]

因此,您可以在其自己的初始化程序中使用a,因为它已在此处声明.唯一的问题是如何. decltype可以应用于命名作用域中的任何变量的id表达式.而且,由于decltype 的表达式是未评估的操作数,没有UB.仅检查变量的类型,不检查其不确定值.

So you can use a in its own initializer, since its declared at the point. The only question is how. decltype can be applied to an id-expression naming any variable in scope. And since the expression of decltype is an unevaluated operand, there is no UB. Only the type of the variable is examined, not its indeterminate value.

虽然没有考虑味道.

这篇关于是否允许在初始化程序中为decltyped的变量使用decltype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆