Home  >  Article  >  Backend Development  >  Why Does Using `enable_if_t` in Template Arguments Lead to Redefinition Errors?

Why Does Using `enable_if_t` in Template Arguments Lead to Redefinition Errors?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 10:08:02280browse

Why Does Using `enable_if_t` in Template Arguments Lead to Redefinition Errors?

Why enable_if_t in Template Arguments Causes 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, templatevoid(). This is equivalent to having two functions print(string, int) with different default int values, which is invalid for overloading.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn