首页 > 解决方案 > 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;
}

标签: c++using

解决方案


与静态类成员不同,类型名需要从类名而不是实例名中访问。一切都没有丢失,您可以使用decltype从实例中获取类名,然后您可以访问类型名称,例如

decltype(b)::value_type foo = 'a';

推荐阅读