Condition in template definition

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

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

      

(it is always guaranteed that T has the property bool

IsCool

.)

+3


source to share


1 answer


You can use std::conditional

to achieve this.

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

You can use it like this:

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() {}

      

+7


source







All Articles