我不明白为什么下面的代码编译得很好:
#include <iostream>
void bar(int x) {
std::cout << "int " << x << std::endl;
}
void bar(double x) {
std::cout << "double " << x << std::endl;
}
template <typename A, typename B> // Note the order of A and B.
void foo(B x) {
bar((A)x);
}
int main() {
int x = 1;
double y = 2;
foo<int>(x); // Compiles OK.
foo<double>(y); // Compiles OK.
return 0;
}
但是,如果我将A
and的顺序切换B
如下,那么它将无法编译:
#include <iostream>
void bar(int x) {
std::cout << "int " << x << std::endl;
}
void bar(double x) {
std::cout << "double " << x << std::endl;
}
template <typename B, typename A> // Order of A and B are switched.
void foo(B x) {
bar((A)x);
}
int main() {
int x = 1;
double y = 2;
foo<int>(x); // error: no matching function for call to ‘foo(int&)’
foo<double>(y); // error: no matching function for call to ‘foo(double&)’
return 0;
}
编辑:欢迎临时解释,但如果有人能指出具体的规范会更好。说。谢谢!