我有由模板设置的类型和大小的缓冲区。
我使用 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;
}
Run Code Online (Sandbox Code Playgroud)
与静态类成员不同,需要从类名而不是实例名访问类型名。尽管如此,一切都没有丢失,您可以使用decltype从实例中获取类名,然后您可以访问类型名,如
decltype(b)::value_type foo = 'a';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |