Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition in Template Definition

I want to change the return type of a template function depending on a property of the given type. Is there a possibility to do something like this, maybe with partial specialization (one for the cool T and one for not cool ones)?

template<typename T, typename ret = T::IsCool ? int : float>
inline ret get() {}

(It is always guaranteed, that T has the bool property IsCool.)

like image 853
PaulProgrammerNoob Avatar asked Feb 05 '23 08:02

PaulProgrammerNoob


1 Answers

You can use std::conditional to achieve this.

See http://en.cppreference.com/w/cpp/types/conditional

You can use it like so:

C++11

template<typename T, typename ret = std::conditional<T::IsCool, int, float>::type>
inline ret get() {}

C++14

template<typename T, typename ret = std::conditional_t<T::IsCool, int, float>>
inline ret get() {}
like image 143
3 revs, 3 users 50% Avatar answered Feb 22 '23 22:02

3 revs, 3 users 50%