有什么像模板化的案例声明 [英] Is There Anything Like a Templatized Case-Statement
问题描述
所以我有这个非常丑的代码:
So I have this really ugly code:
template <typename T>
std::conditional_t<sizeof(T) == sizeof(char),
char,
conditional_t<sizeof(T) == sizeof(short),
short,
conditional_t<sizeof(T) == sizeof(long),
long,
enable_if_t<sizeof(T) == sizeof(long long),
long long>>>> foo(T bar){return reinterpret_cast<decltype(foo(bar))>(bar);}
我使用嵌套 conditional_t
s来做一个排序的case语句。有没有什么东西在那里完成这更优雅,或者我需要煮自己的模板化情况下的语句?
I'm using nested conditional_t
s to make a case-statement of sorts. Is there something out there that accomplishes this more elegantly or do I need to cook up my own templatized-case-statement?
注意:我实际上知道这个使用 reinterpret_cast
是坏的:
推荐答案
我不得不这样做一次,所以我写了一个小包装以达到整洁的结果。您可以按如下方式使用(请参阅这里测试)
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){ ... }
场景,它几乎是你已经有,但通过包装它,我们保持它(更)可读。还有一个版本,允许你切换类型 T
如果你需要的。
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.
编辑: @ Deduplicator的建议是这里的代码
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!");
};
这篇关于有什么像模板化的案例声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!