I am trying to create function pointers for functions that return unique_ptr
instances. Each function should return a value that is as specifically-typed as possible in order to be generally useful to many callers (in my real code, the functions are named constructors and in the public header for each object). However, in this particular use, I only care about the general interface that each class implements.
I am running into an issue where I cannot assign a function that returns unique_ptr<Subclass>
to a function pointer that returns unique_ptr<Superclass>
.
I have boiled my example down to this snippet:
#include <iostream>
#include <memory>
struct Foo {
virtual void foo() = 0;
};
struct Bar : public Foo {
void foo() {};
};
std::unique_ptr<Foo>
foo_creator()
{
return nullptr;
}
std::unique_ptr<Bar>
bar_creator()
{
return nullptr;
}
typedef std::unique_ptr<Foo>(*creator_fn)();
int
main(int argc, char *argv[])
{
std::unique_ptr<Foo> f;
f = foo_creator();
f = bar_creator();
creator_fn foo_fn = foo_creator;
creator_fn bar_fn = bar_creator; // Fails
return 0;
}
The compilation error I get from clang (Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
) is:
cannot initialize a variable of type 'creator_fn'
(aka 'std::unique_ptr<Foo> (*)()') with an lvalue
of type 'std::unique_ptr<Bar> ()':
different return type
('unique_ptr<struct Foo>' vs 'unique_ptr<struct Bar>')
I'm open to being told of a better way of accomplishing my goal, too. :-)