首页 > 解决方案 > pair 的两个构造函数几乎相同,为什么不产生构建错误?

问题描述

在pair的实现中,接下来的两个构造函数只是前缀不同:explicit。这两个成员模板功能几乎相同。

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

那么为什么结果不同呢?

标签: c++templatesoverloading

解决方案


下面的类不使用上面的模板。

该错误是由于您两次描述相同的构造函数而引起的。

explicit只是如何调用构造函数的限制,而不是允许重载的签名更改。


推荐阅读