Search code examples
c++using

c++ is it possible to gain access to an alias (using) from an instance


I have Buffer with type and size set by template.

I store the type with a using, and allow access to the size with a method.

Everything's fine with the size. Now, can I gain access to the type (like in line Buffer<char,6>::value_type val = 'z'; ) but from an instance of Buffer?

I tried the commented syntax, but failed:

//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;
}

Solution

  • Unlike static class members, type names need to be accessed from the class name, not the instance name. All is not lost though, you can use decltype to get the class name from an instance and then you can access the type name like

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