如何创建一个返回sizeof
大于其他类型的类的类模板。例如:
typename largest<int, char, double>::type;
那应该返回double
。我该怎么做呢?
答案 0 :(得分:26)
您可以使用可变参数模板参数和编译时条件来完成此任务:
#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, "");
}
答案 1 :(得分:8)
这是一个将选择最大类型的版本,但打破了最后一种类型的关系:
template<bool, typename, typename>
struct pick_type;
template<typename T, typename U>
struct pick_type<true,T,U> {
typedef T type;
};
template<typename T, typename U>
struct pick_type<false,T,U> {
typedef U type;
};
template<typename...>
struct largest;
template<typename T>
struct largest<T> {
typedef T type;
};
template<typename T, typename... U>
struct largest<T, U...> {
typedef typename largest<U...>::type tailtype;
typedef typename pick_type<
(sizeof(T)>sizeof(tailtype)),
T,
tailtype
>::type type;
};
以下是示例代码:
#include <iostream>
using namespace std;
void foo( double ) { cout << "double\n"; }
void foo( int ) { cout << "int\n"; }
void foo( char ) { cout << "char\n"; }
void foo( bool ) { cout << "bool\n"; }
void foo( float ) { cout << "float\n"; }
int main() {
foo(largest<int,double,char,bool,float>::type{});
}