【发布时间】:2016-06-03 21:21:40
【问题描述】:
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]' 声明采用 const 引用,但隐式声明将采用非 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
【问题讨论】:
标签: c++ templates c++11 std-pair