Search code examples
c++templatestype-deduction

Type deduction only template


I have a function template defined like this :

// #1
template <typename R, typename T>
R func(T arg) { ... }

// #2
template <typename T>
T func(T arg) { ... }

I would like the type T to be always deducted by the compiler so that :

func<int>(my_var); // calls #1
func(my_var); // calls #2

When trying to do the first call, I get an ambiguous function call error.

Is there a way to achieve this ?


Solution

  • This won't get any award for elegance, but...

    // #1
    template <typename R, typename T>
    R func(T) { /* ... */ }
    
    // #2
    template <int = 0, typename T>
    T func(T) { /* ... */ }
    

    Calling func<int>(4) would try to provide a type argument to the non-type parameter of #2, so it is SFINAE'd away.
    Calling the function with implicit deduction uses the default argument and still works fine.