16

有时我会使用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语言扩展)

4

5 回答 5

17

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

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

// Doesn't compile (base class destructor is private)
struct foo : base<bar> { ... };
于 2011-08-30T07:35:50.490 回答
11

你可以使用这样的东西:

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) { }
};
于 2010-12-11T17:42:25.787 回答
2
template<typename T, int arg1, int arg2>
struct Base
{
    typedef T derived_t;
};

struct Foo : Base<Foo, 1, 2>
{
    void check_base() { Base::derived_t(*this); } // OK
};

struct Bar : Base<Foo, 1, 2>
{
    void check_base() { Base::derived_t(*this); } // error
};

此代码基于Amnon 的答案,但检查代码不包含派生类的名称,因此我可以复制并粘贴它而无需更改。

于 2010-12-12T19:40:01.737 回答
0

没有办法知道派生类型。您可以强制Foo从 派生Base<Foo>,但不能强制其他类也不能从该派生。

于 2010-12-11T16:57:49.360 回答
0

我可以使用宏

#define SOMENAMESPACE_BASE(type, arg1, arg2) type : Base<type, arg1, arg2>

但如果存在更好的解决方案,我不想使用宏。

于 2010-12-11T17:04:13.897 回答