In the realm of C , the versatility of auto often sparks curiosity and sometimes even bewilderment. One perplexing observation arises when using auto with private types.
Consider the following code snippet, which surprisingly compiles without errors:
class Foo { struct Bar { int i; }; public: Bar Baz() { return Bar(); } }; int main() { Foo f; auto b = f.Baz(); // ok std::cout << b.i; }
This unconventional behavior prompts the question: why can we access a private type through auto while direct access is prohibited?
To unravel this enigma, we must delve into the mechanics of auto. Its type deduction rules largely mirror those of C templates. This observation holds true for the aforementioned code sample. Just as we can pass objects of private types as arguments to template functions:
template <typename T> void fun(T t) {} int main() { Foo f; fun(f.Baz()); // ok }
we can also infer their types using auto. This is because even though the type name itself remains inaccessible, the type information is still available. This permits the return of private types to client code, allowing for the otherwise forbidden access through auto.
The above is the detailed content of Why Can `auto` Access Private C Types When Direct Access Is Forbidden?. For more information, please follow other related articles on the PHP Chinese website!