如何在编译时检测基类的模板参数(对于错误)?

Gea*_*phy 7 c++ inheritance templates derived-class

我一直在使用奇怪的重复模板模式一般代码如下所示:

template <typename T> void genericFunction(T &);
template <typename T> struct Functionality {
    void genericMethod() {
        genericFunction(*((T *)this)) ;
    }
};

struct Klass : public Functionality<Klass> {};

void main() {
    Klass obj ;
    obj.genericMethod();
}

template <> void genericFunction<Klass>(Klass &obj) {
    //do stuff with Klass &obj here
}
Run Code Online (Sandbox Code Playgroud)

我今天遇到了一个错误,这花了我大约90分钟的拔毛,这个错误是由于我的基类继承声明使用了一个不正确的模板参数引起的,有点像这样:

struct Klass : public Functionality<SomeOtherKlass> {}; //SomeOtherKlass wrong!!!
Run Code Online (Sandbox Code Playgroud)

我想增强我的代码,以便检测派生类和基类模板参数之间的这种不匹配(运行时,编译时,任何时候:)),这甚至可能吗?,谢谢.

Geo*_*che 3

genericMethod()您可以使用 Boost 或 C++11 功能来断言关系:

BOOST_STATIC_ASSERT(( boost::is_base_of<Functionality<T>, T>::value ));
Run Code Online (Sandbox Code Playgroud)

...尽管这是假设另一个类也不是派生自的Functionality<T>

另一种方法是在测试构建中运行时断言关系:

template <typename T> struct Functionality {
#ifdef TEST_BUILD
    virtual ~Functionality() {}
#endif
    void genericMethod() {
#ifdef TEST_BUILD
        assert(dynamic_cast<T*>(this));
#endif
        genericFunction(*((T *)this)) ;
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,测试在构造函数和析构函数中不起作用