2016-05-16 98 views
0

我需要一些幫助實現我的程序設計。所以,我有我想要的一切在它的元組,從這個電話將元組傳遞給幫助類

auto t1 = getMyTuple(); 

創建,但我想打一個輔助類,這樣我可以超載< <操作,這樣,當我打電話

std::cout << my_tuple_helper; 

它會打印出每一件事。

我有一個輔助類,但我不知道怎麼去T1到它..它看起來像

template<typename... Args> 
class my_tuple_helper 
{ 
    public: 
    std::tuple<Args...> my_tup; 

    my_tuple_helper(std::tuple<Args... t) 
    { 
    my_tup = t; 
    } 

//or 

    my_tuple_helper(Args... args) 
    { 
    my_tup = std::tuple<Args...>(args...); 
    } 

}; 

擁有這兩個構造函數是我不知道如何通過模板創建時的問題

auto t1 = getMyTuple(); 
my_tuple_helper<???> mth(t1); 

我有東西,編譯看起來像這樣

template<typename T> 
class my_tuple_helper 
{ 
    public: 
    T my_tup; 

    my_tuple_helper(T t) 
    { 
    my_tup = t; 
    } 
}; 
:如果它的類型是汽車類的對象

,我可以打電話給

auto t1 = getMyTuple(); 
my_tuple_helper<decltype(t1)> mth(t1); 

但我不喜歡這樣的事實是t可以是任何東西,我寧願有一個std ::元組my_tup不是一件T my_tup(我甚至不知道這會工作) 。

有沒有人有任何想法,我可以得到一個std ::元組存儲到一個自動對象,我的助手類,使我可以作爲一個std ::元組對象(在類中)訪問它。

預先感謝您

回答

1

您可以針對

template<typename... Args> 
my_tuple_helper<Args...> 
make_my_tuple_helper(const std::tuple<Args...>& tup) 
{ 
    return my_tuple_helper<Args...>(tup); 
} 

做一個功能,使用它

auto t1 = getMyTuple(); 
auto mth = make_my_tuple_helper(t1); 
+0

謝謝我從來沒有想過這個! – user2770808

1

通常的方式做到這一點是讓其中推導一個工廠方法你的模板參數。所以,你會做my_tuple_helper這個樣子的:

template<typename... Args> 
class my_tuple_helper 
{ 
    public: 
    std::tuple<Args...> my_tup; 

    my_tuple_helper(std::tuple<Args...> t) 
     : my_tup {std::move(t)} 
    { } 
}; 

然後寫一個工廠方法是這樣的:

template <typename... Args> 
my_tuple_helper<Args...> 
make_tuple_helper (const std::tuple<Args...>& t) 
{ 
    return { t }; 
} 

Live Demo

然後,如果你想輸出你的元組,你能做到這一點的一個電話,像這樣:

auto t1 = getMyTuple(); 
std::cout << make_tuple_helper(t1); 
+0

非常感謝,你的演示非常有用,並解決了我的問題:) – user2770808