简体   繁体   English

使用CRTP时如何获取模板参数的大小?

[英]How to get the size of a template argument when using CRTP?

In VC++10 the following example fails with error C2027: "use of undefined type 'X'". 在VC ++ 10中,以下示例失败,错误为C2027:“使用未定义的类型'X'”。 However g++ 4.6 compiles it just fine. 但是,g ++ 4.6可以很好地进行编译。

template<class T>
class C
{
    static const size_t size = sizeof(T);
};

class X : public C<X> { };

So which one is right? 那么哪一个是对的? And how would I do this so that it works on mainstream compilers? 我将如何做才能使其在主流编译器上运行?

It's not a huge deal though, cause VC++ still allows sizeof(T) inside member functions of C. I just have to repeat some long type definitions which is annoying. 不过,这并不是什么大问题,因为VC ++仍允许C的成员函数内使用sizeof(T)。我只需要重复一些很烦人的长类型定义即可。

EDIT: I realize my example was bad because what I really wanted to do was to use the size as a compile time constant, in this way: 编辑:我意识到我的例子很糟糕,因为我真正想做的就是以这种方式使用大小作为编译时间常数:

template<size_t size> class C2 { };

template<class T>
class C
{
   typedef C2<sizeof(T)> A;
};

class X : public C<X> { };

Both compilers reject this so I assume it's probably not possible, but like I said I can still use sizeof inside functions. 两个编译器都拒绝这样做,所以我认为这可能是不可能的,但是就像我说的那样,我仍然可以在函数内部使用sizeof。 I was just hoping I wouldn't have to repeat the typedef inside every function. 我只是希望我不必在每个函数中重复typedef。

template<size_t size> class C2 { };

template<class T>
class C
{
    void foo() { typedef C2<sizeof(T)> A; }
};

class X : public C<X> { };

The static member cannot be initialized in the class itself, because the type T is being defined, and is not complete yet. 静态成员不能在类本身中初始化,因为类型T正在定义中,并且尚未完成。

However, you can initialize it outside the class as: 但是,您可以在类外部将其初始化为:

template<class T>
class C
{
    static const size_t size;
};

template<typename T>
const size_t C<T>::size = sizeof(T); //initialization of the static member

It should compile fine: http://ideone.com/6sNgN 它应该可以正常编译: http : //ideone.com/6sNgN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM