In this question  it was discussed why exposing a private type with auto:
#include <iostream>
using namespace std;
class Base {
  class PrivateClass {    
  public: 
    void bar() { cout << "PrivateClass" << endl; }
  };
public:
  PrivateClass foo() {
    PrivateClass a;
    return a;
  }
};
int main() {
  Base b;
  auto p = b.foo();
  p.bar();
  return 0;
}
is perfectly fine by the C++11 standard. What I still don't get is how this idiom may be useful in a real application. Are there problems where this idiom can be effectively used, or it should be considered as a "curious" side-effect of the keyword?
It can be useful if the return type is unspecified.  For example, the returned object from a call to std::bind, or formerly boost::bind, is not specified.  It is some implementation-defined functor, but you can't actually know its type without looking at implementation details.  Before C++11's auto keyword, you could use boost::function as a variable type for storing the result of bind, or you could pass the result of bind to a function which takes a template argument.  With C++11, you can store the result object using auto.
So, if a class has some internal type, it is not necessary to expose the actual type to a public API.  A user of the class can simply use the auto keyword, and the API documentation can say the type is "unspecified".  This keeps the actual internal type a private implementation detail, which can often improve encapsulation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With