【问题标题】:Inherit dependent typedef without using struct不使用 struct 继承依赖 typedef
【发布时间】:2019-09-17 21:44:52
【问题描述】:

我有一些这样的代码:

#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 结构的情况下从地图继承?

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

谢谢,

【问题讨论】:

    标签: c++ templates inheritance c++14


    【解决方案1】:

    您可以依赖具有注入类名的模板。在map&lt;...&gt;的专业化里面,当前的专业化可以简单的引用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 是注入的类名。为了方便使用,别名抓住了它。

    【讨论】:

    • 太棒了。谢谢你。还有一个问题,我假设 typedef 而不是 using? 是正确的
    • @Tomas - 你可以使用 c 风格的类型别名 typedef typename Container::map Base; 我自己只是更喜欢 using 语法,所以我回答了这个问题。
    • 哎呀,我试的时候拼错了(我这里有不同的名字)。对不起,打扰你。再次感谢:D
    猜你喜欢
    • 2021-02-12
    • 2010-10-01
    • 2015-06-23
    • 2013-04-01
    • 2023-03-28
    • 2017-08-08
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多