Boost或其他库是否支持将无构造函数类提升为使用聚合初始化的函数对象
你遇到的核心问题是boost::hof::construct内部采用括号初始化(T(args...))实现,而没有用户声明构造函数的聚合类型只能通过花括号初始化(T{args...})完成构造,因此原生不支持该场景。
目前没有成熟的第三方库直接提供这个特性,你可以自己实现一个通用的聚合构造函数对象,逻辑非常简单,可完美覆盖完美转发、可变参数的需求:
#include <utility> // 通用聚合构造器,调用时指定目标类型 struct construct_aggregate { template <typename T, typename... Args> constexpr auto operator()(Args&&... args) const noexcept(noexcept(T{std::forward<Args>(args)...})) -> decltype(T{std::forward<Args>(args)...}) { return T{std::forward<Args>(args)...}; } }; // 固定目标类型的聚合构造器,提前绑定目标类型 template <typename T> struct construct_aggregate_for { template <typename... Args> constexpr auto operator()(Args&&... args) const noexcept(noexcept(T{std::forward<Args>(args)...})) -> decltype(T{std::forward<Args>(args)...}) { return T{std::forward<Args>(args)...}; } };
使用示例
struct Foo { int foo; }; // 调用时指定类型用法 construct_aggregate ctor; Foo f1 = ctor<Foo>(3); // f1.foo == 3 // 提前绑定类型用法 construct_aggregate_for<Foo> make_foo; Foo f2 = make_foo(5); // f2.foo == 5
该实现同时兼容聚合类型和有自定义构造函数的普通类型,适用范围比boost::hof::construct更广。C17及以上版本可直接使用,C14版本仅需去掉constexpr修饰即可正常工作。
内容的提问来源于stack exchange,提问作者Enlico
相关产品推荐
相关产品推荐

