2009-04-15 57 views
1

我有一個模板函數fct,它使用了一些基於模板參數的複雜數據結構。它還調用一些輔助函數(模板化在同一類型上),這些函數位於獨立的helpers名稱空間中,並使用相同的複雜數據結構。模板化命名空間和typedef是非法的 - 解決方法?

namespace helpers { 
    template<class T> 
    void h1(const std::vector< std::vector< std::map<T, std::set<T> > > >& bar){ 
    // ... 
    } 
} 

template<class T> 
void fct(const std::vector< std::vector< std::map<T, std::set<T> > > >& bar){ 
    // ... 
    helpers::h1(bar); 
} 

現在我想讓它更漂亮,通過使用一個typedef的所有功能都可以使用:現在,因爲我們不能爲複雜類型,所有的功能都可以訪問使一個typedef變得非常難看。

一個模板typedef將是很好的,但它是不允許的:

template<class T> 
typedef std::vector< std::vector< std::map<T, std::set<T> > > > Bar; 

另一個解決方案是,我認爲,包所有這些功能在一個模板namespace,但是這不是在C不允許++是(我聽說它將在`C++ 0x'中...)。

我們當然有模板化的類,但請注意,我並不想讓用戶必須構造一個對象並調用成員函數。所以,我結束了使用的解決方法是使用一個模板類,所有成員函數都是static

template<class T> 
class All { 

    typedef std::vector< std::vector< std::map<T, std::set<T> > > > Bar; 

    static void fct(const Bar& bar){ 
    // ... 
    h1(bar); 
    } 

private: 
    static void h1(const Bar& bar){ 
    // ... 
    } 
}; 

我的問題是:這可能是一個有點搞笑,如果我的代碼大部分被組織成這樣?畢竟,只有靜態成員函數有很多類是有點不尋常的?是否有其他解決方案/解決方法使「模板化typedef」/「模板命名空間」成爲可能?

+0

重複http://stackoverflow.com/questions/251432/typedefs-for-templated-classes。 – 2009-04-16 07:44:45

回答

0

對於任何在-C後++ 11世界讀這樣的問題:用C++ 11,有一個模板typedef,這就是所謂的'使用」(這實際上可以完全替代的typedef在問題的情況下,這裏是我們做什麼:

template<class T> 
using Bar = std::vector< std::vector< std::map<T, std::set<T> > > >; 

namespace helpers { 
template<class T> 
void h1(const Bar<T>& bar){ 
    // ... 
} 
} 

template<class T> 
void fct(const Bar<T>& bar){ 
    // ... 
    helpers::h1(bar); 
} 

不錯,簡單。有點。