2013-05-29 34 views

Trả lời

26

Bạn có thể thực hiện điều này với việc sử dụng các đối số mẫu variadic và thời gian biên dịch điều kiện:

#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

Yay, tôi nghĩ rằng tôi bắt đầu nhận được hang của thi s loại công cụ. +1. – chris

8

Dưới đây là một phiên bản đó sẽ chọn loại lớn nhất, nhưng phá vỡ mối quan hệ có lợi cho loại lần cuối:

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

Dưới đây là mã ví dụ:

#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{}); 
} 
+0

Điều gì xảy ra nếu lớp của tôi có loại lớn nhất nhưng chưa có hàm tạo mặc định? – 0x499602D2

+1

@ 0x499602D2: Sau đó, ví dụ sẽ không hoạt động, nhưng mẫu vẫn sẽ. –

Các vấn đề liên quan