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++编译器会报错:
block 引用>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 ?
关于c++ - std::pair<> 的模板成员必须具有 const 复制构造函数。如何实现该约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35553822/