如果你使用std::conditional http://en.cppreference.com/w/cpp/types/conditional代替if_
@Matthieu 在他的回答中实现的类模板,那么您的解决方案将简化为:
template <typename T, typename U>
struct select_base
{
typedef typename std::conditional<std::is_base_of<T, Base>::value, T, U>::type base_type;
};
或者简单地这样:
template <typename T, typename U>
struct select_base : std::conditional<std::is_base_of<T, Base>::value, T, U> {};
看起来更好。
这两个解决方案之间的区别在于,在第一个解决方案中,您给出了程序员友好的正如我所给出的,嵌套类型的名称base_type
,而在第二个解决方案中,嵌套类型只是type
这看起来对程序员不太友好。
请注意,在上述两个解决方案中,您必须使用嵌套类型作为select_base<T,U>::base_type
(在第一个解决方案中)或select_base<T,U>::type
(在第二个解决方案中 - 因此,如果您使用typename
正如您在问题本身中所写的那样。
但是,如果您instead使用模板别名,定义为:
template<typename T, typename U>
using base_type = typename std::conditional<std::is_base_of<T, Base>::value, T, U>::type;
那么你可以使用base_type<T,U>
没有任何嵌套类型和typename
as:
template <typename T1, typename T2>
struct test
{
//typename select_base<T1, T2>::type m_ValueOfBaseType; //ugly!
base_type<T1, T2> m_ValueOfBaseType; //better
};
希望有帮助。