c++ - c++ 是否可以从实例访问别名(使用)
问题描述
我有由模板设置的类型和大小的缓冲区。
我用 a 存储类型using
,并允许使用方法访问大小。
一切都很好,大小合适。Buffer<char,6>::value_type val = 'z';
现在,我可以通过 Buffer 实例访问类型(如 in line
)吗?
我尝试了注释语法,但失败了:
//g++ 5.4.0
#include <iostream>
using namespace std;
template<typename T, int N>
struct Buffer {
using value_type = T;
constexpr int size() { return N; }
T tab [N];
Buffer(T val) { for(int _i; _i<N ; _i++){ tab[_i]=val; } }
void p(){ for(int _i; _i<N ; _i++){ cout << tab[_i] << " "; } }
};
int main()
{
Buffer<char,6> b( 'x' );
cout << "there will be " << b.size() << " values : ";
b.p();
cout << endl;
Buffer<char,6>::value_type val = 'z';
// b.value_type val = 'z'; // error: invalid use of ‘using value_type = char’
// b::value_type val = 'z'; // error: ‘b_c’ is not a class, namespace, or enumeration
cout << val << endl;
}
解决方案
与静态类成员不同,类型名需要从类名而不是实例名中访问。一切都没有丢失,您可以使用decltype
从实例中获取类名,然后您可以访问类型名称,例如
decltype(b)::value_type foo = 'a';
推荐阅读
- timestamp - Java - 将 OffsetDateTime/时间戳转换为 RegularTimePeriod 以绘制时间序列图 (Jfreechart)
- docker - 在本地网络中获取大量无法访问的主机和网络错误
- android - 无论如何,我们可以创建像 dev 和 prod 这样的 Kotlin Multiplatform 构建文件的风味版本吗?
- python - 如何在 FLASK REST API 中使用 MQTT 概念?
- spring-security - 如何在没有身份验证的情况下允许 Spring Security 中的某些端点?
- datatable - 是否可以使用箭头光标调整大小,例如浏览器对 vuetify 数据表的调整大小操作?
- python - 如何在 python 字典中按顺序获取数据?
- python - 使用 Factory Boy SelfAttribute + relativedelta
- maven - Maven: 传输文件 XXX 失败返回码是: 501 , ReasonPhrase:HTTPS 必需
- css - 不按所有列定义 Grid 的高度