c++ - 是否允许在 decltyped 的变量的初始化程序中使用 decltype?

标签 c++ language-lawyer decltype

this question 触发,我想知道是否允许这样做:

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

struct bar {};

int main()
{

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

我试过的编译器毫无怨言地接受了它,但我不确定这是否真的合法,或者我是否遗漏了任何陷阱(在声明期间使用 a 的类型看起来很奇怪) .

对于背景:在链接的问题中,OP 希望避免 auto 并拼出类型(这里是 bar, SomeComplexTypeAndNotAuto question) 同时两次,因此他们使用(未使用的)参数来推断 T。我不喜欢仅仅为了推断类型而滥用参数,所以我的第一个想法是 decltype

最佳答案

没关系。

[basic.scope.pdecl]

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

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 is an unevaluated operand 的表达式,没有UB。只检查变量的类型,而不检查它的不确定值。

但不考虑口味。

关于c++ - 是否允许在 decltyped 的变量的初始化程序中使用 decltype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60830867/

相关文章:

c++ - 有没有办法使用 SFINAE 检测是否未声明非模板化非成员函数?

c++ - llvm 可以发出跳转到函数内给定地址的代码吗?

c++ - 访问 std::string 中字符串的位置大于其大小的元素

c++ - 来自函数参数的容器的 decltype

c++ - 为什么 decltype(a, b) 被评估为引用?

c++ - std::vector 是否可以简单复制,为什么?

c++ - 在 C++ 中使用动态多维数组

c++ - 将 std::ispunct 作为参数传递给 remove_copy_if() 无法编译

c++ - 没有重载运算符 ->

c++ - 我应该如何在恒定长度的 STL 样式数据结构中实现 max_size?