I created a class and I want to force anyone who's trying to construct an object, to use unique_ptr
. To do that I thought of declaring the constructor protected
and use a friend
function that returns a unique_ptr
. So here's an example of what I want to do:
template <typename T>
class A
{
public:
friend std::unique_ptr<A<T>> CreateA<T>(int myarg);
protected:
A(int myarg) {}
};
template <typename T>
std::unique_ptr<A<T>> CreateA(int myarg)
{
// Since I declared CreateA as a friend I thought I
// would be able to do that
return std::make_unique<A<T>>(myarg);
}
I did some reading on friend functions and I understood that a friend function provides access to private/protected members of an object of a class.
Is there anyway I can make my example work?
Even without friend functions, my goal is to make the CreateA
the only way for someone to create an object.
EDIT
I change the code a bit. I didn't mention that my class takes one template parameter. That makes things more complex apparently.
A<T>>
always has a constructor takingint
. Is this also true in the real code; or does the real code have constructor takingT
(and perhaps more arguments) ? – Indefinite