[英]Why can't this public member function call decltype on a private struct member declared inside the class?
The following code, which loosely represents some serialization stuff I'm working on, compiles with g++ ( http://ideone.com/0rsGmt ), but Visual Studio Express 2013 RC fails with the following errors: 以下代码松散地代表了我正在处理的一些序列化工作,它们使用g ++( http://ideone.com/0rsGmt )进行编译,但是Visual Studio Express 2013 RC失败并出现以下错误:
Error 1 error C2326: 'void foo::print(void)' : function cannot access 'foo::bar::member_'
Error 2 error C2039: 'bar' : is not a member of 'foo'
The code: 编码:
#include <iostream>
class foo
{
private:
struct bar
{
int member_;
};
public:
void print()
{
std::cout << sizeof(decltype(foo::bar::member_)) << std::endl;
}
};
int main(int argc, char* argv[])
{
foo f;
f.print();
return 0;
}
What's wrong? 怎么了? Visual Studio inadequacy or something else?
Visual Studio不足或其他问题? Obviously I can move the struct declaration out of the class;
显然,我可以将struct声明移出类; and Daniel Frey has offered a workaround below;
Daniel Frey在下面提供了一种解决方法; but I want to know why the above code won't compile as-is with Visual Studio.
但是我想知道为什么上面的代码不能在Visual Studio中按原样编译。
Update: The accepted answer says that it should work, but as is typical for Microsoft it doesn't. 更新:可接受的答案说它应该起作用,但是对于Microsoft来说通常是不行的。 I've filled a bug report here: http://connect.microsoft.com/VisualStudio/feedback/details/801829/incomplete-decltype-support-in-c-11-compiler
我在这里填写了一个错误报告: http : //connect.microsoft.com/VisualStudio/feedback/details/801829/incomplete-decltype-support-in-c-11-compiler
(If someone can suggest a better title for the question, I'd appreciate it!) (如果有人可以为这个问题建议一个更好的标题,我将不胜感激!)
I think your code should work (as on GCC or Clang), according to 我认为您的代码应该可以工作(例如在GCC或Clang上),
5 Expressions [expr]
5个表达式[expr]
8 In some contexts, unevaluated operands appear (5.2.8, 5.3.3, 5.3.7, 7.1.6.2).
8在某些情况下,会出现未评估的操作数 (5.2.8、5.3.3、5.3.7、7.1.6.2)。 An unevaluated operand is not evaluated.
未评估的操作数不评估。 An unevaluated operand is considered a full-expression.
未评估的操作数被视为完整表达式。 [ Note: In an unevaluated operand, a non-static class member may be named (5.1) and naming of objects or functions does not, by itself, require that a definition be provided (3.2).
[ 注意:在未评估的操作数中,可以将非静态类成员命名为(5.1),而对象或函数的命名本身并不要求提供定义(3.2)。 — end note ]
— 尾注 ]
It seems that VC++ does not implement what the note clarifies, so you need a (faked) instance as a work-around to make VC++ happy. 似乎VC ++并没有实现该注释所阐明的内容,因此您需要一个(伪造的)实例作为使VC ++满意的一种解决方法。 This should work:
这应该工作:
void print()
{
std::cout << sizeof(std::declval<bar>().member_) << std::endl;
}
Note that I removed the decltype
as sizeof
can work on expressions directly. 请注意,我删除了
decltype
因为sizeof
可以直接处理表达式。
也许您的代码的问题在于结构就像类,并且您在类内部定义了结构,但是编译器直到编译整个类才知道该类(或结构)是否存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.