使用CRTP时如何避免错误?

Aby*_*byx 15 c++ crtp

使用CRTP有时我会编写如下代码:

// this was written first
struct Foo : Base<Foo, ...>
{
   ...
};

// this was copy-pasted from Foo some days later
struct Bar : Base<Foo, ...>
{
   ...
};
Run Code Online (Sandbox Code Playgroud)

并且很难理解出现了什么问题,直到我在调试器中跟踪代码并看到Bar的成员未被使用Base.

如何在编译时显示此错误?

(我使用MSVC2010,所以我可以使用一些C++ 0x功能和MSVC语言扩展)

Ale*_* C. 14

在C++ 0x中,您有一个简单的解决方案.我不知道它是否在MSVC10中实现.

template <typename T>
struct base
{
private:
    ~base() {}
    friend T;
};

// Doesn't compile (base class destructor is private)
struct foo : base<bar> { ... };
Run Code Online (Sandbox Code Playgroud)


Amn*_*non 10

你可以使用这样的东西:

template<class T> class Base {
protected:
   // derived classes must call this constructor
   Base(T *self) { }
};

class Foo : public Base<Foo> {
public:
   // OK: Foo derives from Base<Foo>
   Foo() : Base<Foo>(this) { }
};

class Moo : public Base<Foo> {
public:
   // error: constructor doesn't accept Moo*
   Moo() : Base<Foo>(this) { }
};

class Bar : public Base<Foo> {
public:
   // error: type 'Base<Bar>' is not a direct base of 'Bar'
   Bar() : Base<Bar>(this) { }
};
Run Code Online (Sandbox Code Playgroud)

  • @Alexandre:模板很详细. (3认同)