Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何检查分配给呼叫接线员结果的类型?_C++_Templates_Operator Overloading - Fatal编程技术网

C++ 如何检查分配给呼叫接线员结果的类型?

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

我正在尝试创建一个简单的矩阵类

“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_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};
}