使用类/函数模板组合进行意外诊断
Unexpected diagnostic with a class/function template combination
我创建了一个定义二维矢量类型的类模板,其中成员具有可变数据类型。
template<class Type> struct XY
{
Type X, Y;
XY() {}
XY(Type X, Type Y): X(X), Y(Y)
Type Square() const { return (X * X + Y * Y); }
};
此外,我重载了减号运算符并定义了一个额外的S
函数。
template<class Type> XY<Type> operator-(const Type& P, const Type& Q)
{ return XY<Type>(P.X - Q.X, P.Y - Q.Y); }
template<class Type> Type S(const XY<Type>& P, const XY<Type>& Q)
{ return (P - Q).Square(); }
现在下面的代码无法编译,在VS2008下:
void main()
{
struct XY<int> P, Q;
S(P, Q);
}
最让我困惑的是错误消息,说
Error 1 error C2440: 'return' : cannot convert from 'XY<Type>' to 'int'
在定义函数的行S
.
减法的结果显然是一个struct XY
,应用于它的方法Square
返回一个标量,不需要任何转换。
任何解释?
你不是说
template<class Type> XY<Type> operator-(const XY<Type>& P, const XY<Type>& Q)
而不是
template<class Type> XY<Type> operator-(const Type& P, const Type& Q)
后者显然不叫。在函数S
中,编译器尝试调用内置operator -
进行int
,因此尝试将参数转换为P
和Q
转换为int
(这是不可能的,因此会出现错误(。
相关文章:
- 在C++中对T*类型执行std::move的意外行为
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 处理除以零会导致<csignal>意外行为
- vscode下的Arduino代码出现意外编译错误
- 使用++运算符会导致意外的结果
- 套接字读取后,我在缓冲区中看到意外输入
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 使用vscode调试时,GDB意外退出
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 尝试将字符串/字符转换为整数会产生意外结果
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 当简单捕获中的标识符显示为参数的声明符 ID 时,没有编译器诊断
- C++标头错误 C2238 意外标记";"
- C++中意外的多头值
- vector.size() 在比较中意外工作
- 使用 malloc() 时出现意外大小
- 多线程程序中出现意外的内存泄漏
- 为什么static_cast基础类型的枚举类int8_t获得意外值?
- 字符串比较中的意外输出
- 使用类/函数模板组合进行意外诊断