c++ - std::pair<> 的模板成员必须具有 const 复制构造函数。如何实现该约束

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

C++11 标准要求 std::pair<> 的模板成员必须有 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]' declared to take const reference, but implicit declaration would take non-const:

            constexpr pair(const pair&) = default

这是因为我们将 A 的复制构造函数声明为非常量。如果我们改变A(A&){}成为A(const A&){} ,或者我们删除 -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或不

最佳答案

//how do you know whether the constructor of T1 and T2 are const ?

您使用 std::is_copy_constructible .

关于c++ - std::pair<> 的模板成员必须具有 const 复制构造函数。如何实现该约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35553822/

相关文章:

c++ - Linux 的 _bstr_t 的极简实现

c++ - 错误 C4716 : must return a value, 由实际返回值的函数抛出

c++ - 如何在多文件项目中正确使用模板?

c++ - 如何将 unique_ptr 与 operator new 一起使用

c++ - 为什么选择非常量版本而不是类的 const 版本?

c++ - 奇数 cpp 读取访问冲突

c++ - lambda 函数 c++ 按值捕获重置其值,为什么?

c++模板函数来展平 vector 的 vector

c++ - 抽象类和 move 语义

c++ - 编写函数以在容器的子集中执行操作