Search code examples
c++templatessfinaetype-traitsenable-if

"Function template has already been defined" with mutually exclusive `enable_if`s


MSVC produces error ("function template has already been defined") for the following code:

template<typename T, typename = std::enable_if_t<std::is_default_constructible<T>::value>>
auto foo(T&& val) {
    return 0;
}

// note difference from above --->               !
template<typename T, typename = std::enable_if_t<!std::is_default_constructible<T>::value>>
auto foo(T&& val) {
    return 0;
}

I thought it would work because there are mutually exclusive sfinae conditions. Can you help me with the hole in my understanding?


Solution

  • Yes, their signature are the same; the default template arguments are not the part of the function template signature.

    You can change them to

    // the 2nd non-type template parameter are different
    template<typename T, std::enable_if_t<std::is_default_constructible<T>::value>* = nullptr>
    auto foo(T&& val) {
        return 0;
    }
    
    template<typename T, std::enable_if_t<!std::is_default_constructible<T>::value>* = nullptr>
    auto foo(T&& val) {
        return 0;
    }
    

    Or

    // the return type are different
    template<typename T>
    std::enable_if_t<std::is_default_constructible<T>::value, int> foo(T&& val) {
        return 0;
    }
    
    template<typename T>
    std::enable_if_t<!std::is_default_constructible<T>::value, int> foo(T&& val) {
        return 0;
    }