I would like to provide a templated function, that varies its implementation (->specialization) according to the sizeof the template type.
Something similar to this (omitted typecasts), but without the if/elseif:
template<class T>
T byteswap(T & swapIt)
{
if(sizeof(T) == 2)
{
return _byteswap_ushort (swapIt);
}
else if(sizeof(T) == 4)
{
return _byteswap_ulong(swapIt);
}
else if(sizeof(T) == 8)
{
return _byteswap_uint64(swapIt);
}
throw std::exception();
}
I know there are many roads to reach my goal, but since I try to learn about SFINAE
and type traits
I'm particularly interested in solutions using those techniques to decide at compile time which specialization to choose and which calls are not admitted.
Perhaps implementing a class trait is_4ByteLong and using boost::enable_if...
I have to admit, I'm stuck right now, so I thank you for any help or advice
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
A template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
All data types, both primitive and compound types, must be defined by using a template.
You don't need SFINAE or type traits. Vanilla template specialization is enough. Of course it must be specialized on structs as C++(98) doesn't support function template partial specialization.
template <typename T, size_t n>
struct ByteswapImpl
/*
{
T operator()(T& swapIt) const { throw std::exception(); }
}
*/ // remove the comments if you need run-time error instead of compile-time error.
;
template <typename T>
struct ByteswapImpl<T, 2> {
T operator()(T& swapIt) const { return _byteswap_ushort (swapIt); }
};
// ...
template <typename T>
T byteswap(T& swapIt) { return ByteswapImpl<T, sizeof(T)>()(swapIt); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With