微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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内不起作用

原文地址:https://www.jb51.cc/c/117775.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐