【问题标题】:How to verify that template class is derived from a given class at compilation time?如何在编译时验证模板类是从给定类派生的?
【发布时间】:2011-05-05 18:52:48
【问题描述】:

我想知道,是否有任何优雅的方法(如this)来检查模板参数是否派生自给定类? 一般来说:

template<class A, class B>
class MyClass
{
    // shold give the compilation error if B is not derived from A
    // but should work if B inherits from A as private
}

另一个question 中提供的解决方案仅在 B 作为公共继承自 A 时才有效:

class B: public A

但是,我宁愿没有这样的约束:

class A{};
class B : public A{};
class C : private A{};
class D;
MyClass<A,B> // works now
MyClass<A,C> // should be OK
MyClass<A,D> // only here I need a compile error

提前致谢!!!

【问题讨论】:

    标签: c++ templates inheritance compiler-errors


    【解决方案1】:

    你可以试试我在这里说的: C++: specifying a base class for a template parameter 在静态断言中(C++0x 或 BOOST_STATIC_ASSERT)

    template<class A, class B> 
    class MyClass 
    { 
      static_assert( boost::is_base_of<A,B>::value );
    }
    

    【讨论】:

      【解决方案2】:

      从任何东西私有继承是一个实现细节。

      在重构和代码分析期间,如果无法对外部功能进行此类检测,我会更高兴...

      【讨论】:

        猜你喜欢
        • 2021-11-22
        • 1970-01-01
        • 2016-11-08
        • 2011-08-25
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 2018-12-14
        相关资源
        最近更新 更多