I want to declare std::make_unique
function as a friend of my class. The reason is that I want to declare my constructor protected
and provide an alternative method of creating the object using unique_ptr
. Here is a sample code:
#include <memory>
template <typename T>
class A
{
public:
// Somehow I want to declare make_unique as a friend
friend std::unique_ptr<A<T>> std::make_unique<A<T>>();
static std::unique_ptr<A> CreateA(T x)
{
//return std::unique_ptr<A>(new A(x)); // works
return std::make_unique<A>(x); // doesn't work
}
protected:
A(T x) { (void)x; }
};
int main()
{
std::unique_ptr<A<int>> a = A<int>::CreateA(5);
(void)a;
return 0;
}
Right now I get this error:
Start
In file included from prog.cc:1:
/usr/local/libcxx-head/include/c++/v1/memory:3152:32: error: calling a protected constructor of class 'A<int>'
return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
^
prog.cc:13:21: note: in instantiation of function template specialization 'std::__1::make_unique<A<int>, int &>' requested here
return std::make_unique<A>(x); // doesn't work
^
prog.cc:22:41: note: in instantiation of member function 'A<int>::CreateA' requested here
std::unique_ptr<A<int>> a = A<int>::CreateA(5);
^
prog.cc:17:5: note: declared protected here
A(T x) { (void)x; }
^
1 error generated.
1
Finish
What is the correct way to declare std::make_unique
as a friend of my class?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…