Search code examples
c++templatestemplate-specialization

Template argument deduction when types are not in function prototype


According to https://en.cppreference.com/w/cpp/language/template_specialization, "When specializing a function template, its template arguments can be omitted if template argument deduction can provide them from the function arguments".

Is it every possible to provide an explicit type for specialisation when the type cannot be deducted?

Consider this basic example:

#include <iostream>

using namespace std;

template<typename T>
void print(int i) {
    T t = static_cast<T>(i) * static_cast<T>(1.5);
    cout << t << endl;
}

int main()
{
    print<double>(5);
    print<int>(5);

    return 0;
}

What if we wanted to provide a specialisation for a type, like int that does something different, even though int doesn't appear in the function prototype? e.g. I'm looking for a way to do something like this:

template<T = int>
void print(int i) {
    cout << i << endl;
}

Solution

  • A specialization looks like this:

    template<>
    void print<int>(int i) {
        cout << i << endl;
    }
    

    The sentence you read refers to the case

    tempalte <typename T> void foo(T);
    

    Where a specialization can be declared via a shorter

    template <> void foo(int);
    

    as an alternativ to the usual

    tempalte <> void foo<int>(int);
    

    The latter is ok in either case.