Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unclear typedef type

I came across this code and was wondering what it means. But even after some 15 minutes of looking at it does not make sense to me.

template< typename T >
struct Vector4 {
    typedef T Vector4<T>::* const vec[4];
    static const vec constVec;

    //just to have some member instances of T
    T member1, member2, member3, member4;
};

So what is the type of constVec? Please do not just repeat the typedef but explain in common language.

My notes so far:

  • Why are there two types (T and Vector4<T>), is this a function pointer?
  • What does ::* mean? Take everything from the scope of Vector4?
  • Is it a const pointer array? But why the :: then?
like image 415
Nobody moving away from SE Avatar asked Mar 21 '12 12:03

Nobody moving away from SE


1 Answers

constVec is an array of 4 constant pointers to the members of the Vector4<T> class which are of type T

Note: The members aren't constant, the pointers themselves are.

First, since these are constant pointers, you need to initialize them in the constructor: (I've just noticed the static qualifier, so it has to be initialized outside the class, but if it weren't static, you'd need to do that in the initialization list.)

template< typename T >
struct Vector4 {
    typedef T Vector4<T>::* const vec[4];
    static const vec constVec;

    //just to have some member instances of T
    T member1, member2, member3, member4;

};

template<typename T>
const typename Vector4<T>::vec Vector4<T>::constVec = {&Vector4::member1,&Vector4::member2,&Vector4::member3,&Vector4::member4};

int main() {
    Vector4<int> v;
    for(int i=0; i<4; i++) {
        (v.*Vector4<int>::constVec[i]) = 5;
    }
return 0;
}
like image 180
enobayram Avatar answered Nov 09 '22 21:11

enobayram