Search code examples
c++type-traits

Constant integer trait in simple class


Given the following simple declaration, is it possible to give the class a constant integer trait specifying the number of components (2 in this case)? Vec3 and Vec4 would have 3 and 4 respectively. I just want this as a compile-time constant for instantiating other templates in various ways. It doesn't have to be there at runtime.

template<class T>
struct Vec2
{ 
    typedef T value_type;
    typedef unsigned index_type;

    struct 
    {
        T x, y; 
    };
};

Solution

  • The most portable way would be to add an enum constant:

    template<class T> struct Vec2
    {
        enum { num_components = 2 };
    };
    template<class T> struct Vec3
    {
        enum { num_components = 3 };
    };
    

    Then just use V::num_components where needed.

    If you are into C++11 then you can also use static const int num_components = 2; instead of an anonymous enum, but if you need compatibility with old compilers, then the enum idiom will save you some headaches.