Here is an example of my code:
#include <iostream>
#include <memory>
class Base
{
public:
virtual void name() = 0;
};
using ptr_t = std::unique_ptr<Base>;
class A : public Base
{
A(int x) : n(x) {}
public:
void name() override
{
std::cout << "Test " << n << "\n";
}
template <typename T>
friend ptr_t create(int x);
private:
int n;
};
template <typename T>
ptr_t create(int x)
{
return std::make_unique<T>(x);
}
int main()
{
auto a = create<A>(3);
a->name();
}
At first I thought the problem was in the conversion from std::unique_ptr<A>
to std::unique_ptr<Base>
. But that seems to work fine in an isolated code sample and is also correct according to this answer:
unique_ptr to a base class
The code above also works if I use a raw pointer instead of a unique pointer.
Can someone explain what I'm missing. Thank you.