C++ 隐式运算符bool()未响应我的调用
我正在测试一个模板:C++ 隐式运算符bool()未响应我的调用,c++,operator-overloading,C++,Operator Overloading,我正在测试一个模板: template<typename Key> struct _Tarray<Key, char>{ map<const Key, string> data; //stuff operator bool(){cout << " just testing"; return false;} //trying to call this, but its not answering }; 模板
template<typename Key>
struct _Tarray<Key, char>{
map<const Key, string> data;
//stuff
operator bool(){cout << " just testing"; return false;} //trying to call this, but its not answering
};
模板
塔雷结构{
地图数据;
//东西
操作符bool(){cout在你的操作符var
中是一个常量&
。这里的重要信息是它是const
,这意味着如果var
修改了var
的属性,就不能从var
调用任何函数
编译器不知道您的运算符bool
没有修改任何内容,因此它失败。您必须通过将函数指定为const
,明确声明您的运算符bool
不会修改\u Tarray
:
//Note the 'const', operator bool own't change anything, so the call from a const
//instance is legal
operator bool() const
{
std::cout << "Just testing\n";
return false;
}
//注意“const”,操作符bool own不会改变任何东西,因此来自const的调用
//这是合法的
运算符bool()常量
{
std::cout调用什么?此问题无法满足a的“完整”要求。请相应地更新您的问题。什么都没有!只是一个编译器错误:检查上面的“新建编辑”。@OsagieOdigie请停止对非HTML、CSS、JS代码使用堆栈片段。对于普通代码,请使用“代码块”按钮。
template<typename T, typename U>
ostream& operator<< (ostream& os, const _Tarray<T, U>& var){
//now i expect operator bool() to be called here
if(var){os << " Yes !";} //and bool is not being called. my compiler (g++) is angry
else{cout << " No !";}
return os;
}
./template.h: In instantiation of 'std::ostream& operator<<(std::ostream&, const _Tarray<T, U>&) [with T = int; U = char; std::ostream = std::basic_ostream<char>]':
./template.h:128:41: required from 'void var_dump(const T&) [with T = _Tarray<int, char>]'
functions.cpp:12:21: required from here
./template.h:122:5: error: passing 'const _Tarray<int, char>' as 'this' argument discards qualifiers [-fpermissive]
if(var){os << "heheheheh";}
^
./template.h:73:5: note: in call to '_Tarray<Key, char>::operator bool() [with Key = int]'
operator bool() const {cout << " just testing"; return false;}
//Note the 'const', operator bool own't change anything, so the call from a const
//instance is legal
operator bool() const
{
std::cout << "Just testing\n";
return false;
}