C++ 声明与auto一起工作,但不通过显式声明类型来工作?

C++ 声明与auto一起工作,但不通过显式声明类型来工作?,c++,c++11,C++,C++11,我有以下课程: struct pool : public std::enable_shared_from_this<pool> { private: struct manager { explicit manager(const std::weak_ptr<pool> &pool) : m_pool{pool} { } explicit manager() = default;

我有以下课程:

struct pool : public std::enable_shared_from_this<pool> {
     private:
      struct manager {
        explicit manager(const std::weak_ptr<pool> &pool) : m_pool{pool} {
        }
        explicit manager() = default;
        auto operator()(connection *conn) -> void;

       private:
        std::weak_ptr<pool> m_pool;
      };

     public:
      pool(const pool &) = delete;
      auto operator=(const pool &) -> pool & = delete;

      auto borrow() noexcept -> std::unique_ptr<connection, manager>;
}
但是我不能声明与
borrow()
的返回类型相同的变量:

std::唯一的ptr连接

当clang返回错误时:

错误:“manager”是“dbc::detail::pool”的私有成员。

这两者不应该互换吗

这两者不应该互换吗

不,不一定。私有结构将被视为实现细节,因此可以在类的未来版本中删除或重命名它。因此,不允许任何人(类外)拼写私有结构的名称

如果类的成员函数返回该私有类型的对象,则需要一种处理这些对象的方法。这样做的一种可能性是
auto
关键字。(可选方法是
decltype
和函数模板。后者存在于C++11之前。)请注意,如果决定重命名私有结构,
auto
关键字也会起作用。

如果使用
decltype
,可以声明所需的变量:

decltype(p->borrow()) conn = p->borrow();
访问控制适用于名称,而不是定义或数据

即使类型的名称是私有的,只要不命名,也可以使用该类型

下面是一个没有
auto
的示例:

class A
{
    struct B { int x; } m_b;
public:
    B f() { return m_b; }
};

int main()
{
    A a;
    std::cout << a.f().x; // Compiles, since 'A::B::x' is public.
    decltype(a.f()) b1; // Compiles, since the name 'B' is not used.
    A::B b; // Doesn't compile, since the name is private.
}
A类
{
结构B{int x;}m_B;
公众:
bf(){return m_B;}
};
int main()
{
A A;
标准::cout
class A
{
    struct B { int x; } m_b;
public:
    B f() { return m_b; }
};

int main()
{
    A a;
    std::cout << a.f().x; // Compiles, since 'A::B::x' is public.
    decltype(a.f()) b1; // Compiles, since the name 'B' is not used.
    A::B b; // Doesn't compile, since the name is private.
}