gpt4 book ai didi

c++ - 不使用struct继承依赖的typedef

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:39 24 4
gpt4 key购买 nike

我有这样的代码:

#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 结构,这样我就不必多次编写冗长的 map 声明。

我想知道是否有更好的方法可以在不使用任何 Base 结构的情况下从 map 继承?

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

谢谢,

最佳答案

您可以依赖具有注入(inject)类名的模板。内专业map<...> ,当前的专业可以简单地用map来表示.并且该注入(inject)的类名也可用于派生类(和类模板)。但由于它是从属的,所以它需要一个合格的名称。它看起来比听起来简单,下面是如何将别名滚动到 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是注入(inject)的类名。别名会捕获它以方便使用。

关于c++ - 不使用struct继承依赖的typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57982453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com