C++:重载的模板别名
C++: Overloaded template alias
目前正在编程一个专门的标准库,我发现在特定情况下这对我来说是必要的:
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
扩展,请使用nonstd
或std_ext
命名空间。这既会使现有代码在移植时无法编译或工作,也会避免让程序员用户养成std
中的坏习惯。
将大多数内容添加到std
中也是非法的,只有极少数例外,如std::hash
专门化。
相关文章:
- 继承函数的重载解析
- 部分定义/别名模板模板参数
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 如何在C++20中创建模板别名的推导指南
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- C++重载解析总是诉诸别名 arg. 而不是其他人作为对所有人都有效的 arg.
- 类型别名和运算符<<使用 ostream_iterator 重载会导致无效操作数
- 所有重载方法的别名
- 重载以 typedef 别名作为参数的成员方法
- C++:重载的模板别名