获取不依赖于模板化模板的 typedef class

Getting a typedef that does not depend on templates of a templated class

如果这是重复的,请提前致歉 - 我无法在这里找到我的答案。我有以下 class:

template <typename T>
class A {
public:
    using X = double;

private:
    T x;
};

现在,我想获得A<T>::X。可以不声明 T 吗?

我尝试了一些方法:

template <typename T>
using B = A<T>::X;

B e = 0;

但如果不指定模板,那显然是行不通的。

首先,定义B 别名模板需要关键字typename:

template <typename T>
using B = typename A<T>::X;

原因是X是一个从属名称:一个模板中的名称,带有尚未确定的参数T


因为 B 是别名 template 采用 type 模板参数 (即:T),必须提供该参数才能确定 X,例如,如果 Tint:

B<int> e = 0;

但是,请注意,这可能对每个 T 都无效或无法正常工作,因为 A class 模板可能已经 专门化 的名字 X 代表完全不同的东西。例如,X 可以表示 double 以外的类型:

template<>
class A<float> { 
public:
    using X = int; // not double!
};

名称 X 可以表示 数据成员 而不是类型:

template<>
class A<char> { 
public:
    static constexpr int X = 1; // not a type!
};

或者根本不存在:

template<> class A { /* not name X */};