C ++:重载的模板别名

时间:2014-10-08 22:11:13

标签: c++ c++11 c++14

目前正在编写一个专门的标准库,我发现在特定情况下,这对我来说是必要的:

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>;
}
然而,它确实不起作用。不奇怪。但我有什么选择来实现这一目标? 我曾考虑使用预处理器,但我想知道你们的想法。

如果可能的话,我希望能够将模板类别选择性地转换为另一个名称空间。

解决方案(在我的情况下)是添加默认值而不是使用多个:

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 个答案:

答案 0 :(得分: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规范。

为非nonstd扩展名提供std::extstd命名空间。这将使现有代码无法编译或在移植时工作,并且它将避免培训程序员用户对std中的内容的不良习惯。