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);}
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?
Note: I am actually aware that this use of reinterpret_cast
is bad: Why Doesn't reinterpret_cast Force copy_n for Casts between Same-Sized Types?
The template version of a switch statement is a specialized template.
As long as you understand the risk that the same sized type may not be the convertible, you could simply plugin a
mpl::map
..e.g.
A type tag:
void_t
(coming in C++17 to a compiler near you):enable_first_t
takes a pack ofstd::enable_if
(note the lack of_t
), and returns the first that passes the test. You can usetag<X>
to replacestd::enable_if<true, X>
:this behaves a lot like a
switch
, but the statements are full boolean expressions.live example
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)
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
Something like this perhaps: