Convert a free function to a DefaultConstructible function object

I am looking for a type that converts a free function to a default function construct object.

It should be a class template that takes a function as a template parameter:

template<typename F, F P> struct fn_to_type { template<class... Args> decltype(auto) operator()(Args&&... args) { return P(std::forward<Args>(args)...); } }; 

Therefore, it can be used as a template parameter for containers and smart pointers:

 bool CloseHandle(void* handle); using UniqueHandle = std::unique_ptr<void, fn_to_type<decltype(&CloseHandle), &CloseHandle>>; bool FooLess(const Foo& lhs, const Foo& rhs); using FooSet = std::set<Foo, fn_to_type<decltype(&FooLess), &FooLess>>; 

The standard library definitely does not have such a function, but perhaps the Boost library?

I'm also curious why such a thing is missing from the standard library - are there any pitfalls that I don't see?

And if there is no library with such a function, is there a way to improve this fn_to_type thing? For instance. do something so as not to print the function name twice?

+1
source share
1 answer

The standard library already has a class that can convert a pointer to a standard class type by default:

 template <class T, T v> struct integral_constant { ... constexpr operator value_type() { return value; } }; 

Thus, it can be used instead of this class fn_to_type :

 #include <type_traits> bool CloseHandle(void* handle); using UniqueHandle = std::unique_ptr<void, std::integral_constant<decltype(&CloseHandle), &CloseHandle>>; bool FooLess(const Foo& lhs, const Foo& rhs); using FooSet = std::set<Foo, std::integral_constant<decltype(&FooLess), &FooLess>>; 
+2
source

All Articles