Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot I use an instantiation of std::make_shared as a pointer to function?

When a class has a default constructor, I can use the instantiation of std::make_shared in the same way as a pointer to a function. This is probably because the instantiated template has to be compiled and stored in memory and its address must exist.

#include <memory>
#include <functional>

class DefaultConstructible
{
};

typedef std::function<std::shared_ptr<DefaultConstructible>()> Generator;

int main()
{
    Generator generator(std::make_shared<DefaultConstructible>);
    std::shared_ptr<DefaultConstructible> defConst = generator();

    return 0;
}

But the same thing fails when I add a non-trivial constructor:

#include <memory>
#include <functional>

class FromInt
{
public:
    FromInt(int a):a_(a){}
    int a_;
};

typedef std::function<std::shared_ptr<FromInt>(int)> Generator;

int main()
{
    Generator generator(std::make_shared<FromInt>);
    std::shared_ptr<FromInt> p = generator(2);

    return 0;
}

I get a compiler error:

 error: no matching function for call to 
'std::function<std::shared_ptr<FromInt>(int)>::function(<unresolved overloaded function type>)'
     Generator g(std::make_shared<FromInt>);
                                          ^

Why is this so and how can I make my code compile?

like image 994
Martin Drozdik Avatar asked Feb 10 '14 10:02

Martin Drozdik


1 Answers

You just need to be explicit about which constructor you want it to use:

Generator generator(std::make_shared<FromInt, int>);

The "extra" template argument(s) correspond to the constructor arguments.

like image 152
John Zwinck Avatar answered Oct 11 '22 18:10

John Zwinck