Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template specialization according to sizeof type

Tags:

c++

templates

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

like image 708
nabulke Avatar asked Aug 20 '10 08:08

nabulke


People also ask

What is a template specialization?

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.

What are templates and its types?

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.

How will you restrict the template for a specific datatype?

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.

Which of the data types are supported by template?

All data types, both primitive and compound types, must be defined by using a template.


1 Answers

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); }
like image 81
kennytm Avatar answered Oct 22 '22 13:10

kennytm