C++ 如何检查分配给呼叫接线员结果的类型?
我正在尝试创建一个简单的矩阵类 “mymat.h”的相关部分 它打印 0 0 0 0 500 0 0 0 0 Error, unexpected type! 0 0 0 0 500 0 0 0 0 错误,意外类型! 但使用呼叫接线员时:C++ 如何检查分配给呼叫接线员结果的类型?,c++,templates,operator-overloading,C++,Templates,Operator Overloading,我正在尝试创建一个简单的矩阵类 “mymat.h”的相关部分 它打印 0 0 0 0 500 0 0 0 0 Error, unexpected type! 0 0 0 0 500 0 0 0 0 错误,意外类型! 但使用呼叫接线员时: #include <iostream> #include "mymat.h" int main() { MYMAT<int> m(3, 3); m(2, 2) = 500; m.print
#include <iostream>
#include "mymat.h"
int main()
{
MYMAT<int> m(3, 3);
m(2, 2) = 500;
m.print_mat();
m(2, 2) = 500.0;
m.print_mat();
}
#包括
#包括“mymat.h”
int main()
{
mymatm(3,3);
m(2,2)=500;
m、 print_mat();
m(2,2)=500.0;
m、 print_mat();
}
它打印:
0 0 0
0 500 0
0 0 0
0 0 0
0 500 0
0 0 0
0 0 0
0 500 0
0 0 0
0 0 0
0 500 0
0 0 0
如您所见,该值从double转换为int
如何将
set()
中的条件应用于call operator?以实现您想要的:
m(2, 2) = 500.0; // do custom checks for conversions from
// right hand side to left hand side
从operator()
返回T&
不起作用,因为您无法控制到T
的隐式转换。在这种情况下,无法阻止从double
到int
的转换
相反,您可以从自己编写的operator()
返回一个类型,这样您就可以控制隐式转换。此类型需要保留左侧的信息,即m
的This
指针以及operator()
的参数。只需支持运算符=
即可检查右侧的隐式转换:
private:
struct Wrapper
{
MYMAT *t; // holds onto the this pointer
int x, y;
template <typename C>
void operator=(C val)
{
t->set(x, y, val); // uses MYMAT::set to do the conversion checking
}
};
定义如下:
public:
Wrapper operator ()(int x, int y);
template<typename T>
inline auto MYMAT<T>::operator()(int x, int y) -> Wrapper
{
return {this, x, y};
}
模板
内联自动MYMAT::operator()(int x,int y)->Wrapper
{
返回{this,x,y};
}
这里有一个.无关:
\u MYMAT\u H\u GUARD\u
是非法标识符。看见它很少咬人,但是当它咬人的时候,它是一个严肃的想法。也没有关系:为了简洁起见,您可能忽略了特殊的成员函数,但如果没有,请阅读。一旦您返回了T&
,您就没有什么可以做的来防止调用代码弄乱它了。如果您想强制更改值以通过set
中的检查,您可以将operator()
更改为const&operator(int,int)const
,但这将使其成为只读的。@NathanPierson已经很好地解决了这一问题<代码>m(2,2)=500.0不进行类型检查,并愉快地隐式转换为double
,以适应int
。据我所知,你对此无能为力。
public:
Wrapper operator ()(int x, int y);
template<typename T>
inline auto MYMAT<T>::operator()(int x, int y) -> Wrapper
{
return {this, x, y};
}