Home > Article > Backend Development > Why Does Using `enable_if_t` in Template Arguments Lead to Redefinition Errors?
In C , std::enable_if is used for conditional type selection in template arguments. When using the newer syntax typename std::enable_if_t<...> in place of typename std::enable_if<...>::type*, compilers may raise redefinition errors.
To understand why, consider the following code:
template<typename T, typename std::enable_if<std::is_same<int, T>::value>::type* = nullptr> void f() { } template<typename T, typename std::enable_if<std::is_same<double, T>::value>::type* = nullptr> void f() { }
This code declares two templates that overload f based on whether T is int or double. However, when the code is updated to use std::enable_if_t, it causes a redefinition error:
template<typename T, typename = std::enable_if_t<std::is_same<int, T>::value>> void g() { } template<typename T, typename = std::enable_if_t<std::is_same<double, T>::value>> void g() { }
The reason for the error is that even though the default value for the second template argument is different, the templates are still of the same type, template
To resolve the issue, remove the enable_if clause in the template arguments and replace typename with class:
template<class T, class U /* = std::enable_if_t<std::is_same<int, T>::value> */> void g() { } template<class T, class U /* = std::enable_if_t<std::is_same<double, T>::value> */> void g() { }
Alternatively, you can specify a different type for the second template argument:
template<class T, std::enable_if_t<std::is_same<int, T>::value, int> = nullptr> void g() { } template<class T, std::enable_if_t<std::is_same<double, T>::value, int> = nullptr> void g() { }
The above is the detailed content of Why Does Using `enable_if_t` in Template Arguments Lead to Redefinition Errors?. For more information, please follow other related articles on the PHP Chinese website!