You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:06:03