This the below program i have written for some test.
class tgsetmap
{
public:
std::map<std::string,std::string> tgsetlist;
void operator<<(const char *str1,const char *str2)
{
tgsetlist.insert( std::map<std::string,std::string>::value_type(str1,str2));
}
};
int main()
{
tgsetmap obj;
obj<<("tgset10","mystring");
obj.tgsetlist.size();
}
This throws a compilation error:
“test.cc”, line 10: Error: Illegal number of arguments for tgsetmap::operator<<(const char, const char*).
“test.cc”, line 22: Error: The operation “tgsetmap << const char*” is illegal.
2 Error(s) detected.*
Am i wrong some where?
You can’t force
operator<<to take two arguments on right-hand side. The following code:does not work as a function call with two arguments but instead just uses the
,operator. But it’s probably not what you are interested in.If you need to pass two arguments to the
<<operator, you need to wrap them in some other (single) type. For example, you could use the standard std::pair, i.e.std::pair<const char*, const char*>.But note that the
operator<<should also return some reasonable type suitable for<<chaining. That would probably be atgsetmap&in your case. The following version should work fine:Note that I’ve added typedefs to not have to repeat the type names over and over again. I’ve also made
operator<<return atgsetmap&so that<<could be chained (used like in the modifiedmain()above). And finally, I’ve reused thestd::map<...>::value_typeto make it simpler but you could also use any other type of your own.But I believe that you may prefer using a regular method instead. Something like:
(inside the class declaration), and then: