模板中的重载决策

时间:2010-10-25 11:02:34

标签: c++ templates

任何人用一个例子解释这个

  "Involving conversions on a function argumentsinvolved in template
   parameter deduction."

这样的示例:

 template<class T> struct B { /* ... */ };
 template<class T> struct D : public B<T> { /* ... */ };
 template<class T> void f(B<T>&);
 void g(B<int>& bi, D<int>& di)
   {
    f(bi);
    f(di);
   }

请再给我一些例子

编辑:这是ISO C ++标准14.8.3 / 5中的一个观点/声明:重载分辨率

1 个答案:

答案 0 :(得分:3)

这是关于示例所示的内容。总之,这些是那些转换

  • 函数参数可以是Base<T>,而函数参数是Derived<T>。与ifstream << "hello"比较 - operator<<的左侧以这种方式推断。
  • 函数参数可以是const U&,而函数参数是U(对于volatile也是如此)。
  • 函数参数可以是const U*const E C::*,而函数参数分别是U*E C::*(这些是资格转换) - 对于volatile也是如此。

对于参与演绎的函数参数/参数,无法进行其他转换。如果函数参数参与演绎,则可以应用整个转换范围,但这需要一个非推导的上下文或根本没有参数推断的上下文,并且实现不需要实际上并不同意(见here)。

换句话说:

template<typename T> struct id { typedef T type; };
template<typename T> void f(T, typename id<T>::type);

int main() {
  // deduction acts on void(int*, int*) - deduction does not need
  // to deduce anything and follows [temp.arg.explicit]p4
  f<int*>(0, 0); 

  // deduction acts on void(T, id<T>::type) - second is a non-deduced context,
  // which *will* allow the conversion of int -> int*, since it will not compare
  // the argument with parameter during deduction (since it is non-deduced).
  f((int*)0, 0);
}

第二个例子对于some partial ordering上下文起作用至关重要。

相关问题