问题
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