专用类中的模板别名

template alias in specialized class

本文关键字:别名 专用      更新时间:2023-10-16

下面的代码给出了错误(在我定义测试的行中):

错误C2143:语法错误:缺少";"在'<'之前注意:请参阅对正在编译的类模板实例化"ptc::Produce"的引用错误C4430:缺少类型说明符-假定为int。注意:C++不支持默认的int

有人知道为什么会发生这种事吗?编译器是VC2015 CTP1。

编辑:错误必须发生在模板解析的第1阶段,因为即使我从未实例化类Produce也会发生。

namespace OrderPolicy
{
    struct Unordered {};
    struct Ordered {};
};
template <typename TOrderPolicy>
struct OrderManager {};
template<>
struct OrderManager<OrderPolicy::Unordered>
{
    template <typename TItem>
    using item_t = TItem;
};
template<>
struct OrderManager<OrderPolicy::Ordered> 
{
    template <typename TItem>
    using item_t = TItem*;
};
template<typename TOrderPolicy>
struct Produce : public OrderManager<TOrderPolicy>
{
    item_t<int> test;
    //using item_type = item_t<int>;
};

第2版:当我将代码的最后一部分更改为时,它就起作用了

struct Produce : public OrderManager<OrderPolicy::Ordered>
{
    item_t<int> test;
    //using item_type = item_t<int>;
};
item_t<int> test;

它从基类中命名一个依赖模板类型。在这种情况下,您需要告诉编译器item_t是基类中的一个类型,并且它是一个模板。

直接的方法是使用typenametemplate:

typename OrderManager<TOrderPolicy>::template item_t<int> test;

正如你所看到的,这将很快变得不可读。我会制作一些本地别名以使代码更整洁:

using Base = OrderManager<TOrderPolicy>;
using item_type = typename Base::template item_t<int>;
item_type test;

您必须使用:

typename OrderManager<TOrderPolicy>::template item_t<int>

代替:

item_t<int> test;

哇,学习从未停止。直到现在,我还没有看到在这个上下文中使用的关键字模板。