Can a template function be called with missing template parameters in C++ ?

匆匆过客 提交于 2019-12-20 03:52:50

问题


This is an interview question, which has been done.

Which line has error ?

  #include<iostream>
  template<class T> void foo(T op1, T op2)
  {
      std::cout << "op1=" << op1 << std::endl;
      std::cout << "op2=" << op2 << std::endl;
  }

  template<class T>
  struct sum
  {
      static void foo(T op1, T op2)
      {
              std::cout << "sum=" << op2 << std::endl ;
      }
  };

  int main()
  {
      foo(1,3);  // line1
      foo(1,3.2);  // line2
      foo<int>(1,3);  // line3
      foo<int>(1, '3') ; // line 4
      sum::foo(1,2) ; // line 5  , 

      return 0;
  }

Line 2 has error because the template parameter is not matching the definition. Line 5 has error because the template parameter is missing.

But, Line 1 is an not an error, I do not know why, does not it also miss template parameter ?

Thanks !


回答1:


It's called type deducition.

On Line 1, the type of T can be deduced because parameters op1 and op2 are both int, making T an int.

Whereas on Line 2, you are passing both an int and a double while the function accepts both parameters as T, the compiler has no clue whether T should be a double or an int.

Line 3 is fine because you specify int specialization and pass ints in as well (making the specialization redundant but perfectly OK).

Line 4 is OK because you declare T to be an int, then casting the char value of '3' to its numeric int value.

Line 5 is an error because you're accessing a function that gets its type from the templated struct it's in, and type deduction only works for functions.




回答2:


When we use a function template, the compiler infers what template argument(s) to bind to the template parameter(s). Once the compiler determines the actual template argument(s), it instantiates an instance of the function for us. Essentially the compiler figures out what type to use in place of each type parameter. So, if op1 and op2 have the same type the template parameter(s) can be omitted (that's why line #2 causes error).

From C++ primer



来源:https://stackoverflow.com/questions/10872730/can-a-template-function-be-called-with-missing-template-parameters-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!