c++ - 基于基类的特殊成员函数

标签 c++ boost template-specialization enable-if

这个问题类似于: c++ template specialization for all subclasses 现在我有一个模板类的成员函数,而不是模板函数,它需要根据类模板的基类做不同的事情

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
  }
};

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

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

关于c++ - 基于基类的特殊成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360756/

相关文章:

c++ - 仅专门化嵌套模板

c++ - 当不支持可变模板参数时,如何为元组专门化类模板?

C++非常简单的网络触发器(库,代码)

c++ - 重载 operator<< 以处理字符串

c++ - 在 C++ 中使用 unordered_set 作为 unordered_map 的键时出现的问题

visual-studio-2010 - boost 库 1.47.1 构建 'lib' 前缀导致 LNK1104 错误

c++ - boost::archive::binary_oarchive 如何处理枚举?

c++ - 规避模板特化

c++ - 为什么要有一个指向指针的指针(int **a)?

python - RNN 在 TensorFlow 中的实时实现