10

I'm trying to make a vector class with predefined static constants for up, right and forward because these should be the same in all cases. How should this be defined and is it even possible?

I'm trying to do something like this:

template <class T> class vec3
{
public:
    vec3(T x = 0, T y = 0, T z = 0) :
        x(x),
        y(y),
        z(z)
    {
    }

    static const vec3<T> right;
    static const vec3<T> up;
    static const vec3<T> forward;

    T x, y, z;
}

cpp:

#include "vec3.h"

template <typename T>
const vec3<T>::right(1, 0, 0);

template <typename T>
const vec3<T>::up(0, 1, 0);

template <typename T>
const vec3<T>::forward(0, 0, 1);

This results in a syntax error.

Duckdoom5
  • 716
  • 7
  • 27
  • 1
    It should be `static const vec3 right;` in class. – Jarod42 Dec 01 '15 at 17:40
  • BTW, I doubt that you want the definition in .cpp as it continue to depend on `T`. – Jarod42 Dec 01 '15 at 17:41
  • @Jarod42 how would it be defined in the header? If I try `= vec3(1,0,0);`'vec3::right': a static data member with an in-class initializer must have non-volatile const integral type` – Duckdoom5 Dec 01 '15 at 17:43
  • You likely want `template const vec3 vec3::right(1, 0, 0);` in the header! –  Dec 01 '15 at 17:45
  • @DieterLücking That gives a compiler error with right(, , ) – Duckdoom5 Dec 01 '15 at 17:47
  • @Duckdoom5 compiles fine with g++ after fixing: `error: expected ‘;’ after class definition` –  Dec 01 '15 at 17:52

2 Answers2

13

It should be (all in header (you may use .inl or .hxx if you want to split declaration from definition)):

template <class T> class vec3
{
public:
    vec3(T x = 0, T y = 0, T z = 0) :
        x(x),
        y(y),
        z(z)
    {
    }

    static const vec3 right;
    static const vec3 up;
    static const vec3 forward;

    T x, y, z;
};

template <typename T> const vec3<T> vec3<T>::right(1, 0, 0);
template <typename T> const vec3<T> vec3<T>::up(0, 1, 0);
template <typename T> const vec3<T> vec3<T>::forward(0, 0, 1);

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302
2
template <class T> class vec3
{
public:
    vec3(T x = 0, T y = 0, T z = 0) :
        x(x),
        y(y),
        z(z)
    {
    }

    static const vec3 right;
    static const vec3 up;
    static const vec3 forward;

    T x, y, z;
};


template <typename T>
const vec3<T> vec3<T>::right(1, 0, 0);

template <typename T>
const vec3<T> vec3<T>::up(0, 1, 0);

template <typename T>
const vec3<T> vec3<T>::forward(0, 0, 1);
SergeyA
  • 61,605
  • 5
  • 78
  • 137