【问题标题】:specialized member function based on baseclass基于基类的特殊成员函数
【发布时间】:2012-04-28 05:04:03
【问题描述】:

这个问题类似于: 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 教程。所以我无法为这个小修改获得正确的语法

【问题讨论】:

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


    【解决方案1】:

    您可以使用标签调度

    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::。

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 1970-01-01
      • 2012-10-08
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多