C++ 如何处理与类型转换相关的模板函数

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

我对一些编译器如何工作的一般想法是,在类型检查阶段(语义分析)AST 用类型转换信息注释,所以举个例子,例如:1 + 1.2,节点代表1 将用浮点数(或双精度)进行注释,以指示必须对其进行转换,以便它可以匹配函数调用 operator+(float, float)(或 float.operator+(float))。

但是,当涉及到模板函数参数时,例如:

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);

可以将不同类型的大量组合传递给此函数。那么,AST ab 的类型转换注解是如何处理的呢?该函数是否针对调用它的可能的不同类型进行了复制?函数是否内联?

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

是的。大致就是写模板的思路。 test 不是函数,test<int,double> 是。

以下内容并非真实情况,但在一定程度上可以作为心智模型使用。

你打电话

test(1,1.0);

编译器将 TB 分别推断为 intdouble。因此它将实例化一些东西:

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

现在才需要编译器,并且拥有查看 a+b 是否需要提升其中一个操作数所需的所有信息。通常的规则确实适用:https://en.cppreference.com/w/cpp/language/implicit_conversion