17

在这个问题中,讨论了为什么公开私有类型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;
}

完全符合 C++11 标准。我仍然不明白这个习语在实际应用程序中如何有用。 是否存在可以有效使用此成语的问题,或者应该将其视为关键字的“好奇”副作用?

4

2 回答 2

10

如果未指定返回类型,它会很有用。例如,从调用返回的对象std::bind,或以前boost::bind,没有指定。它是一些实现定义的仿函数,但如果不查看实现细节,您实际上无法知道它的类型。在 C++11 的auto关键字之前,您可以boost::function用作存储结果的变量类型bind,或者您可以将结果传递bind给接受模板参数的函数。使用 C++11,您可以使用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.

于 2012-12-04T18:45:53.773 回答
1

Wheter the "auto" keyword & subclasing provides such feature, the concept of "private types" seems unpractical.

Before O.O.P., some developers hide some type using a (void*) pointer, to a "struct". Another more updated cases allowed an object of a given class, been exposed only by a superclass.

于 2012-12-04T19:02:21.540 回答