簡體   English   中英

如何從元組中包含的數據構造對象?

[英]How to construct an object from data packed in a tuple?

假設我有

struct SomeType {
  template<typename... Args>
  SomeType(Args... args);
  // ...
};

template<typename... Args> std::tuple<Args> data;   // syntax correct?

並且想要從tuple data打包的參數值構造一個新對象SomeType 我怎樣才能做到這一點?

unique_ptr<SomeType> p = new SomeType( data ??? );  // how?

編輯1我認為問題很清楚,但Kevin不同意......我想調用SomeBody的構造函數,將tuple data包含的值作為參數。 知道了,凱文?


編輯2我認為一個問題是一個問題,但凱文再次不同意。 為了他的好處,這是一個用例:我想動態構造線程局部對象,每個對象由前面提供的一些參數的線程構造。 考慮

template<typename Object>
class thread_specific
{
public:
  // default constructor: objects will be default constructed
  thread_specific();
  // objects will be copy constructed from specimen provided
  thread_specific(Object const&specimen);
  // objects will be constructed from arguments provided
  template<typename... Args>
  thread_specifiv(Args... args);
  // return thread-specific object; objects are constructed only when needed
  Object& local_object();
};

(例如,通過std::map<std::thread::id,unique_ptr<Object>> )。 現在,如果用戶使用第3個構造函數創建了一個全局thread_specific<>對象,則必須以某種方式存儲參數並在需要時將其提供給Object的構造函數,即在第一次調用thread_specific<>::local_object()時每個std::thread

使用index_sequence解壓縮std::tuple (或std::pairstd::array或支持元組接口的任何其他內容):

#include <utility>
#include <tuple>

template <typename Tuple, std::size_t... Inds>
SomeClass help_make_SomeClass(Tuple&& tuple, std::index_sequence<Inds...>)
{
    return SomeClass(std::get<Inds>(std::forward<Tuple>(tuple))...);
}

template <typename Tuple>
SomeClass make_SomeClass(Tuple&& tuple)
{
    return help_make_SomeClass(std::forward<Tuple>(tuple),
        std::make_index_sequence<std::tuple_size<Tuple>::value>());
}

std::index_sequencestd::make_index_sequence將在C ++ 1y中。 如果找不到定義它們的標頭,可以使用以下方法:

template <std::size_t... Inds>
struct index_sequence {
    static constexpr std::size_t size()
    { return sizeof...(Inds); }
};

template <std::size_t N, std::size_t... Inds>
struct help_index_seq {
    typedef typename help_index_seq<N-1, N-1, Inds...>::type type;
};

template <std::size_t... Inds>
struct help_index_seq<0, Inds...> {
    typedef index_sequence<Inds...> type;
};

template <std::size_t N>
using make_index_sequence = typename help_index_seq<N>::type;

實例,在C ++ 11模式下: http//coliru.stacked-crooked.com/a/ed91a67c8363061b

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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