如何为自定义boost::outcome_v2::result模板别名添加CTAD支持?
解决boost::outcome_v2::result模板别名的CTAD支持问题
问题的核心在于:C++不支持为模板别名编写类模板实参推导(CTAD)指南。你的my_result只是boost::outcome_v2::result<result_t, my_error>的别名,并非独立的类模板,因此无法直接为它添加推导指南。而直接使用boost::outcome_v2::result能正常CTAD,是因为Boost库已经为这个类模板预定义了推导指南。
要让my_result支持CTAD,你需要将它从模板别名改为继承自boost::outcome_v2::result的类模板,然后为这个新类模板编写推导指南。以下是具体实现:
实现方案
#include <boost/outcome.hpp> class my_error { // 你的自定义错误类型实现 }; // 将my_result改为继承自boost::result的类模板 template <typename T> struct my_result : boost::outcome_v2::result<T, my_error> { // 继承基类的所有构造函数,保留原boost::result的全部功能 using boost::outcome_v2::result<T, my_error>::result; }; // 为my_result编写推导指南:从boost::result<T, my_error>推导my_result<T> template <typename T> my_result(boost::outcome_v2::result<T, my_error>) -> my_result<T>; // 可选:添加直接从值或错误构造的推导指南 // 支持从my_error构造出my_result<void> my_result(my_error) -> my_result<void>; // 支持从任意T构造出my_result<T> template <typename T> my_result(T) -> my_result<T>; // 测试用例 boost::outcome_v2::result<int, my_error> some_function() { return 42; } int main() { // 现在可以正常CTAD推导了 const my_result res = some_function(); return res.value(); }
原理说明
- 类模板替代模板别名:通过让
my_result成为继承自boost::outcome_v2::result<T, my_error>的类模板,我们获得了一个可以添加推导指南的独立类模板。 - 继承构造函数:
using boost::outcome_v2::result<T, my_error>::result;让my_result复用基类的所有构造逻辑,无需重新实现。 - 推导指南匹配:编写的推导指南会告诉编译器,当遇到从
boost::outcome_v2::result<T, my_error>构造my_result时,推导模板参数为T;额外的指南则支持直接从值或错误对象构造的场景。
这样修改后,你就能像使用原生boost::outcome_v2::result一样,对my_result使用CTAD了。
内容的提问来源于stack exchange,提问作者CJCombrink
相关产品推荐
相关产品推荐

