Why doesn't my templated function promote 'int' to 'T', where 'T' = 'double'?

前端 未结 3 1253
无人及你
无人及你 2021-02-05 07:21

I have a class templated with typename T. It contains a function,

template 
myClass operator+(myClass

        
3条回答
  •  梦谈多话
    2021-02-05 07:47

    When you are using template argument deduction, all deductions for one template parameter must have the same result.

    In your case, the two deductions for T produce double and int, which are not the same, and so deduction fails.

    What you can do is only use one function argument for template argument deduction, and make the other one undeduced:

    template 
    void foo(myClass arg1, typename std::common_type::type arg2);
    //                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    Note that std::common_type::type is essentially just T, but because the type of arg2 is now a dependent type (its name appears to the right of a ::), it is not deduced. Therefore, only the first argument takes part in deduction and produces T = double unambiguously, and then the second function parameter just has type double, and the usual conversions take place.

    As a rule of thumb, template argument deduction does not cross ::.

提交回复
热议问题