【问题标题】:Way for class template to deduce type when constructing an instance with std::make_unique?使用std :: make_unique构造实例时类模板推断类型的方式?
【发布时间】:2022-01-15 12:30:30
【问题描述】:

假设我们有一个类模板Foo,它有一个类型模板参数,它可以从其构造函数中的参数推导出来。如果我们使用std::make_unique 来构造Foo 的实例,那么Foo 的构造函数有没有办法像正常调用它的构造函数那样推导出模板参数?这是实现这一目标的最简单方法吗?

std::make_unique< decltype(Foo{...}) > (...);

这看起来很干净,但是如果Foo 的构造函数需要很多参数,它可能会变成一条非常丑陋的行。

【问题讨论】:

    标签: c++ templates decltype template-argument-deduction


    【解决方案1】:

    您可以利用辅助函数将丑陋的代码包装到漂亮的包装器中。看起来像

    template <typename... Args>
    auto make_foo_ptr(Args&&... args)
    {
        return std::make_unique<decltype(Foo{std::forward<Args>(args)...})>(std::forward<Args>(args)...);
    }
    

    【讨论】:

    • 这不会强制从Foo 实例化的模板类可以复制/移动构造,因为最终它必须是auto x = make_foo_ptr(); 之类的东西?
    • @Zoso 它没有,因为该函数返回一个unique_ptr&lt;Foo&gt;,而不是一个Foo,并且unique_ptr&lt;T&gt; 始终是可移动的。此外,从 C++17 开始,即使它返回 Foo 并且 Foo 不可移动或不可复制,由于 C++17 保证复制省略,它仍然可以工作。
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 2015-10-31
    相关资源
    最近更新 更多