为什么在使用decltype时,编译器为什么不推断成员的类型? [英] Why doesn't the compiler infer the type of member when using decltype?
问题描述
我只是在自己的代码中注意到了这种行为,所以这是一个天真的问题:
I just noticed this behavior in own code, so here is the naive question:
此:
struct A
{
int get()
{
return a;
}
int a=1;
};
int main() {}
当然可以编译,尽管当成员数据的声明位于函数定义的之后.
Compiles of course fine, although when the declaration of member data lies after the function definition.
但是我不明白为什么这样:
But then I don't understand why this:
struct A
{
auto get() -> decltype(a)
{
return a;
}
int a=1;
};
不编译(*).我必须写这个:
does not compile(*). I have to write this:
struct A
{
int a=1;
auto get() -> decltype(a)
{
return a;
}
};
是否有任何与语言相关的原因导致它不正常,或者仅仅是编译器没有实现?无论类成员的顺序如何,我都希望具有相同的行为.
Is there any language-related reasons why it's not ok, or is it just that the compilers have not implemented that ? I would expect to have the same behavior regardless of the order of the class members.
(*)通过Ideone.com在gcc 6.3上进行了测试
(*) tested with gcc 6.3 through Ideone.com
推荐答案
在您的第一个示例中,声明了 A :: get
,然后声明了 A :: a
,直到那时(因为完全声明了 A
),才定义了 A :: get
.此时,在 A :: get
中,编译器知道了 A :: a
.
In your first example, A::get
is declared, then A::a
is declared, and only then (because A
is fully declared), A::get
is defined. At this point, in A::get
, the compiler knows about A::a
.
考虑以下等效形式:
struct A
{
int get();
int a=1;
};
inline int A::get()
{
return a;
}
这对于您的第二个示例来说是无法编译的:
This would not be compilable for you second example:
struct A
{
auto get() -> decltype(a); // What is "a"?
int a=1;
};
inline auto A::get() -> decltype(A::a)
{
return a;
}
声明类型时必须遵循相同的声明顺序",例如:
The same "order of declaration" has to be respected when you declare types, for example:
struct A
{
using IntType = int;
auto get() -> IntType;
int a=1;
};
你不能这样写:
struct A
{
using IntType = decltype(a);
auto get() -> IntType;
int a=1;
};
还请注意,这不仅限于返回类型:参数类型也是函数声明的一部分.因此,这也不会编译:
Also note that this is not limited to return types: parameter types are also part of a function declaration. So this doesn't compile either:
struct A
{
void f(decltype(a));
int a=1;
};
这篇关于为什么在使用decltype时,编译器为什么不推断成员的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!