2014-10-08 84 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中的坏习惯。