模板类限制

template class restriction

本文关键字:      更新时间:2023-10-16

我想知道是否有任何方法来限制使用自定义条件的模板生成代码,在我的情况下,我想函数foo只有在模板类T被类bar继承(类似这样)时才被调用

template <class T:public bar> void foo()
{
    // do something
}

您可以通过使用"替代失败不是错误" (SFINAE)来限制T:

template <typename T>
typename std::enable_if<std::is_base_of<bar, T>::value>::type foo()
{
}

如果T不是从bar派生的,则函数模板的专门化将失败,并且在重载解析时不会考虑它。std::enable_ifstd::is_base_of是即将发布的c++ 0x修订版中添加的c++标准库的新组件。如果你的编译器/标准库实现还不支持它们,你也可以在c++ TR1或Boost.TypeTraits中找到它们。

是的,可以使用以下技术(用于公共继承)。它只会导致一个指针初始化的开销。

编辑:重写

template<typename Parent, typename Child>
struct IsParentChild
{
  static Parent* Check (Child *p) { return p; }
  Parent* (*t_)(Child*);
  IsParentChild() : t_(&Check) {} // function instantiation only
};
template<typename T>
void foo ()
{
  IsParentChild<Bar, T> check;
// ...
}
相关文章:
  • 没有找到相关文章