Search code examples
c++c++11function-pointerspointer-to-member

Pointer to constructor overload?


I have a bunch of legacy code that looks like:

#define MAKE_FOO_FNS(fooname) \
fooname* makeFoo_ ## fooname ## A(A arg) { \
  return new fooname(arg); \
} \
fooname* makeFoo_ ## fooname ## B(B arg) { \
  return new fooname(arg); \
} \
// ... repeated many more times 

so that later in the code we can say:

MAKE_FOO_FNS(FooType1);
MAKE_FOO_FNS(FooType2);

and then have access to function pointers with the types:

 FooType1* (*)(A);
 FooType1* (*)(B);
 FooType2* (*)(A);
 FooType2* (*)(B);

I know that I can replace MAKE_FOO_FNS with templates:

template<typename FooType>
FooType* makeFooA(A arg) {
  return new FooType(arg);
}
// .. etc ..

so that we can get the function pointer from &MakeFooA<FooType1>, &MakeFooA<FooType2>, etc, without any macro hackery.

But this still seems like unnecessary boilerplate --- is there a (C++11) way to get a function pointer directly to "invoking operator new of FooType1 with the constructor that takes an A" without writing all of these wrapper functions?


Solution

  • You might merge all the makeFooA<>(), makeFooB<>(), etc. functions into a single generic template:

    template<typename T, typename... Args>
    T* make_ptr(Args&&... args)
    {
        return new T(std::forward<Args>(args)...);
    }
    

    This has the advantage that passing multiple parameters is now possible (either by value or by reference) and the drawback that you need to specify full signature when taking the address, i.e., &make_ptr.

    Note that, if you have boost, you don't need to implement it yourself: http://www.boost.org/doc/libs/1_61_0/libs/functional/factory/doc/html/