为什么我的模板函数不提升'int'到'T',其中'T'='双'? [英] Why doesn't my templated function promote 'int' to 'T', where 'T' = 'double'?
问题描述
我有一个类用 typename T
模板化。它包含一个函数,
I have a class templated with typename T
. It contains a function,
template <typename T, size_t a>
myClass<T,a> operator+(myClass<T,a> lhs, const T& rhs) {
return lhs += rhs;
}
myClass<T,a> myClass<T,a>::operator+=(const T& rhs) {
// Do addition, depends on 'a'.
return *this;
}
当我使用
myClass<double, 2> myObj_double_2(constructor args);
myObj_double_2 = myObj_double_2 + 5.2;
我没有问题。
然而,我调用
myObj_double_2 = myObj_double_2 + 5;
然后编译器给我一个类似于< (操作数类型是'myClass< double,2ul>'和'int')。候选者是...注意:推断参数const T('double'和'int')的冲突类型。
Then the compiler gives me a message like - No match for 'operator+' (operand types are 'myClass<double, 2ul>' and 'int'). Candidates are ... note: deduced conflicting types for parameter 'const T' ('double' and 'int')
.
以某种方式编写代码以允许传递具有转换为 T
的额外类型(因为例如double(5)是有效的构造函数调用)?
Can I write the code in some way to allow additional types to be passed that have a conversion to T
(since, for example, double(5) is a valid constructor call)?
推荐答案
当您使用模板参数扣除时,一个模板参数的所有扣减必须具有 。
When you are using template argument deduction, all deductions for one template parameter must have the same result.
在您的情况下, T
的两个扣除产生 double
和 int
,这是不一样的,因此扣除失败。
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 <typename T, std::size_t A>
void foo(myClass<T, A> arg1, typename std::common_type<T>::type arg2);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
请注意, std :: common_type< T> :: type
本质上只是 T
,但因为 arg2
的类型现在是一个依赖类型(它的名称显示在 ::
),不会被推导出来。因此,只有第一个参数参与推导,并且明确地产生 T = double
,然后第二个函数参数只有类型 double
,并发生通常的转换。
Note that std::common_type<T>::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 ::
.
这篇关于为什么我的模板函数不提升'int'到'T',其中'T'='双'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!