如何确定类型是否从模板类派生? [英] How to determine if a type is derived from a template class?

查看:68
本文介绍了如何确定类型是否从模板类派生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定类型是否从模板类派生?特别是,我需要确定模板参数是否具有std::basic_ostream作为基类.通常,std::is_base_of是用于作业的工具.但是,std::is_base_of仅适用于完整类型,不适用于类模板.

How can I determine if a type is derived from a template class? In particular, I need to determine if a template parameter has std::basic_ostream as a base class. Normally std::is_base_of is the tool for the job. However, std::is_base_of only works for complete types not class templates.

我正在寻找这样的东西.

I'm looking for something like this.

template< typename T >
bool is_based_in_basic_ostream( T&& t )
{
   if( std::is_base_of< std::basic_ostream< /*anything*/>, T >::value )
   {
      return true;
   }
   else
   {
      return false;
   }
}

我确定这是可以做到的,我不认为该怎么做.

I'm sure this can be done I can't think how.

推荐答案

我不知道一种简短的方法.但是您可以再次滥用超载

I'm not aware of a short and concise way. But you can abuse overloading again

template< typename T, typename U >
std::true_type is_based_impl( std::basic_ostream<T, U> const volatile& );
std::false_type is_based_impl( ... );

template< typename T >
bool is_based_in_basic_ostream( T&& t ) {
  return decltype(is_based_impl(t))::value;
}

它将仅检测公共继承.请注意,您可以改为检测来自ios_base的派生,这可能对您同样有效(此测试对输入流也将是肯定的,因此仅适用范围有限)

It will only detect public inheritance. Note that you can instead detect derivation from ios_base, which may work for you equally well (this test will also be positive for input streams, so it's only of limited applicability)

std::is_base_of<std::ios_base, T>

这篇关于如何确定类型是否从模板类派生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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