我正在寻找将自由函数转换为默认可构造函数对象的类型。
它应该是一个类模板,它将功能作为模板参数:
template<typename F, F P>
struct fn_to_type {
template<class... Args>
decltype(auto) operator()(Args&&... args) {
return P(std::forward<Args>(args)...);
}
};
因此,它可用作容器和智能指针的模板参数:
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>>;
标准库肯定没有这种功能,但是Boost库可能有吗?
我也很好奇为什么这样的东西不在标准库中-我有看不见的陷阱吗?
而且,如果没有具有此类功能的库,是否有办法改进此功能fn_to_type
?例如,要做一些避免两次输入函数名称的事情?
标准库已经有一个类,可以将函数指针转换为默认可构造的类类型:
template <class T, T v>
struct integral_constant {
...
constexpr operator value_type() { return value; }
};
因此,可以使用它代替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>>;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句