-
Operator Problem
Hello :)
Is there a way to perform mathematical operations with the following custom datatype:
Code:
#include <iostream>
#include <string>
#include <vector>
#include <boost/variant.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
typedef boost::variant< int, string > IntStr;
int main()
{
//Pre-operation is legal
IntStr a = 1 + 2; //a = 1+2
cout << a; //outputs 3
cout << endl;
//Post-operation is illegal
IntStr b = 1; //b = 1
cout << b + 2; //outputs error
cout << endl;
}
Error:
no match for 'operator+' in 'b + 2'
Note:
candidates are: std::_Bit_iterator std:: operator+(ptrdiff_t, const std::_Bit_iterator&)
std::_Bit_const_iterator std:: operator+(ptrdiff_t, const std::_Bit_const_iterator&)
Thanks :)
-
All you have to do is define the operation. If you wanted your operator+ to be integer addition, you could do something like this:
Code:
IntStr operator+(const IntStr& i1, const IntStr& i2)
{
return IntStr(boost::lexical_cast<int, IntStr>(i1) + boost::lexical_cast<int, IntStr>(i2));
}
Of course, operator+ isn't exactly obvious in this case. I could also see operator+ being a concatenation of the strings.