基于基类的专用成员函数

specialized member function based on baseclass

本文关键字:专用 成员 函数 基类 于基类      更新时间:2023-10-16

这个问题类似于:所有子类的 C++ 模板专用化而不是模板化函数,现在我有一个模板化类的成员函数,它需要根据类模板的基类做不同的事情

template<typename T>
class xyz
{
  void foo()
  {
     if (T is a subclass of class bar)
        do this
     else
        do something else
  }
}

我找不到一个易于理解的 boost::enable_if 教程,所以我无法为这个小修改获得正确的语法

您可以使用标签调度

template <typename T> class   xyz  
{
  public:
  void foo()  
  {
     foo( typename boost::is_base_of<bar,T>::type());
  }
  protected:
  void foo( boost::mpl::true_ const& )
  {
    // Something
  }
  void foo( boost::mpl::false_ const& )
  {
    // Some other thing
  }
};

请注意,标记调度通常比使用 enable_if 的 SFINAE 更好,因为enable_if在选择适当的重载之前需要线性数量的模板实例化。

在 C++11 中,您可以使用等效于这些 boost 元函数的 std:: 。