如何初始化非默认构造的不可复制对象的元组?
How to initialize a tuple of non-default-constructible not-copyable objects?
给定一些类带有参数化的构造函数,例如:
class A
{
public:
A(bool b, int i) { /*...*/ }
private:
A(const A&) {}
};
class B
{
public:
B(char c, double d) { /* ... */ }
private:
B(const B&) {}
};
如何正确初始化这样的元组类?
boost::tuple<A,B> tup( /* ??? */ );
不使用 A 或 B 的复制构造函数,如果可能,也不使用移动构造函数。如果可能,首选 C++03 解决方案。
您可以使用以下内容:
tuple<A,B> tup(A(true, 42), B('*', 4.2));
你能为你的类型添加一个分段构造函数吗?如果是这样,您可以创建一个可怕的宏来解包并委托一个元组:
#define CONSTRUCT_FROM_TUPLE(CLS) \
template <class... Ts> \
CLS(std::tuple<Ts...> const& tup) \
: CLS(tup, std::index_sequence_for<Ts...>{}) \
{ } \
\
template <class Tuple, size_t... Is> \
CLS(Tuple const& tup, std::index_sequence<Is...> ) \
: CLS(std::get<Is>(tup)...) \
{ }
并将其添加到您的类型中:
struct A {
A(bool, int ) { }
A(const A& ) = delete;
CONSTRUCT_FROM_TUPLE(A)
};
struct B {
B(char, double ) { }
B(const B& ) = delete;
CONSTRUCT_FROM_TUPLE(B)
};
并传入元组:
std::tuple<A, B> tup(
std::forward_as_tuple(true, 42),
std::forward_as_tuple('x', 3.14));
C++11 之前的版本,我不知道这是可能的——您根本没有委托构造函数。您必须:
- 编写你自己的
tuple
-like class 在其构造函数中接受元组
- 将元组构造函数添加到您的类型中,以显式初始化与非元组版本相同的东西
- 有一个可构造单参数类型的元组,例如
boost::tuple<boost::scoped_ptr<A>, boost::scoped_ptr<B>>(new A(...), new B(...))
(1) 工作量很大,(2) 代码重复且容易出错,(3) 现在不得不突然进行分配。
给定一些类带有参数化的构造函数,例如:
class A
{
public:
A(bool b, int i) { /*...*/ }
private:
A(const A&) {}
};
class B
{
public:
B(char c, double d) { /* ... */ }
private:
B(const B&) {}
};
如何正确初始化这样的元组类?
boost::tuple<A,B> tup( /* ??? */ );
不使用 A 或 B 的复制构造函数,如果可能,也不使用移动构造函数。如果可能,首选 C++03 解决方案。
您可以使用以下内容:
tuple<A,B> tup(A(true, 42), B('*', 4.2));
你能为你的类型添加一个分段构造函数吗?如果是这样,您可以创建一个可怕的宏来解包并委托一个元组:
#define CONSTRUCT_FROM_TUPLE(CLS) \
template <class... Ts> \
CLS(std::tuple<Ts...> const& tup) \
: CLS(tup, std::index_sequence_for<Ts...>{}) \
{ } \
\
template <class Tuple, size_t... Is> \
CLS(Tuple const& tup, std::index_sequence<Is...> ) \
: CLS(std::get<Is>(tup)...) \
{ }
并将其添加到您的类型中:
struct A {
A(bool, int ) { }
A(const A& ) = delete;
CONSTRUCT_FROM_TUPLE(A)
};
struct B {
B(char, double ) { }
B(const B& ) = delete;
CONSTRUCT_FROM_TUPLE(B)
};
并传入元组:
std::tuple<A, B> tup(
std::forward_as_tuple(true, 42),
std::forward_as_tuple('x', 3.14));
C++11 之前的版本,我不知道这是可能的——您根本没有委托构造函数。您必须:
- 编写你自己的
tuple
-like class 在其构造函数中接受元组 - 将元组构造函数添加到您的类型中,以显式初始化与非元组版本相同的东西
- 有一个可构造单参数类型的元组,例如
boost::tuple<boost::scoped_ptr<A>, boost::scoped_ptr<B>>(new A(...), new B(...))
(1) 工作量很大,(2) 代码重复且容易出错,(3) 现在不得不突然进行分配。