2014-10-08 81 views
0

目前編程專業標準庫,而且我發現,在特定的情況下,這是必要的我:C++:重載模板別名

namespace std 
{ 
    // key, value 
    template<class K, class V> 
    using vector_map = other_namespace::vector_map<K, V>; 

    // key, value, compare 
    template<class K, class V, class C> 
    using vector_map = other_namespace::vector_map<K, V, C>; 
} 

它,然而,無法正常工作。不奇怪。但是,我有什麼選擇來實現這一目標? 我曾想過使用預處理器,但我想知道你們的想法。

我希望能夠選擇性別名模板類到另一個名稱空間,如果可能的話。

解決方案(在我的情況)是增加而不是有幾個usings默認值:

namespace std 
{ 
    // key, value, compare 
    template<class K, class V, class C = default_value> 
    using vector_map = other_namespace::vector_map<K, V, C>; 
} 
+1

你想達到什麼目的? 'other_namespace :: vector_map'也不是「重載」的,它只有'C'的默認值。那也能爲你工作嗎? – Cameron 2014-10-08 22:12:34

+0

我想要具有相同的功能,就好像模板類本身與我的using語句位於同一名稱空間中一樣。在此示例中,vector_map位於other_namespace中,但我想將特定變體移動到std :: namespace:類型。 – gonzo 2014-10-08 22:15:01

+0

是的,謝謝!我只是將默認值添加到我的模板別名,並解決它。再次感謝 – gonzo 2014-10-08 22:20:02

回答

2

如果你想寫一個奇特的條件轉發,你必須不只是使用using

template<class A, class B, class... C> 
struct vector_map_helper { 
    using type = other_namespace::vector_map<A,B>; 
}; 
// specialize for 3: 
template<class A, class B, class C> 
struct vector_map_helper<A,B,C> { 
    using type = other_namespace::vector_map<A,B,C>; 
}; 
template<class A, class B, class C, class D, class...Z> 
struct vector_map_helper<A,B,C,D, Z...>; // error 4 or more 

template<class A, class B, class... C> 
using vector_map = typename vector_map_helper<A,B,C...>::type; 

一般來說,即使您正在實現std庫,你應該避免接口加入您的std不來自std庫中的任何「面向用戶」。而你所支持的東西應該符合std的規格。

對於非std擴展名,有nonstdstd::ext命名空間。這既會使現有代碼在移植時無法編譯或工作,也會避免訓練程序員用戶在std中的壞習慣。