Pregunta

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:

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? Obviously I can move the struct declaration out of the class; and Daniel Frey has offered a workaround below; but I want to know why the above code won't compile as-is with Visual Studio.

Update: The accepted answer says that it should work, but as is typical for Microsoft it doesn't. I've filled a bug report here: 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!)

¿Fue útil?

Solución

I think your code should work (as on GCC or Clang), according to

5 Expressions [expr]

8 In some contexts, unevaluated operands appear (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). — 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. 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.

Otros consejos

Maybe the problem with your code is that structs are like classes and you define the struct inside the class but the compiler does not know that this class(or struct) exists until it compiles the whole class.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top