假设我有以下代码(C++):

template < class Td, class Ud, class Vd>
class Extractor
{
private:
  // some code here
public:
  // the class has functions to populate these vectors
  vector<Td* >    list_of_layers;
  vector<Ud* >    list_of_resistors;
  vector<Vd* >    list_of_nodes;
}

我希望施加这样的限制,即在实例化类Extractor的对象时用来替换Td,Ud和Vd的类分别是,始终是分别从类T,U和V派生的。可能吗?

最佳答案

您可以将type_traits,尤其是 enable_if is_base_of 结合使用,如下例所示:

#include <type_traits>

class BaseT {};
class BaseU {};
class BaseV {};

class DerivedT : public BaseT {};
class DerivedU : public BaseU {};
class DerivedV : public BaseV {};

template < class Td, class Ud, class Vd, class Enable = void>
class Extractor {
  static_assert(std::is_base_of<BaseT, Td>::value, "Template argument Td is not derived from BaseT");
  static_assert(std::is_base_of<BaseU, Ud>::value, "Template argument Ud is not derived from BaseU");
  static_assert(std::is_base_of<BaseV, Vd>::value, "Template argument Vd is not derived from BaseV");
};

template <class Td, class Ud, class Vd>
class Extractor<Td, Ud, Vd,
  typename std::enable_if<std::is_base_of<BaseT, Td>::value &&
                          std::is_base_of<BaseU, Ud>::value &&
                          std::is_base_of<BaseV, Vd>::value>::type> {

};

int main() {
  Extractor<DerivedT, DerivedU, DerivedV> dummy;
  Extractor<int, double, int> dummy2; // will fail to compile!!!
}

10-08 04:15