Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exposing a private type with auto: where can it be useful?

Tags:

c++

c++11

auto

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?

like image 864
Massimiliano Avatar asked Dec 04 '12 18:12

Massimiliano


1 Answers

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.

like image 128
Charles Salvia Avatar answered Nov 15 '22 23:11

Charles Salvia