如何判断一个类型是否派生自模板类?
如何确定类型是否派生自模板类?特别是,我需要确定模板参数是否以 std::basic_ostream
作为基类。通常 std::is_base_of
是完成这项工作的工具。但是,std::is_base_of 仅适用于完整类型,不适用于类模板。
我正在寻找这样的东西。
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;
}
}
我确信这是可以做到的,但我不知道如何做到。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道有什么简短的方法。但是你可以再次滥用重载
它只会检测公共继承。请注意,您可以改为检测
ios_base
的派生,这可能同样适合您(此测试对于输入流也将是积极的,因此它的适用性有限)I'm not aware of a short and concise way. But you can abuse overloading again
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)Boost 的 is_instance_of 之类的东西可能就是你想要的吗?
http://www.boost.org/doc/ libs/1_46_1/boost/lambda/detail/is_instance_of.hpp
这是 1 参数模板的简短版本:
不幸的是,如果您尝试将其扩展到可变参数模板,则使用当前的 GCC (4.6.0) 它将产生错误消息。 这个答案意味着这是当前 GCC 的问题,并且可变参数模板版本应该按照标准工作。
Might something like Boost's is_instance_of be what you are after?
http://www.boost.org/doc/libs/1_46_1/boost/lambda/detail/is_instance_of.hpp
Here is the short version for 1-argument templates:
Unfortunately, if you try to extend this to variadic templates, with current GCC (4.6.0) it will produce an error message. This SO answer implies that this is currently a problem of GCC and that the variadic template version is supposed to work according to the standard.