How can I get a member function pointer to a class copy constructor?

Is there a way to get a member function pointer to a class copy constructor? I know how to define and use a regular pointer to a member function, but I cannot figure out how to get it.

+5
source share
1 answer

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; } 
+3
source

Source: https://habr.com/ru/post/1258901/


All Articles