Overloaded non-type template is ambiguous while non-templated function is ok

后端 未结 3 544
庸人自扰
庸人自扰 2021-01-11 12:29

If we have a template function which takes a non-type parameter of type int or short the compiler complains about the ambiguity of the following ca

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 13:35

    Here's what happens when you write f<0>().

    1. The compiler looks up f, and finds two function template declarations:

      template    void foo();
      template  void foo();
      
    2. The compiler sees the explicit template argument list and attempts to substitute it into each function template declaration:

      template    void foo(); // with I = 0
      template  void foo(); // with S = 0
      

      Substitution succeeds in both cases because 0 is an int, and can be converted to short, and the conversion is an allowed conversion in this context.

    3. After substitution, two candidate function specializations are produced. Both are viable. Overload resolution is then performed - and since the signature is identical and no tiebreaker applies, overload resolution fails and the call is ambiguous.

    The point here is that the normal overload resolution rules do not apply to template arguments. The conversions for template arguments are applied in an earlier stage, before the regular overload resolution takes place.

提交回复
热议问题