简体   繁体   中英

Unable to access private member - template and std::unique_ptr

I have the following code:

#include <memory>

template<typename T, size_t Level>
class Foo
{
    friend class Foo<T, Level + 1>;
    typedef std::unique_ptr<T> ElmPtr;
    typedef std::unique_ptr<Foo<ElmPtr, Level - 1>> NodePtr;        

    public:
    Foo() {
        // no errors
        auto c = children;
    }

    Foo(int n) {
        // !!! compiler error !!!
        auto c = children;
    }

    std::array<NodePtr, 4> children;            
};

template<typename T>
class Foo<T, 0>
{
    friend class Foo<T, 1>;

    public:
    Foo() {}
};

int main()
{
    Foo<int, 1> foo1;
}

I get the following error:

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

Why? How can I fix this problem?

You have:

auto c = children;

Where:

std::array<std::unique_ptr<T>, N> children;            

That would require copying unique_ptr s, and unique_ptr is not copyable. You can take a reference to children though:

auto& c = children; // OK 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM