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.
1 Answer
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;
}
-
The only missing lines are #include <iostream> and #include <string>, and the code works in both C++11 and C++14 using the GCC compiler. What problems are you having? Oct 27, 2016 at 20:11
-
-
The + should not be necessary, not sure why it's there? It should trigger an implicit conversion upon return just fine without it. Oct 27, 2016 at 20:35
-
2@NirFriedman the
+
would be relevant if the trailing return type were omitted (in which case the return type is deduced from the argument of the return statement, without applying the conversion of lambda to function-pointer)– M.MOct 27, 2016 at 23:52 -
Hmm this would be fine if I could store the results of different GetCopyConstructor calls in one type. I guess making the return type
void*(*)(void*)
would do, but also sidestep the type system :(– rubenvbOct 28, 2016 at 17:26
(someObject.*mfp)(args)
. how would you use the copy constructor member function pointer to construct a new object with that syntax?