Thread: Operator Problem

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    67

    Smile 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

  2. #2
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    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.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

Popular pages Recent additions subscribe to a feed