annapurna
annapurna

Reputation: 31

How to check the value of a template parameter?

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!

Upvotes: 1

Views: 734

Answers (4)

max66
max66

Reputation: 66200

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>>;

Upvotes: 2

songyuanyao
songyuanyao

Reputation: 172924

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.

Upvotes: 2

Desmond9989
Desmond9989

Reputation: 25

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.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180585

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.

Upvotes: 2

Related Questions