如何使用std::constructible_from?C++ Concepts使用困惑求助
解决C++ Concepts中
create_unique的模板参数顺序与约束问题 我来帮你梳理一下这个问题,核心是模板参数顺序和Concept约束的正确写法,咱们一步步来解决:
1. 修正模板参数顺序,实现只显式指定CreatedClass
你最初的问题是模板参数顺序导致必须显式指定两个参数——因为模板参数的显式指定是按左到右顺序的,如果Arg放在第一个位置,显式指定CreatedClass时必须先填Arg的类型,这显然不是你想要的。
正确的做法是把需要显式指定的CreatedClass放在第一个模板参数位置,让Arg通过函数参数推导得到,同时用requires子句约束CreatedClass可从Arg构造:
#include <memory> #include <stdexcept> #include <concepts> #include <utility> #include <string> template<typename CreatedClass, typename Arg> requires std::constructible_from<CreatedClass, Arg> std::unique_ptr<CreatedClass> create_unique(Arg&& arg) { return std::make_unique<CreatedClass>(std::forward<Arg>(arg)); }
这样调用时只需要显式指定CreatedClass,Arg会自动推导:
auto x = create_unique<std::string>("Hello"); // 正常编译,Arg推导为const char(&)[6]
2. 用Concept简洁实现否定分支
你提到传统enable_if不够简洁,在C++20 Concepts中,直接用!std::constructible_from就能实现否定约束,完全不需要enable_if:
template<typename CreatedClass, typename Arg> requires (!std::constructible_from<CreatedClass, Arg>) std::unique_ptr<CreatedClass> create_unique(Arg&& arg) { throw std::runtime_error("CreatedClass is not constructible from arg."); }
现在测试不匹配的情况:
// auto x = create_unique<std::string>(42); // 触发第二个模板,抛出异常
为什么你的第二个尝试不对?
你之前把模板改成:
template<std::constructible_from<std::string> CreatedClass, typename Arg > std::unique_ptr<CreatedClass> create_unique( Arg && arg ) { ... }
这里的问题是约束硬编码了std::string,导致CreatedClass只能是可从std::string构造的类型,完全和Arg无关,违背了你的初衷——我们需要的是CreatedClass可从**推导出来的Arg**构造,所以必须用requires std::constructible_from<CreatedClass, Arg>这种依赖两个模板参数的约束。
额外补充:更简洁的写法(可选)
如果你想把两个分支合并成一个,也可以用if constexpr配合Concept检查,这种写法代码更紧凑:
template<typename CreatedClass, typename Arg> std::unique_ptr<CreatedClass> create_unique(Arg&& arg) { if constexpr (std::constructible_from<CreatedClass, Arg>) { return std::make_unique<CreatedClass>(std::forward<Arg>(arg)); } else { throw std::runtime_error("CreatedClass is not constructible from arg."); } }
内容的提问来源于stack exchange,提问作者Generic Name
相关产品推荐
相关产品推荐

