I had to do something like this once so I wrote a small wrapper to acheive the result neatly. You could use it as follows (see here for a test)
template<class T>
typename static_switch<sizeof(T)
,int // default case
,static_case<sizeof(char),char>
,static_case<sizeof(short),short>
,static_case<sizeof(long),long>
>::type foo(T bar){ ... }
Behind the scenes it pretty much does what you already have but by wrapping it we keep it (more) readable. There is also a version to allow you to switch direclty on the type T
if you needed that.
Edit: At @Deduplicator's suggestion here is the code behind it
#include <type_traits>
/*
* Select a type based on the value of a compile-time constant such as a
* constexpr or #define using static_switch.
*/
template<int I,class T>
struct static_case {
static constexpr int value = I;
using type = T;
};
template<int I, class DefaultType, class Case1, class... OtherCases>
struct static_switch{
using type = typename std::conditional< I==Case1::value ,
typename Case1::type,
typename static_switch<I,DefaultType,OtherCases...>::type
>::type;
};
struct fail_on_default {};
template<int I, class DefaultType, class LastCase>
struct static_switch<I,DefaultType,LastCase> {
using type = typename std::conditional< I==LastCase::value ,
typename LastCase::type,
DefaultType
>::type;
static_assert(!(std::is_same<type, fail_on_default>::value),
"Default case reached in static_switch!");
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…