How to check the value of a template parameter?

602 views Asked by At

I want to use the alias based on the value in template parameter. Something like this:

If W > 32:
template<size_t W>
using int_t = My_Int<W, int64_t>;

Else:
template<size_t W>
using int_t = My_Int<W, int32_t>;

I also tried std::conditional, but didn't find a good way to do it.. How should I do that? Thanks!

4

There are 4 answers

0
NathanOliver On

Using std::conditional you would have

template<size_t W>
using int_t = std::conditional_t<(W > 32), My_Int<W, int64_t>, My_Int<W, int32_t>>;

where My_Int<W, int64_t> is used when W > 32 is true and My_Int<W, int32_t> is used when it is false.

0
leslie.yao On

Yes you can use std::conditional for it, e.g.

template<size_t W>
using int_t = typename std::conditional<(W > 32), My_Int<W, int64_t>, My_Int<W, int32_t>>::type;

Or since C++14:

template<size_t W>
using int_t = std::conditional_t<(W > 32), My_Int<W, int64_t>, My_Int<W, int32_t>>;

Note that you need to add parentheses for the condition W > 32; otherwise W will be considered as the only template argument, which won't work because std::conditional expects three ones.

1
Desmond9989 On
template<size_t W>
using int_t = std::conditional_t<(W > 32), My_Int<W, int64_t>, My_Int<W, int32_t>>;

will work on C++14.

0
max66 On

A little-less type-writing version of std::conditional_t solutions

template <std::size_t W>
using int_t = My_Int<W, std::conditional_t<(W > 32), int64_t, int32_t>>;