C++:重载的模板别名

C++: Overloaded template alias

本文关键字:别名 重载 C++      更新时间:2023-10-16

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

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>;
}

如果您想编写一个奇特的条件转发器,那么您必须不仅仅使用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中的坏习惯。

将大多数内容添加到std中也是非法的,只有极少数例外,如std::hash专门化。