c ++是否有可能从实例访问别名(使用)
c++ is it possible to gain access to an alias (using) from an instance
我有类型和大小由模板设置的缓冲区。
我使用 using
存储类型,并允许使用方法访问大小。
大小合适。现在,我可以访问该类型吗(如在线
Buffer<char,6>::value_type val = 'z';
) 但来自 Buffer 的一个实例?
我尝试了注释语法,但失败了:
//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;
}
与静态 class 成员不同,类型名称需要从 class 名称而不是实例名称访问。不过,一切都没有丢失,您可以使用 decltype
从实例中获取 class 名称,然后您可以访问类型名称,如
decltype(b)::value_type foo = 'a';
我有类型和大小由模板设置的缓冲区。
我使用 using
存储类型,并允许使用方法访问大小。
大小合适。现在,我可以访问该类型吗(如在线
Buffer<char,6>::value_type val = 'z';
) 但来自 Buffer 的一个实例?
我尝试了注释语法,但失败了:
//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;
}
与静态 class 成员不同,类型名称需要从 class 名称而不是实例名称访问。不过,一切都没有丢失,您可以使用 decltype
从实例中获取 class 名称,然后您可以访问类型名称,如
decltype(b)::value_type foo = 'a';