Using 'auto' on Private Types
In C , it may seem counterintuitive that one can utilize 'auto' with private types, as demonstrated in the following code:
class Foo { struct Bar { int i; }; public: Bar Baz() { return Bar(); } };
Normally, it would be expected that attempting to access the private type 'Bar' directly (e.g., Foo::Bar b = f.Baz();) would result in an error. However, this is not the case when using 'auto':
int main() { Foo f; auto b = f.Baz(); // ok std::cout << b.i; }
This behavior arises due to the similarity between 'auto' rules and template type deduction. Similar to how private types can be passed to template functions:
template <typename T> void fun(T t) {} int main() { Foo f; fun(f.Baz()); // ok }
This ability stems from the fact that while the name of a private type may be inaccessible, the type itself remains usable. Consequently, 'auto' is able to deduce the type correctly and assign it to the 'b' variable, despite being a private type.
The above is the detailed content of Can `auto` Deduce Private Types in C ?. For more information, please follow other related articles on the PHP Chinese website!