How to define a static const variable of a template class

帅比萌擦擦* 提交于 2019-12-10 13:19:58

问题


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.


回答1:


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




回答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);


来源:https://stackoverflow.com/questions/34026555/how-to-define-a-static-const-variable-of-a-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!