Home > Back-end >  How to overload function template function inside a class template?
How to overload function template function inside a class template?

Time:03-17

How can I overload the Contains function template in class template Range?

When I run this code , I get an error as below:

template <typename T>
class Range {
public:
    Range(T lo, T hi) : low(lo), high(hi)
    {}

    typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type    
    Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
    {
        // do sth
        return true;
    }

    typename std::enable_if<std::numeric_limits<T>::is_integer, bool>::type 
    Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
    {
        // do sth
        return true;
    }
};
error: ‘typename std::enable_if<std::numeric_limits<_Tp>::is_integer, bool>::type Range<T>::Contains(T, bool, bool) const’ cannot be overloaded
         Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
         ^~~~~~~~
    error: with ‘typename std::enable_if<(! std::numeric_limits<_Tp>::is_integer), bool>::type Range<T>::Contains(T, bool, bool) const’
         Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const

CodePudding user response:

You need to make Contains themselves template too. E.g.

template <typename X = T>
typename std::enable_if<!std::numeric_limits<X>::is_integer, bool>::type    
Contains(X value, bool leftBoundary = true, bool rightBoundary = true) const
{
    // do sth
    return true;
}

template <typename X = T>
typename std::enable_if<std::numeric_limits<X>::is_integer, bool>::type 
Contains(X value, bool leftBoundary = true, bool rightBoundary = true) const
{
    // do sth
    return true;
}

Since C 17 you can use Constexpr If instead of overloading.

bool
Contains(T value, bool leftBoundary = true, bool rightBoundary = true) const
{
    if constexpr (!std::numeric_limits<T>::is_integer) {
        // do sth
        return true;
    } else {
        // do sth
        return true;
    }
}
  • Related