【问题标题】:template member of std::pair<> must have const copy constructor. How to implement that constraintstd::pair<> 的模板成员必须具有 const 复制构造函数。如何实现该约束
【发布时间】:2016-06-03 21:21:40
【问题描述】:

C++11 标准要求std::pair&lt;&gt; 的模板成员必须有const 复制构造函数。否则,它将无法编译。(来自C++ 标准库一书,Nicolai M. Josuttis。)。因此,如果下面的代码违反 c++11 标准,则无法编译:

class A{
    int i;
public:
    A(){}
    A(A&){} 
};

int main(){
    pair<int, A> p;
}

使用-std=c++11,G++ 编译器会报错:

constexpr std::pair<_t1 _t2>::pair(const std::pair<_t1 _t2>&) [with _T1 = int; _T2 = A]' 声明采用 const 引用,但隐式声明将采用非 const:

            constexpr pair(const pair&) = default

那是因为我们将 A 的复制构造函数声明为非常量。如果我们将A(A&amp;){} 更改为A(const A&amp;){},或者我们删除-std=c++11 标志,一切都会好起来的。

我的问题是,该约束是如何实现的?我看不出语言本身没有支持让我们深入了解模板参数T。我的意思是,声明如下:

template<typename T1, typename T2>
class pair{
    ...
    //how do you know whether the constructor of T1 and T2 are const ?
    ...
};

怎么知道T1和T2的构造函数是不是const

【问题讨论】:

    标签: c++ templates c++11 std-pair


    【解决方案1】:

    //怎么知道T1和T2的构造函数是否为const?

    你使用std::is_copy_constructible

    【讨论】:

    • is_copy_constructible() 检查是否存在复制构造函数。它不检查参数是否为const
    • is_copy_constructible 检查类型是否可由const T&amp; 构造。严格来说,答案应该是检查std::is_constructible&lt;T1, T1&amp;&gt;std::is_constructible&lt;T1, const T1&amp;&gt;的组合;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多