【发布时间】:2021-06-01 23:08:32
【问题描述】:
我需要制作一个可能包含引用成员的包装类模板。我定义了复制和移动构造函数,其中包装类型的引用作为参数传递。如果类型不是引用,这一切都很好。但是如果是的话,type& 和type&& 都变成了左值引用,两个构造函数相互冲突。
我尝试使用requires 子句为类型不是引用的情况定义一组构造函数,而在类型不是引用的情况下定义另一组构造函数,如下面的代码所示。但是如果类型是引用,这不会编译! GCC 以某种方式将中毒的构造函数视为仍然有效。
我误解了requires 的工作原理,还是这是一个错误?下面是编译器资源管理器中的相同示例:https://godbolt.org/z/qjMxx3nGE
#include <type_traits>
template <typename T>
struct S {
using type = T;
type x;
S(const type& x) requires(!std::is_reference_v<type>)
: x(x) { }
S(type&& x) requires(!std::is_reference_v<type>)
: x(x) { }
S(type x) requires(std::is_reference_v<type>)
: x(x) { }
};
int main(int argc, char** argv) {
int i = 5;
S<int&> s(i);
return s.x;
}
【问题讨论】:
标签: c++ constructor reference c++20 c++-concepts