运算符+和浮点参数
operator + and float argument
我对模板有一个奇怪的问题,我正在尝试在模板类和"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;
}
相关文章:
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- 运算符重载:"operator+"必须采用零个或一个参数
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 参数相关查找和流运算符重载
- C++:使用运算符 = 调用多参数构造函数
- 了解布尔运算符==(参数 1,参数 2)
- 我能否根据其运算符()的签名专门化可变参数模板参数
- SFINAE 检查模板参数运算符
- 不允许运算符 const 参数调用 const 成员函数
- 为私有结构定义双参数运算符重载
- C++ 通过自定义赋值运算符隐式转换函数参数
- 函数参数变量总是需要 & 或 * 运算符吗?
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 可变参数模板参数转发使用逗号运算符
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 具有两个或多个模板参数的 C++ assigment 运算符
- 将多个参数传递给运算符 []
- 如何使用类的参数重载运算符+?
- 不允许在C++中使用多参数运算符 [] 的根本原因