继承依赖类型定义而不使用结构

Inherit dependent typedef without using struct

本文关键字:结构 依赖 类型 定义 继承      更新时间:2023-10-16

我有一些这样的代码:

#include <string>
#include <map>
typedef std::less<std::string> Comparator; // simplified
typedef std::allocator<std::pair<const std::string, int>> Allocator; // simplified
template<class T>
struct Base
{
typedef std::map<std::string, T, Comparator, Allocator> type; // VERY long declaration in the actual code
};
template<class T>
struct Container : public Base<T>::type
{
Container(Allocator a) : Base<T>::type(Comparator(), a) {}
};
int main()
{
Allocator a;
Container<int> c(a);
}

尽管声明在我的实际代码中更花哨一些。

使用Base结构,这样我就不必多次编写长映射声明。

我想知道是否有更好的方法可以在没有任何Base结构的情况下从地图继承?

请不要使用宏。我希望以某种方式将 typedef 隐藏在容器类本身或类似的东西中。

谢谢

您可以依赖具有注入类名的模板。在map<...>的专业化内部,目前的专业化可以简单地用map来指代。并且该注入的类名也可用于派生类(和类模板(。但由于它是依赖的,因此需要一个限定名称。它看起来比听起来简单,以下是将别名滚动到Conatiner的方法:

template<class T>
struct Container : public std::map<std::string, T, Comparator, Allocator>
{
using Base = typename Container::map;
Container(Allocator a) : Base(Comparator(), a) {}
};

Container::map是注入的类名。别名抓住它以方便使用。