![](/img/trans.png)
[英]How to initialize an std::array<T, 2> where T is non-copyable and non-default-constructible?
[英]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的副本構造函數,並且如果可能,也不使用move-constructor。 如果可能,首選C ++ 03解決方案。
您可以為您的類型添加分段構造器嗎? 如果是這樣,您可以創建一個可怕的宏來解包並委托一個元組:
#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
的類,在其構造函數中接受元組 boost::tuple<boost::scoped_ptr<A>, boost::scoped_ptr<B>>(new A(...), new B(...))
(1)的工作量很大,(2)代碼重復且容易出錯,(3)現在涉及突然進行分配。
您可以使用以下內容:
tuple<A,B> tup(A(true, 42), B('*', 4.2));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.