Why can I use auto on a private type?

前端 未结 4 694
悲哀的现实
悲哀的现实 2020-11-22 09:26

I was somehow surprised that the following code compiles and runs (vc2012 & gcc4.7.2)

class Foo {
    struct Bar { int i; };
public:
    Bar Baz() { retu         


        
4条回答
  •  忘了有多久
    2020-11-22 09:59

    The rules for auto are, for the most part, the same as for template type deduction. The example posted works for the same reason you can pass objects of private types to template functions:

    template 
    void fun(T t) {}
    
    int main() {
        Foo f;
        fun(f.Baz());         // ok
    }
    

    And why can we pass objects of private types to template functions, you ask? Because only the name of the type is inaccessible. The type itself is still usable, which is why you can return it to client code at all.

提交回复
热议问题