Search code examples
c++templatescompiler-construction

How does C++ handle template functions with respect to type conversions


My general idea of how some compilers work, is that during the type checking phase (semantic analysis) the AST is annotated with type conversion information, so with a example such as: 1 + 1.2, the node representing 1 will be annotated with a float (or double) to indicate that it has to be converted so that it can match the function call operator+(float, float) (or float.operator+(float)).

However, when it comes to templated functions arguments such as:

template<typename T, typename B>
void test(T a, B b) {
    a + b;
}
...
test(23, 12);
test(23, 1.2);
test(2.3, 12);
test(2.3, 1.2);

A great combination of different types can be passed to this function. Therefore, how is type conversion annotations of the AST a and b handled? Is the function duplicated for the possible different types it's called with? Is the function inlined?


Solution

  • Is the function duplicated for the possible different types it's called with?

    Yes. Thats roughly the idea of writing templates. test is not a function, test<int,double> is.

    The following is not really what happens but it works as a mental model to quite some extend.

    You call

    test(1,1.0);
    

    Compiler deduces T and B to be int and double, respectively. Hence it will instantiate something along the line of:

    void test(int a, double b) {
        a + b;
    }
    

    Only now the compiler is required and has all the information needed to see if a+b requires to promote one of the operands. The usual rules do apply: https://en.cppreference.com/w/cpp/language/implicit_conversion