Search code examples
c++c++11c++14copy-constructorpointer-to-member

How can I obtain a member function pointer to the copy constructor of a class?


Is there any way to get a member function pointer to the copy constructor of a class? I know how to define and use a normal member function pointer, but I can't seem to figure out a way to get it.


Solution

  • According to the C++ standard, "the address of a constructor shall not be taken," so it's just not possible to do what you're asking. However, there's a simple workaround. The below code returns a function pointer to a function that creates a copy of it's input.

    template<class obj> auto GetCopyConstructor() -> obj(*)(const obj&) 
    {
        return +[](const obj& o) { return obj(o); };
    }    
    struct foo
    {
        std::string msg;
        foo(const std::string& my_msg) { msg = my_msg; }
        foo(const foo&) = default;
    };
    int main()
    {
        auto make_copy = GetCopyConstructor<foo>();
        foo a("Hello, world");
        foo b = make_copy(a);
        std::cout << b.msg << std::endl;
    }
    

    Alternatively: (A simplification that also covers additional use cases)

    template<class obj> obj Copy(const obj& o) { return obj(o); }
    template<class obj> obj* CopyNew(const obj& o) { return new obj(o); }
    template<class obj> obj CopyFromPtr(const obj* o) { return obj(*o); }
    template<class obj> obj* CopyNewFromPtr(const obj* o) { return new obj(*o); }
    template<class obj> void* WhyWouldYouEvenWantToDoThis(const void* o) 
    { return new obj(*(obj*)o); }
    int main()
    {
        foo(*make_copy)(const foo&) = Copy<foo>;
        foo a("Hello, world");
        foo b = make_copy(a);
        std::cout << b.msg << std::endl;
    }