我一直在使用
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内不起作用