模板值的公共访问

Public Access of Template Value

本文关键字:访问      更新时间:2023-10-16

考虑以下内容:

template<int T>
class Test {
public:
    constexpr static int A = T;
};
int main(int argsc, char** args) {
    std::cout << Test<2>::T << std::endl; // Option 1
    std::cout << Test<2>::A << std::endl; // Option 2
}

为什么选项1不能编译?看起来static constexpr A只是一个额外的步骤。是T不能公开使用吗?

是否有一种更干净的方式来获得T,而不是通过创建一个像A这样的公开访问的成员?

为什么选项1不能编译?

因为模板形参只是形参的名字。您可以重命名它们,即:

template <class T> struct X;
// refers to same X
template <class U> struct X { ... };
// still the same X
template <class V>
void X<V>::foo() { ... };

与允许在声明和定义之间以不同的方式命名函数形参的原因相同。要求模板参数的名称在类模板中自动可见意味着它必须在一开始就被固定。

是否有比创建像上面的a这样的可公开访问的成员更干净的方法来获得T ?

通常的做法是创建可公开访问的成员。或者,您可以创建一个外部特征:
template <class T> struct X { using type = T; }; // internal
template <class > struct get_type;
template <class T> struct get_type<X<T>> { using type = T; }; // external