如何避免使用CRTP时出现错误? [英] How to avoid errors while using CRTP?
本文介绍了如何避免使用CRTP时出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 CRTP 有时候我会写下这样的代码:
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, ...>
{
...
};
这很难理解错误,直到我在调试器中跟踪代码,在 Base
中未使用。
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?
(我使用MSVC2010,所以我可以使用一些C ++ 0x功能和MSVC语言扩展)
(I use MSVC2010, so I can use some C++0x features and MSVC language extensions)
推荐答案
在C ++ 0x中有一个简单的解决方案。我不知道它是否在MSVC10中实现。
In C++0x you have a simple solution. I don't know whether it is implemented in MSVC10 however.
template <typename T>
struct base
{
private:
~base() {}
friend T;
};
// Doesn't compile (base class destructor is private)
struct foo : base<bar> { ... };
这篇关于如何避免使用CRTP时出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文