Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional return type with template

I want to use a conditional return type related to a template in C++. C++ 11, 14 and 17 preview are available on my environment.

I am not new to programming, but I am new to C++ and a bit confused with some functionalities.

What I want to achieve is :

If template is int32_t my return type will be int64_t, int16_t will return an int32_t and int8_t will return an int16_t.

Actually I am using a generic template for both :

template <class T, class T2>
static T2 Foo(T bar1, T bar2) { //do something }

int64_t x = Foo<uint32_t, uint64_t>(555555, 666666);

I would like to make this a little more practical by having to type only the parameters type.

int64_t x = Foo<uint32_t>(555555, 666666);
int32_t x = Foo<uint16_t>(12000, 13000;
int16_t x = Foo<uint8_t>(88, 99);

I tried to implement it with std::conditional:

template<typename OtherType,
        typename T = typename std::conditional<(sizeof(Type) <=   
        sizeof(OtherType)),
        OtherType, Type>::type>

I am open to use overloads and crazy ideas.

like image 241
Lizi Avatar asked Jan 05 '23 19:01

Lizi


1 Answers

An idiomatic way to do that in C++ is using traits.
As an example:

template<typename> struct foo_ret;
template<> struct foo_ret<uint32_t> { using type = uint64_t; };
template<> struct foo_ret<uint16_t> { using type = uint32_t; };
// And so on...

A template parameter for the return type is even no longer required now:

template <class T>
static typename foo_ret<T>::type Foo(T bar1, T bar2) {};

And you can invoke it as it follows, as requested:

int64_t x = Foo<uint32_t>(555555, 666666);

Or let the compiler deduce T if you prefer.

like image 114
skypjack Avatar answered Jan 07 '23 08:01

skypjack