Search code examples
c++templatesenable-if

ambiguous function template


I want to select a specific function template via enable_if applied to the return type.

A boiled down example would be to distinguish between signed and unsigned arguments.

#include <iostream>
#include <type_traits>

template<typename T>
typename std::enable_if<std::is_signed_v<T>, bool>
foo(T t)
{
  return true;
}

template<typename T>
typename std::enable_if<!std::is_signed_v<T>, bool>
foo(T t)
{
  return false;
}

int main(){
  std::cout << foo<uint32_t>(42) << std::endl;

  return 0;
}

here I get the compiler error: call of overloaded ‘foo<uint32_t>(int)’ is ambiguous std::cout << foo<uint32_t>(42) << std::endl;

I get that it would be ambiguous if I used foo(42) as 42 can be converted to signed an unsigned. But if I specify the tempalte parameter explicitly as in my example I would expect it to work.

What is the problem with my code and how can I fix it?


Solution

  • you are missing the ::type at the end of your enable_if so no error occur even when the condition is false

    you can use enable_if_t or add the ::type like

    typename std::enable_if<std::is_signed_v<T>, bool>::type