According to the C ++ standard, "constructor address should not be accepted," so it is simply not possible to accomplish what you ask. However, there is an easy way around this problem. The following code returns a pointer to a function that creates a copy of its 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: (simplification, which also applies to 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; }
source share