Comparator for boost::any underlying type

298 Views Asked by At

I have a struct that is used for Tokenizing a byte stream (std::vector<uint8_t>). The stream can contain bytes, words, dwords, null-terminated strings and raw data.

struct Token {
    enum TokenClass {
        BYTE, WORD, INT, SZCHAR, DATA
    };

    TokenClass type;
    boost::any value;

    Token( TokenClass c, uint8_t b ) : type(c), value(b) { }
    Token( TokenClass c, uint16_t w ) : type(c), value(w) { }
    ... etc.
};

It seems to work up to the point where I try to check the value in a unit test.

ie:

// ts is of type std::vector<Token>
CHECK_EQUAL(Token::WORD, ts[0].type); // fine
CHECK_EQUAL(257, ts[0].value); // error!

gives an error of

error: no match for ‘operator==’ (operand types are ‘const boost::any’ and ‘const int’) if (!(expected == actual))

So I added a comparator to the class, just for the int:

bool operator==(const int rhs) const
{
    return boost::any_cast<int>(value) == rhs;
}

But that did nothing to alleviate the issue.

How do I compare the underlying type with values since once I start validation code then I will need to be able to compare values.

Also would boost::variant be better suited to what I need to do? In my quick read through of both it appeared that any was more suited to my task.

0

There are 0 best solutions below