我理解模板函数参数推导不会考虑隐式转换。
所以这段代码没有编译:
#include <iostream>
template<class T>
struct A {};
struct B : public A<int> {};
struct C {
operator B() { return {}; }
};
template<class X>
void test(A<X> arg1, A<X> arg2) {
std::cout << "ok1";
}
int main() {
B b;
C c;
test(b, c); // error: no matching function for call to 'test'
}
我不明白的是,如何通过身份typedef
添加额外级别的间接使其工作:
#include <iostream>
template<class T>
struct A {};
struct B : public A<int> {};
struct C {
operator B() { return {}; }
};
template<typename U> struct magic { typedef U type; };
template<class T> using magic_t = typename magic<T>::type;
template<class X>
void test(A<X> arg1, A<X> arg2) {
std::cout << "ok1";
}
template<class X>
void test(A<X> arg3, magic_t<A<X>> arg4) {
std::cout << "ok2";
}
int main() {
B b;
C c;
test(b, c); // prints "ok2"
}
magic_t<A<X>>
如何最终匹配C
?