Sunday, 27. August 2017 07:42AM
#Piecewise Construction 逐块式构造

Class pair<> 提供三个构造函数,用以初始化first和second
~~~
namespace std {
template <typename T1, typename T2>
stuct pair {

pair(const T1& x, const T2& y);
template<typename U, typename V> pair(U&& x, V&& y);
template<typename… Args1, typename… Args>
pair(piecewise_construct_t, tuple first_args, tuple second_args); ... }; } ~~~ 第三个构造函数传递使用两个tuple分别将其元素传递first和second的构造函数去构造实例。为了强迫执行这样的行为, 你必须传递std::piecewise_construct作为额外的第一实参。 ==Example== ~~~ // util/pair1.cpp

#include #include #include using namespace std;

class Foo {
public:
Foo (tuple<int,float>) {
cout«“Foo::Foo(tuple)”«endl;
}
template Foo (Args... args) { cout<<"Foo::Foo(args...)"<<endl; } };

int main() {
//create tuple t;
tuple<int,float> t(1, 2.22);

//pass the tuple as a whole to the constructor of Foo:
pair<int, Foo> p1(42,t);

//pass the elements of tuple to the constructor of Foo;
pair<int,Foo> p2 (piecewise_construct, make_tuple(42), t); } ~~~ 这个程序有以下输出 ~~~ Foo::Foo(tuple) Foo::Foo(args...) ~~~