使用 CRTP 时如何获取模板参数的大小?
在 VC++10 中,以下示例失败并出现错误 C2027:“使用未定义类型 'X'”。然而 g++ 4.6 编译得很好。
template<class T>
class C
{
static const size_t size = sizeof(T);
};
class X : public C<X> { };
那么哪一个是正确的呢?我该如何做才能使其在主流编译器上运行?
但这并不是什么大问题,因为 VC++ 仍然允许在 C 的成员函数中使用 sizeof(T)。我只需要重复一些很烦人的长类型定义。
编辑: 我意识到我的例子很糟糕,因为我真正想做的是使用大小作为编译时间常量,这样:
template<size_t size> class C2 { };
template<class T>
class C
{
typedef C2<sizeof(T)> A;
};
class X : public C<X> { };
两个编译器都拒绝这个,所以我认为这可能是不可能的,但就像我说的,我仍然可以在内部使用 sizeof功能。我只是希望不必在每个函数中重复 typedef 。
template<size_t size> class C2 { };
template<class T>
class C
{
void foo() { typedef C2<sizeof(T)> A; }
};
class X : public C<X> { };
In VC++10 the following example fails with error C2027: "use of undefined type 'X'". However g++ 4.6 compiles it just fine.
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.
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. I was just hoping I wouldn't have to repeat the typedef inside every function.
template<size_t size> class C2 { };
template<class T>
class C
{
void foo() { typedef C2<sizeof(T)> A; }
};
class X : public C<X> { };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态成员无法在类本身中初始化,因为类型
T
正在定义,并且尚未完成。但是,您可以在类外部将其初始化为:
它应该可以正常编译: http://ideone.com/6sNgN
The static member cannot be initialized in the class itself, because the type
T
is being defined, and is not complete yet.However, you can initialize it outside the class as:
It should compile fine: http://ideone.com/6sNgN