我正在我的一个库中创建一个面向元编程的小型模块,它使用 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/