c++ - 避免具有继承的类之间重复 typedef

标签 c++ templates inheritance typedef c++14

我正在我的一个库中创建一个面向元编程的小型模块,它使用 List<Ts...>用于编译类型列表操作的类。

我专攻List使用空参数包来专门化某些元函数或类型定义。然而,许多 typedef 或元函数在 List<> 中都有相同的实现。和List<Ts...> .

示例:

template<typename...> struct List;

template<> struct List<>
{
    using Type = List<>;        // Redundant
    using Tuple = std::tuple<>; // Redundant
    // ...other redundant typedefs...

    template<typename TList> using Append = TList; // Non-redundant
    // ...other non-redundant typedefs...
};

template<typename... Ts> struct List
{
    using Type = List<Ts...>;        // Redundant
    using Tuple = std::tuple<Ts...>; // Redundant
    // ...other redundant typedefs...

    template<typename TList> 
    using Append = AppendImpl<Type, TList>; // Non-redundant
    // ...other non-redundant typedefs...
};

如您所见,List<> 之间的一些 typedef 是多余的和List<Ts...> .

我想做的事情与此类似:

template<typename...> struct List;

template<typename... Ts> struct ListBase
{
    using Type = List<Ts...>;
    using Tuple = std::tuple<Ts...>;
};

template<> struct List<> : public ListBase<>
{
    template<typename TList> using Append = TList;
};

template<typename... Ts> struct List : public ListBase<Ts...>
{
    template<typename TList> 
    using Append = AppendImpl<Type, TList>;
};

// The lines below should be valid code:
using X0 = List<>::Type;
using X1 = List<int, char, int>::Type;
using X2 = List<>::Tuple;
using X3 = List<char, char>::Tuple;
using X4 = List<>::Append<List<int, float>>;
using X5 = List<int>::Append<List<float>>;

不幸的是,typedefs do not propagate from the base class to the derived one 。正如 sbabbi 在评论中所说,您必须使用完整限定名称来引用基类中的 typedef,这对于 List<...> 来说是 Not Acceptable 。我正在设计的类(class)。

有什么方法可以在不诉诸宏的情况下避免这种重复吗?

最佳答案

如何以相反的方式进行操作,将所有常见内容保留在 List 主模板中,然后使用单独的模板,专门针对空参数包,以处理不同的部分例如附加

template<typename... Ts> struct ListAppend
{
    template<typename TList> 
    using Append = AppendImpl<Ts..., TList>;
};

template<> struct ListAppend<>
{
    template<typename TList> 
    using Append = TList;
};

template<typename... Ts> struct List 
{
    using Type = List<Ts...>;
    using Tuple = std::tuple<Ts...>;

    template<typename TList> 
    using Append = typename ListAppend<Ts...>::Append<TList>;
};

现在您只需对不相同的部分使用专门化,并且不要重复任何内容。

关于c++ - 避免具有继承的类之间重复 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28767814/

相关文章:

c++ - 为什么 C++ 编译器不区分同名的继承公共(public)方法和继承私有(private)方法?

c++ - CRTP继承中的基类 "friending"是否也会影响子类?

c++ - 为什么 std::ends 会导致字符串比较失败?

c++ - 具有动态共享内存的模板化 CUDA 内核

C++ Template meta-magic, template call-site qualification deduction机制

c++ - 从 boost::program_options 值中输入 un-erasure

c++ - 计算 C++17 中 POD 类型的普通数组的字段?

c++ - vector<int> 上的 memset

templates - 如何在 Flask 中呈现错误页面,不会导致请求的蓝图出现错误循环?

c# - 使用 JavaScript/jQuery 从另一个类调用 C# 方法