如何覆盖 'const T&' 和 'T&&' 的泛型函数,其中 T 可以作为引用?
How to override generic function for aguments `const T&` and `T&&` where T could be a reference?
我正在尝试在 C++ 中实现类似 Rust 的 Result<T,E>
类型,这是一个持有T
或E
值的联合。
它的一些构造函数是:
template <typename T, typename E>
Result<T,E>::Result(const T& value) : isOk(true), value(value) {}
template <typename T, typename E>
Result<T,E>::Result(T&& value) : isOk(true), value(std::move(value)) {}
它按照我所期望的T
和E
是非引用类型或指针工作,但如果任何基础类型是引用,则无法编译。例如:
MyType my_object;
Result<MyType&, AnyOtherType> result(my_object);
产生以下错误:
./result.h:46:5: error: multiple overloads of 'Result' instantiate to the same signature 'void (MyType &)'
Result(T&& value);
^
main.cpp:39:23: note: in instantiation of template class 'Result<MyType &, int>' requested here
Result<MyType&,int> result(object);
^
./result.h:37:5: note: previous declaration is here
Result(const T& value);
^
我知道这是因为引用折叠规则(&+ &&= &(:如果T
是MyType&
,那么T&
和T&&
都是MyType&
,因此这两个构造函数在这里具有相同的签名。
但是有什么好方法可以克服这个问题,并允许T
作为参考,同时仍然拥有const T&
和T&&
构造函数?
可以使用带有转发引用的模板化构造函数来涵盖这两种情况:
template<typename T>
struct Result {
template<typename... S>
Result(S&&... s) : t(std::forward<S>(s)...) {}
T t;
};
int i;
Result<int&> r1(i);
Result<int> r2(i);
关于std::expected<R, E>
提案的相关文件:
- http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4109.pdf
- http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0323r7.html
相关文章:
- 如何使用 swig 修改类构造函数以保留对其中一个构造函数参数的引用?
- 我如何创建一个函数(),其中一帕雷米特是映射
- 创建类类型的动态分配数组,其中类不得具有默认构造函数
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 为什么 std::get<T> 其中 T 是调用 constexpr 函数失败的结果?
- 如何创建一个函数来执行其中的其他函数
- 模板函数,其中一个参数需要专门化,而另一个不需要
- 构造函数模板参数推导,其中 std::function 作为参数
- 在两个类上协调析构函数,其中一个类需要首先清理
- 模板函数,其中模板参数类型取决于函数参数
- 不带初始值设定项的构造函数列表,其中包含带有已删除构造函数的对象
- 用C++编写一个函数,其中客户端决定从类运行哪个函数
- openCv 3中的等效polyfit函数在其中
- 当其中一个函数未编译时,函数重载查找如何工作?
- 带有映射的 Lambda 函数,其中键是元组,值是双精度
- 如何覆盖 'const T&' 和 'T&&' 的泛型函数,其中 T 可以作为引用?
- C函数调用C 成员函数 - 其中C代码与C编译器编译
- 将一个函数传递给另一个函数,其中参数的数量可以不同C++
- 将函数指针作为参数传递,其中函数指针的参数是函数的函数指针参数的子项
- 从 Fortran 调用 C 函数,其中 C 函数名称最初是从 C 传入的