如何返回类型列表中最大的类型? [英] How do I return the largest type in a list of types?
本文介绍了如何返回类型列表中最大的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何创建一个类模板返回 sizeof
大于其他类型。例如:
How would I make a class template that returns the type whose sizeof
is greater than the others. For example:
typename largest<int, char, double>::type;
这应该会返回 double
。
推荐答案
您可以使用可变参数模板参数和编译时条件语句来实现这一点:
You can accomplish this with the use of variadic template arguments and compile-time conditionals:
#include <type_traits>
template <typename... Ts>
struct largest_type;
template <typename T>
struct largest_type<T>
{
using type = T;
};
template <typename T, typename U, typename... Ts>
struct largest_type<T, U, Ts...>
{
using type = typename largest_type<typename std::conditional<
(sizeof(U) <= sizeof(T)), T, U
>::type, Ts...
>::type;
};
int main()
{
static_assert(
std::is_same<largest_type<int, char, double>::type, double>::value, "");
}
这篇关于如何返回类型列表中最大的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文