如何定义模板类的静态const变量 [英] How to define a static const variable of a template class

查看:103
本文介绍了如何定义模板类的静态const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用向上,向右和向前的预定义静态常量创建矢量类,因为在所有情况下它们都应该相同。

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

这会导致语法错误。

推荐答案

应为(全部位于标头中(如果要从定义中拆分声明,可以使用.inl或.hxx)):

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

演示

这篇关于如何定义模板类的静态const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆