模板类限制 [英] template class restriction

查看:97
本文介绍了模板类限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法来限制生成代码模板使用自定义条件在我的情况下我想函数foo只有当模板类T已经嵌入由类bar(类似这样) p>

I'm wondering if there is any way to restrict generating code for a template using custom conditions in my case i want to function foo to be called only if template class T has inherieted by class bar(something like this)

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


推荐答案

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

You can restrict T though using "Substitution Failure Is Not An Error" (SFINAE):

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

}

如果 T 不是从 code>,函数模板的特殊化将失败,并且在重载解析期间不会被考虑。 std :: enable_if std :: is_base_of 是C ++标准库的新组件, ++ 0x。如果你的编译器/标准库实现还不支持它们,你也可以在C ++ TR1或Boost.TypeTraits中找到它们。

If T is not derived from bar, specialization of the function template will fail and it will not be considered during overload resolution. std::enable_if and std::is_base_of are new components of the C++ Standard Library added in the forthcoming revision, C++0x. If your compiler/Standard Library implementation don't yet support them, you can also find them in C++ TR1 or Boost.TypeTraits.

这篇关于模板类限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆