vendredi 23 juillet 2021

Function template overloading and ambiguity

The code is taken from Partial template function specialization with enable_if: make default implementation . I was expecting the call to dummy(5) to be ambiguous between the "Generic" and the "Integral" overloads as T is deduced as int in both cases. Aren't they equally "ranked" in the call to dummy(5) ? How does the compiler choose the "Generic" version ?

#include <iostream>

template<typename T, typename Enable = void>
void dummy(T t)
{
  std::cout << "Generic: " << t << std::endl;
}


template<typename T, typename std::enable_if<std::is_integral<T>::value>::type>
void dummy(T t)
{
  std::cout << "Integral: " << t << std::endl;
}


template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type>
void dummy(T t)
{
  std::cout << "Floating point: " << t << std::endl;
}

int main() {
  dummy(5); // Print "Generic: 5"
  dummy(5.); // Print "Generic: 5"
}

Aucun commentaire:

Enregistrer un commentaire