pair的两个构造函数几乎相同,为什么不生成构建错误?
the two constructors of pair is almost the same, why not generate build error?
在pair的实现中,接下来的两个构造函数仅在前缀上有所不同:显式。 两个成员模板函数几乎相同。
template<class _Other1,
class _Other2,
enable_if_t<conjunction_v<
is_constructible<_Ty1, _Other1>,
is_constructible<_Ty2, _Other2>,
is_convertible<_Other1, _Ty1>,
is_convertible<_Other2, _Ty2>
>, int> = 0>
constexpr pair(_Other1&& _Val1, _Other2&& _Val2)
_NOEXCEPT_COND(is_nothrow_constructible_v<_Ty1, _Other1>
&& is_nothrow_constructible_v<_Ty2, _Other2>)
: first(_STD forward<_Other1>(_Val1)),
second(_STD forward<_Other2>(_Val2))
{ // construct from moved values
}
template<class _Other1,
class _Other2,
enable_if_t<conjunction_v<
is_constructible<_Ty1, _Other1>,
is_constructible<_Ty2, _Other2>,
negation<conjunction<
is_convertible<_Other1, _Ty1>,
is_convertible<_Other2, _Ty2>>>
>, int> = 0>
constexpr explicit pair(_Other1&& _Val1, _Other2&& _Val2)
_NOEXCEPT_COND(is_nothrow_constructible_v<_Ty1, _Other1>
&& is_nothrow_constructible_v<_Ty2, _Other2>)
: first(_STD forward<_Other1>(_Val1)),
second(_STD forward<_Other2>(_Val2))
{ // construct from moved values
}
但是当我编写我的测试示例如下时:
class A
{
public:
template<typename T1,typename T2>
A(T1 a,T2 b){}
template<typename T1,typename T2>
explicit A(T1 a,T2 b){}
};
构建错误显示为:
Error C2535 'A::A(T1,T2)': member function already defined
那么为什么结果不同呢?
下面的类不使用上面的模板。
此错误是由您两次描述同一构造函数的事实引起的。
explicit
只是限制构造函数的调用方式,而不是允许重载的签名更改。
区别不仅在于explicit
的使用,模板参数中还有一个不同的条件来enable_if_t
:
// Constructor 1 Constructor 2
enable_if_t<conjunction_v< enable_if_t<conjunction_v<
is_constructible<_Ty1, _Other1>, is_constructible<_Ty1, _Other1>,
is_constructible<_Ty2, _Other2>, is_constructible<_Ty2, _Other2>,
is_convertible<_Other1, _Ty1>, negation<conjunction<
is_convertible<_Other2, _Ty2> is_convertible<_Other1, _Ty1>,
is_convertible<_Other2, _Ty2>>>
如果所有四个条件都为真,则调用第一个构造函数(_Ty1/2
可以从_Other1/2
构造,_Other1/2
可以转换为_Ty1/2
(。仅当后两个条件为假时,才调用第二个条件。
explicit
本身不会影响重载解析,它只是意味着构造函数只能在直接初始化上下文中使用。
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 为什么不能通过在错误输入后设置 std::cin.clear() 来使用 std::cin?
- C++:如果括号为空,为什么不抛出错误对象?
- pair的两个构造函数几乎相同,为什么不生成构建错误?
- 语法检查器指出一些我不知道为什么的错误
- 我的程序运行良好,可以复制对象,但是当我使用复制分配(=)时,它仍然可以正常运行.为什么不给错误
- C++ 为什么不使用已删除的函数时编译器失败并显示错误代码 C2280
- 为什么这个错误如此不清楚
- Box2D不寻常的错误.为什么 0阻止错误
- 为什么不会导致分段错误
- 为何分配给基本呼叫的结果,为什么不是编译器错误
- 为什么在使用初始化语法时不调用转换运算符,为什么 clang 错误消息看起来是错误的
- 在c++中定义类中的方法时,为什么不存在多个定义错误呢
- 当第三方代码中没有警告时,为什么不将所有警告视为错误?
- 为什么致命错误C1083:不能打开源代码文件(vc++)
- Snprintf:当第二个参数超过目标内存时,为什么不报告错误
- 为什么不将操作符重载标记为内联会导致重复定义错误?
- C++实例化结构错误,为什么不允许这样做?