运算符+和浮点参数

operator + and float argument

本文关键字:参数 运算符      更新时间:2023-10-16

我对模板有一个奇怪的问题,我正在尝试在模板类和"float/double/int"类型。这是非常基本的,但如果我这样做:

template<class T>
class toto{
    T a;
};
template<class T>
toto<T> operator+(toto<T> const&, T&){
     std::cout <<  "hello " <<std::endl;
}
int main(){
     toto<float> t;
     toto<float> d = t +2.3;
}

它不会编译,因为2.3被认为是双精度的,它与签名不匹配。我可以为我的操作员+使用第二个模板参数作为

template<class T, class D>
toto<T> operator+(toto<T> const&, D&){
     std::cout <<  "hello " <<std::endl;
}

它编译、执行正确但过于危险的D可能是一切。另一种选择是使用float、double或int(O_O)创建不同的签名。Boost::enable_if似乎是我的解决方案,但在文档中我读到:

template <class T>
T foo(T t,typename enable_if<boost::is_arithmetic<T> >::type* dummy = 0);

将此方法应用于运算符*不起作用,因为编译器抱怨默认参数被禁止。

有什么建议吗?

干杯,

++t

对第二个参数使用非推导上下文。和一个const-引用作为参数,以允许右值。

template <typename T> struct identity {using type = T;};
template <typename T>
using identity_t = typename identity<T>::type;
template<class T>
toto<T> operator+(toto<T> const&, identity_t<T> const&)
{
     std::cout <<  "hello " <<std::endl;
}

未推导的上下文将导致推导忽略某个参数的调用参数,因为无法推导调用的模板参数。在某些情况下,就像这里一样,这是可取的,因为不一致的扣除已经不可能了。换句话说,第二个参数的类型完全取决于调用的第一个参数,而不是第二个(可以隐式转换)。

toto<float> d = t + 2.3;

现在应该编译演示

您可以这样使用enable_if

template<class T, class D, typename = typename std::enable_if<std::is_arithmetic<D>::value>::type>
toto<T> operator+(toto<T> const&, const D&){
    std::cout <<  "hello " <<std::endl;
    return toto<T>();        
}

演示

enable_if往往不太漂亮,无法阅读,但其他方式会让人感觉更糟。我通常使用返回值类型来启用函数,因为它位于正面:

#include<type_traits>
#include<iostream>
template<class T>
class toto
{
    T a;
};
template<typename T,typename D> 
typename std::enable_if< std::is_arithmetic<D>::value
                       // && some other constraint
                       // && etc.
    , toto<T> >::type operator+(toto<T> const&, D const&)
{
    std::cout <<  "hello " <<std::endl;
}
int main() 
{
    toto<float> t;
    toto<float> d = t +2.3;
}