c++ - 运算符 + 和 float 参数

标签 c++ templates

我对模板有一个奇怪的问题,我正在尝试在两者之间进行基本添加 一个模板类和“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 被认为是 double 的,它与签名不匹配。我可以为我的 operator+ 使用第二个模板参数作为

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);

将此方法应用于 operator* 不起作用,因为编译器会提示默认参数被禁止。

有什么建议吗?

干杯,

++t

最佳答案

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

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;

现在应该编译,Demo .

关于c++ - 运算符 + 和 float 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705581/

相关文章:

C++模板模板非类型参数

javascript - 如何在 blaze 模板的模板上的另一个函数中创建该函数?

c++ - 使用模板时无效使用非静态数据成员

c++ - 如何表达我想做某事 "if a function returns true/false"

c++ - 需要有关在 VS2010 中运行程序的帮助

c++ - 如何处理 "signed/unsigned mismatch"警告 (C4018)?

xslt - 左侧修剪空白 xslt 1.0

c++ - 链接器错误,在 ubuntu 15.04 上使用 OpenCV 和 Eclipse CDT

c++ - 为什么 C++ 函数调用便宜?

python - 如何制作 python-mysqldb 模板?