目前正在编写一个专门的标准库,我发现在特定情况下这对我来说是必要的:
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
扩展提供nonstd
或std_ext
命名空间。这会导致现有代码在移植时无法编译或工作,并且会避免让您的程序员用户养成关于 std
中的内容的坏习惯。
将大多数东西添加到 std
中也是非法的,只有少数异常(exception),例如 std::hash
特化。
关于C++:重载模板别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267319/