C ++类型traits在T1和T2之间选择 [英] C++ type traits to select between T1 and T2
本文介绍了C ++类型traits在T1和T2之间选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据一些条件从两种类型中选择一个模板。例如
struct Base {};
template< typename T1,typename T2>
struct test
{
//例如这里应当选择is_base_of< Base>的T1 / T2。
typename select_base< T1,T2> :: type m_ValueOfBaseType;
};
当然,将条件传递给select_base是非常有用的,
下面是一个我尝试的示例解决方案,但它总是选择T1: http://ideone.com/EnVT8
问题是如何实施select_base模板。
code> template< bool,typename T,typename U> struct if_ {typedef T type; };
template< typename T,typename U>
struct if_< false,T,U> {typedef U型; };
然后你只需使用 is_base_of
p>
template< typename T,typename U>
struct select_base:if_< std :: is_base_of< T,Base> :: value,T,U> {};
就是这样。
I want a template to select from two types based on some condition. E.g.
struct Base {};
template <typename T1, typename T2>
struct test
{
// e.g. here it should select T1/T2 that is_base_of<Base>
typename select_base<T1, T2>::type m_ValueOfBaseType;
};
Of course to pass condition to the select_base (to make it generic) would be useful, but hard-coded solution is easier and good as well.
Here's a sample solution that I tried but it always selects T1: http://ideone.com/EnVT8
The question is how to implement the select_base template.
解决方案
First you need a facility to selection a type depending on a boolean value.
template <bool, typename T, typename U> struct if_ { typedef T type; };
template <typename T, typename U>
struct if_<false, T, U> { typedef U type; };
Then you just use is_base_of
:
template <typename T, typename U>
struct select_base: if_<std::is_base_of<T, Base>::value, T, U> {};
And that is it.
这篇关于C ++类型traits在T1和T2之间选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文