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

我一直在使用 Curiously recurring template pattern一般代码如下所示:
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
}

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

struct Klass : public Functionality<SomeOtherKlass> {}; //SomeOtherKlass wrong!!!

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

解决方法

你可以断言关系,例如genericmethod()使用Boost或C 11特性:
BOOST_STATIC_ASSERT(( boost::is_base_of<Functionality<T>,T>::value ));

…虽然假设其他类不是从功能< 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)) ;
    }
};

请注意,测试在constructors and destructors内不起作用

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...