c++ - 我应该如何使我的分配器可重新绑定(bind)?我可以在保持其字段私有(private)的同时做到这一点吗?

标签 c++ templates friend allocator

长话短说,问题是:

template<class T>
struct alloc
{
    template<class U>
    alloc(alloc<U> const &other) : foo(other.foo) { }  // ERROR: other.foo is private 
    template<class U> struct rebind { typedef alloc<U> other; };
private:
    pool<T> *foo;  // do I HAVE to expose this?
};

是公开公开私有(private)字段的唯一解决方案吗?
您应该如何实际创建转换构造函数?

最佳答案

在模板复制构造函数中,alloc<T>alloc<U>是不同的类型,意味着您无法访问 alloc<U> 的私有(private)成员在这里。

您可以制作alloc<U> friend :

template<class T>
struct alloc
{
    ... ...
    template <typename U>
    friend struct alloc;
    alloc(alloc<U> const &other) : foo(other.foo) {} // possible to access other.foo now
};

关于c++ - 我应该如何使我的分配器可重新绑定(bind)?我可以在保持其字段私有(private)的同时做到这一点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38045672/

相关文章:

templates - 模板返回值的模板函数的完全特化

c++ - 为什么编译器不能将 const int 绑定(bind)到右值引用?

c++ - 如何初始化一个私有(private)嵌套类类型的静态字段?

c++ - 列出QTable - 选择动态

c++ - 区分静态数组,指针和结构的C++模板

c++ - 模板类的模板友元函数

.net - friend 引用课?

c++ - 两个窗口 - 一个由线程随机输出修改

c# - 如何在C#编写的程序中使用C++的.h库?

c++ - 简化四面体网格的库