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

前端 未结 2 476
醉酒成梦
醉酒成梦 2021-01-24 12:47

This is an interview question, which has been done.

Which line has error ?

  #include
  template void foo(T op1, T op2)
         


        
2条回答
  •  滥情空心
    2021-01-24 13:34

    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.

提交回复
热议问题