2013-04-11 51 views
3

如何實現一個通過類型訪問元素而不是索引的元組類?沿着這條接口線的東西...類型索引元組

template<typename... T> 
class Tuple 
{ 
public: 
    Tuple(T... elements); 

    template<typename U> 
    U &get();    // U is one of the types in T... 
}; 
+0

如果使用相同類型兩次,該怎麼辦? – cppguy 2013-04-11 01:33:50

+0

該類將專門用於每種類型只使用一個元素的用例。 – jmegaffin 2013-04-11 01:34:55

+0

我以前做過 - 也許7年前 - 當時在提升郵件列表中提到過它,但沒有人看到它的實用性,我無法詳細解釋它。我使用了Alexandrescu的Loki圖書館,所以有一種方法可以做到這一點。如果你遇到困難,那麼你會有一個值得回答的正確問題; -P。很好的一點是,你可以通過索引號,訪問者模式等提供返回類型的設施。並且重新考慮你的擔心 - 你可以簡單地將值包裝到不同的類型中。 – 2013-04-11 01:57:39

回答

2

您可變參數模板實現Tuple的方式是這樣的

// Base case, Tuple<> 
template< typename... Ts > 
class Tuple { 
}; 

// recursive inheritance :D 
template< typename T, typename... Ts > 
class Tuple< T, Ts... > : private Tuple<Ts...> { 
public: 
    // we implement get() by checking wether element type match with 
    // request type 
    template< typename t > 
    typename std::enable_if< std::is_same< t, T >::value, t& >::type 
    get() { 
    return element; 
    } 

    // above is not enough since it only check this class's element type, 
    // we can check the rest of the tuple by inspecting its the parent classes. 
    template< typename t > 
    typename std::enable_if< !(std::is_same< t, T >::value), t& >::type 
    get() { 
     return Tuple<Ts...>::template get<t>(); // call its parent's get() 
               // ::template to shut compiler up 
    }  

private: 
    T element; 
}; 


Tuple< short, int, float, double, char, std::string > t; 
auto x = t.get<std::string>(); // x will be an empty string. 

這個假設沒有重複的元素類型,如果它會挑一個在最前面。 如果請求類型不在Tuple中,它將不會編譯。

+0

我從來沒有想過用遞歸繼承來解決這個問題。謝謝! – jmegaffin 2013-04-11 19:26:57