简体   繁体   English

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

[英]Template function argument deduction with an implicit conversion

I understand that template function argument deduction does not take implicit conversions into account. 我了解模板函数自变量推导不考虑隐式转换。

So this code doesn't compile: 因此,此代码无法编译:

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

What I don't understand is how adding an extra level of indirection with an identity typedef somehow makes it work: 我不明白的是如何使用身份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 在Godbolt上进行现场演示

How does magic_t<A<X>> end up matching C ? magic_t<A<X>>如何最终匹配C

The second parameter becomes non-deduced context and doesn't participate in template argument deduction. 第二个参数变为非推导上下文 ,并且不参与模板参数推导。 X is then successfully deduced from the first argument. 然后从第一个参数成功推导出X

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM