Home > Blockchain >  C template with condition for type
C template with condition for type

Time:10-22

I have class with template. I want to add template condition for one of the class methods.

The idea is for float types I want separate passed method to call this with some epsillon value.

Is it possible? The example what I want:

template<typename ValueType>
class Comparator {
public:

...

bool passed(ValueType actualValue);

template<
    typename ValueType,
    typename = std::enable_if_t<
        std::is_floating_point<std::remove_reference_t<ValueType>>::value
    >
>
bool passed(ValueType actualValue, ValueType eps) { ... }

...

};

Environment: Debian 11, C 14, gcc (Debian 10.2.1-6) 10.2.1 20210110

CodePudding user response:

Yes, you can do this:

#include <type_traits>

template<typename ValueType>
class Comparator {
public:

template<
    typename U = ValueType,
    typename = std::enable_if_t<
        !std::is_floating_point<std::remove_reference_t<U>>::value
    >
>
bool passed(ValueType actualValue);

template<
    typename U = ValueType,
    typename = std::enable_if_t<
        std::is_floating_point<std::remove_reference_t<U>>::value
    >
>
bool passed(ValueType actualValue, ValueType eps);

};

Demo.

CodePudding user response:

You are most of the way there already. In order to overload SFINAE, you need to use a non-type template parameter with an assigned default value instead of using defaulted type template parameter.

So, we change both functions to use a non-type paramere with a default value, and just negate the condition like:

template<typename ValueType>
class Comparator {
public:

...
template<
    typename T = ValueType,
    std::enable_if_t<
        !std::is_floating_point<std::remove_reference_t<ValueType>>::value,
//      ^- not here, so only non-floating point types allowed
        bool> = true // set the bool to true, this lets us call the function without providing a value for it
>
bool passed(T actualValue) { non floating point code here }

template<
    typename T = ValueType,
    std::enable_if_t<
        std::is_floating_point<std::remove_reference_t<T>>::value,
        bool> = true // set the bool to true, this lets us call the function without providing a value for it
>
bool passed(T actualValue, T eps) { floating point code here }
  • Related