在 T1 和 T2 之间进行选择的 C++ 类型特征

2024-01-23

我想要一个模板根据某些条件从两种类型中进行选择。例如。

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;
};

当然,将条件传递给 select_base (以使其通用)会很有用,但硬编码解决方案也更容易且更好。

这是我尝试过的示例解决方案,但它始终选择 T1:http://ideone.com/EnVT8 http://ideone.com/EnVT8

问题是如何实现select_base模板。


如果你使用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
};

希望有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 T1 和 T2 之间进行选择的 C++ 类型特征 的相关文章

随机推荐