模板值的公共访问
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
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 我们可以访问一个不存在的联盟的成员吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 我的简单if-else语句是如何无法访问的代码
- 从C++dll访问C#中的一行主要参数
- 概念TS检查忽略私有访问修饰符
- 访问被拒绝后,c++中的故障保护代码
- 在c++中访问int到类对象的映射时出错
- 我想访问std::unique_ptr中的一个特定元素
- 为什么示例代码访问IUnknown中已删除的内存
- C++:无法访问声明的受保护成员
- 通过指向指针数组的指针访问子类的属性
- 如何使用单独文件中的派生类访问友元函数对象