typedef 为模板模板的别名

typedef to alias of template template

我有一个特征 class,AttributeTraits,它使用智能指针模板 class,MySmartPointer :

template<typename T>
class MySmartPointer {};

template<template <typename> class SP = MySmartPointer>
struct AttributeTraits {
    template <typename T>
    using SmartPointerClass = SP<T>;
};

AttributeTraits 使用别名来保存它拥有的模板 class。 现在,我需要获得特征 class 的属性 class 将使用指向智能指针 class 的 typedef/alias,例如:

template <typename Traits>
struct Attribute {
    typedef typename Traits::SmartPointerClass<int> SmartPointerType; // error: non-template 'SmartPointerClass' used as template
    using SmartPointerType2 = typename Traits::SmartPointerClass<int>; // error: expected ';' before '<' token
    using SmartPointerType3 = Traits::SmartPointerClass<int>; // error: non-template 'SmartPointerClass' used as template
};

但是上述 3 个选项中的 none 有效...

这是您的依赖 class 是模板的情况之一,因此您在定义别名时必须使用笨拙的 template 语法:

template <typename Traits>
struct Attribute {
    typedef typename Traits::template SmartPointerClass<int> SmartPointerType;
    using SmartPointerType2 = typename Traits::template SmartPointerClass<int>; 
    using SmartPointerType3 = typename Traits::template SmartPointerClass<int>; 
};

有关何时需要 template 关键字的说明,请参阅 this documentation

The template disambiguator for dependent names
Similarly, in a template definition, a dependent name that is not a member of the current instantiation is not considered to be a template name unless the disambiguation keyword template is used or unless it was already established as a template name

This Whosebug Answer 也提供了一些很好的背景。