2010-10-29 42 views
3

鑑於下面的代碼是否有更好的方法來糾正它,而不是重複typename std::iterator_traits<T>::iterator_category兩次?不重複用作模板參數的類型

template<class T, class T2> 
struct foo : 
    bar< 
     foo<T, T2>, typename 
     std::conditional< 
      std::is_same<typename 
       std::iterator_traits<T>::iterator_category, //Repeated 
       std::random_access_iterator_tag 
      >::value, 
      std::bidirectional_iterator_tag, typename 
      std::iterator_traits<T>::iterator_category  //Repeated 
     >::type 
    > 
{} 

回答

3

分割它(像它應該是這樣):

// put in detail namespace/file or something in real code 
template<class T, class T2> 
struct foo_base 
{ 
    typedef foo<T, T2> foo_type; 
    typedef typename std::iterator_traits<T>::iterator_category category_type; 

    static const bool random_access = std::is_same<category_type, 
             std::random_access_iterator_tag>::value; 
    typedef typename std::conditional<random_access, 
             std::bidirectional_iterator_tag, 
             category_type>::type tag_type; 

    typedef bar<foo_type, tag_type>::type base_type; 
} 

template<class T, class T2> 
struct foo : 
    foo_base<T, T2>::base_type 
{}; 

即使沒有重複一下,你還是應該把它分解以保持基本類型邏輯與實際繼承基本類型分開。

+0

謝謝。回想起來似乎很明顯。 – Jon 2010-10-29 15:56:19

+0

@Jon:幸運的是,你只需要學習一次。 :) – GManNickG 2010-10-29 15:58:11

0

你可以typedef它:

typedef std::iterator_traits<T>::iterator_category it_cat; 
+2

這是可編譯的嗎?你打算把這個代碼放在哪裏?請注意'T'是一個模板參數。 – Vlad 2010-10-29 15:45:53

+0

@Vlad,我們可以說: typedef std :: iterator_traits :: iterator_category it_cat; – Sheen 2010-10-29 15:48:24

+0

@Sheen:那沒有意義。你仍然需要在'foo'和基類列表之間放置'typedef'。 – GManNickG 2010-10-29 15:54:13

相關問題