【问题标题】:C++: Overloaded template aliasC++:重载的模板别名
【发布时间】:2022-01-24 06:03:04
【问题描述】:

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

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

【问题讨论】:

  • 你想达到什么目的? other_namespace::vector_map 也没有“重载”,它只是默认为 C。这对你也有用吗?
  • 我希望具有与模板类本身与我的 using 语句所在的命名空间相同的功能。在此示例中,vector_map 位于 other_namespace,但我想将特定变体移至std:: 命名空间: 类型。
  • 好的,谢谢!我刚刚将默认值添加到我的模板别名中,这就解决了。再次感谢
  • 我不明白你为什么把这个声明放到namespace std?你即将产生“未定义的行为”,例如见here
  • 我知道,而且我还在考虑这一切。这适用于没有定时器中断的操作系统,因此无论如何都可能没有(完整的)标准库。我目前使用std 只是因为它会为用户所熟悉。最终这不是我的决定。

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


【解决方案1】:

如果你想编写一个花哨的条件转发器,你不能只使用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 专业化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多