簡體   English   中英

如何初始化不可默認構造的不可復制對象的元組?

[英]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之前的版本中,我不知道這是可能的-您根本沒有委派構造函數。 您必須:

  1. 編寫自己的tuple的類,在其構造函數中接受元組
  2. 在您的類型中添加元組構造函數,以顯式初始化與非元組版本相同的內容
  3. 具有可單參數構造的元組類型,例如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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM