我将如何制作一个返回类型sizeof
大于其他类型的类模板。例如:
typename largest<int, char, double>::type;
那应该返回double
。我该怎么做呢?
您可以使用可变参数模板参数和编译时条件来完成此操作:
#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, "");
}
这是一个将选择最大类型的版本,但会打破平局以支持最后一种类型:
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{});
}