C++:重载模板别名

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

最佳答案

如果你想写一个花哨的条件转发器,你将不得不不只是使用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 添加任何不是来自 的“面向用户”的接口(interface)>std 库。您支持的东西应该符合 std 规范。

为非std 扩展提供nonstdstd_ext 命名空间。这会导致现有代码在移植时无法编译或工作,并且会避免让您的程序员用户养成关于 std 中的内容的坏习惯。

将大多数东西添加到 std 中也是非法的,只有少数异常(exception),例如 std::hash 特化。

关于C++:重载模板别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267319/

相关文章:

c++ - 使用除法运算符时未得到预期结果

c++ - Project Euler #23,在程序中找不到问题

c++ - 为什么编译器需要尾随返回类型?

node.js - 在Mint17上为Node.js构建插件

c++ - 为什么这不会为链接器生成重复的符号?

c++ - 如何弄清楚为什么 ssh session 有时不退出?

c++ - 继续基于范围的 for 循环不会重新触发断点吗?

c++ - 使用模板元编程计算数据编译时间

c++ - 返回 vector 比通过引用传递慢吗?

c++ - 静态转换 : Conversion function templates - are they really working?