这个问题类似于: 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/