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

戏子无情 提交于 2020-04-07 05:12:33

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/56284648/function-template-has-already-been-defined-with-mutually-exclusive-enable-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!