skip to Main Content

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

2

Answers


  1. 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 }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search