Bind default constructor to a std::function<T*()>

Viewed 66

I have a class template which allocates objects and, to allow use of a particular (not default) constructor, an allocation function shall be provided with the following signature to return a pointer to a T object:

Foo<T>::Foo(std::function<T*()> allocate);

I then implement a function which calls the specific constructor and then bind this method to the allocate function:

Foo<MyClass> foo( std::bind(&MyClassAllocFunction,parameter) );

with MyClassAllocFunction() being for instance:

MyClass *MyClassAllocFunction( int parameter )
{
    return new MyClass(parameter);
}

Now I'd like to use the default constructor, and possibly avoid creating a dedicated function. Is there a way to bind a "default constructor allocator" which would return a pointer to an allocated object ?

The solution proposed by @MarekR answers my question

Foo<MyClass> foo( []() { return new MyClass {}; } );
0 Answers
Related