带有隐式转换的模板函数参数推导

时间:2017-08-18 21:21:02

标签: c++ c++11 templates argument-deduction

我理解模板函数参数推导不会考虑隐式转换。

所以这段代码没有编译:

#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"
}

Live demo on Godbolt

magic_t<A<X>>如何最终匹配C

1 个答案:

答案 0 :(得分:4)

第二个参数变为non-deduced context,不参与模板参数推断。然后,从第一个参数中成功推导出X

相关问题