如何正确地特化与其父级类型相同的模板化静态常量成员

发布于 2024-12-22 22:44:11 字数 616 浏览 4 评论 0原文

如果标题不清楚,代码应该有助于澄清:

// .h file    
template<class T> class DF_Vector3
{
public:

    T x, y, z;

    static const DF_Vector3 ZERO;

    DF_Vector3() {}
    DF_Vector3( T F );
    DF_Vector3( T X, T Y, T Z );
};

typedef DF_Vector3<DF_FLOAT> DF_Vector3F;

// .cpp file
template<> const DF_Vector3F DF_Vector3F::ZERO( 0.0f, 0.0f, 0.0f ); // ERROR: Explicit specialization of 'ZERO' after instantiation

编译器随后引用了引用 DF_Vector3F::ZERO 的另一个位置,并指出:“此处首先需要隐式实例化。”

Visual Studio 2010 编译器似乎并不介意这一点。然而,Apple 的 CLANG (LLVM) 编译器不喜欢它(它是抱怨的)。

有办法解决这个问题吗?谢谢。

If the title isn't clear, the code should help clarify:

// .h file    
template<class T> class DF_Vector3
{
public:

    T x, y, z;

    static const DF_Vector3 ZERO;

    DF_Vector3() {}
    DF_Vector3( T F );
    DF_Vector3( T X, T Y, T Z );
};

typedef DF_Vector3<DF_FLOAT> DF_Vector3F;

// .cpp file
template<> const DF_Vector3F DF_Vector3F::ZERO( 0.0f, 0.0f, 0.0f ); // ERROR: Explicit specialization of 'ZERO' after instantiation

The compiler subsequently cites another location where DF_Vector3F::ZERO is referenced and states: "Implicit instantiation first required here."

The Visual Studio 2010 compiler doesn't seem to mind this. However, Apple's CLANG (LLVM) compiler does not like it (it's the one complaining).

Is there a way to fix this? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦言归人 2024-12-29 22:44:11

您不能在静态成员的定义中使用 typedef,因为当您拥有 typedef 时,类模板已经实例化,之后您无法显式地特化其成员。

您应该这样做:

//general case
template<class T> 
const DF_Vector3<T> DF_Vector3<T>::ZERO;

//specialization
template<> 
const DF_Vector3<DF_FLOAT> DF_Vector3<DF_FLOAT>::ZERO(0.0f, 0.0f, 0.0f);

//after that define the typedef
typedef DF_Vector3<DF_FLOAT> DF_Vector3F; //after

演示:http://ideone.com/AMWMC

You cannot use the typedef in the definition of the static members, because by the time you have a typedef, the class template is already instantiated, after which you cannot explicity specialized its member(s).

You should do this:

//general case
template<class T> 
const DF_Vector3<T> DF_Vector3<T>::ZERO;

//specialization
template<> 
const DF_Vector3<DF_FLOAT> DF_Vector3<DF_FLOAT>::ZERO(0.0f, 0.0f, 0.0f);

//after that define the typedef
typedef DF_Vector3<DF_FLOAT> DF_Vector3F; //after

Demo : http://ideone.com/AMWMC

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文