使用CRTP时如何避免错误?
使用 CRTP 有时我会编写如下代码:
// this was written first
struct Foo : Base<Foo, ...>
{
...
};
// this was copy-pasted from Foo some days later
struct Bar : Base<Foo, ...>
{
...
};
并且很难理解出了什么问题,直到我在调试器中跟踪代码并看到 Bar 的成员未在 Base
中使用。
如何在编译时显示此错误?
(我使用MSVC2010,所以我可以使用一些C++0x功能和MSVC语言扩展)
Using CRTP sometimes I write a code like this:
// this was written first
struct Foo : Base<Foo, ...>
{
...
};
// this was copy-pasted from Foo some days later
struct Bar : Base<Foo, ...>
{
...
};
And it's very difficult to understand what goes wrong, until I trace code in debugger and see that Bar's members aren't used in Base
.
How to reveal this error at compile time?
(I use MSVC2010, so I can use some C++0x features and MSVC language extensions)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 C++0x 中,您有一个简单的解决方案。我不知道它是否在MSVC10中实现。
In C++0x you have a simple solution. I don't know whether it is implemented in MSVC10 however.
你可以使用这样的东西:
You can use something like this:
此代码基于 Amnon 的回答,但检查代码不包含派生类的名称,因此我可以复制并粘贴它而无需更改。
This code is based on Amnon's answer, but checking code don't contains name of derived class, so I can copy and paste it without changes.
无法知道派生类型。您可以强制要求
Foo
派生自Base
,但不能强制要求没有其他类也从中派生。There's no way of knowing the deriving type. You could enforce that
Foo
derived fromBase<Foo>
, but you can't enforce that no other classes also derive from that.我可以使用宏
,但如果存在更好的解决方案,我不想使用宏。
I can use a macro
but I don't want to use macros if better solution exists.