views:

186

answers:

2

Hi, I defined two classes:

class Token_
{
public:
    virtual char operator*()const = 0;//this fnc cannot run implicitly
protected:
    Token_()
    { }
    Token_(const Token_&);
    Token_& operator=(const Token_&);
};

and second:

class Operator : public Token_
    {
    public:
    Operator(const char ch):my_data_(token_cast<Operator_enm>(ch))
    { }
    Operator_enm get()const
    {
     return my_data_;
    }
    Operator_enm set(const Operator_enm& value)
    {
     Operator_enm old_value = get();
     my_data_ = value;
     return old_value;
    }
    char operator*()const//this operator has to be invoke explicitly
    {
     return static_cast<char>(my_data_);
    }
private:
    Operator_enm my_data_;
};

and later on in program I have something like this:

template<class R>
R Calculator::expr_()const
{
    Token_* token = read_buffer_();
    switch (*token)//here if I use explicit call of operator*() it works
    {
    case PLUS:
     {
      R result ;//not defined yet
      return result;
     }
    case MINUS:
     {
      R result ;//not defined yet
      return result;
     }
    default:
     cerr << "Bad expr token.";
    }

}

Why this call of operator*() can't be implicit? Is there any way to make it implicit? Thank you.

+5  A: 

token is a pointer to a Token_ object, not a Token_ object itself, thus the * operator in the switch statement dereferences only the pointer (thereby only obtaining the object), but doesn't then continue to call the operator you defined.

Try instead:

switch(*(*token)) {

The use of your custom operator * might be a bit confusing now though.

Another options is to alter read_buffer_() such that you can do the following:

Token_ token = read_buffer_(); // NOTE: read_buffer_() returns a Token_ object directly
switch (*token)//here if I use explicit call of operator*() it works

In that case, Token_ objects mimic pointers, and you wouldn't return pointer to pointers normally either.

catchmeifyoutry
...So to invoke your defined operator, write `**token`.
Dave Hinton
Works, thanks. I wonder how many years one have to spend with pointers to not get surprised by them?
There is nothing we can do
"how many years?" 42, of course
catchmeifyoutry
A: 

The other option is instead of:

Token_* token = read_buffer_();

do:

Token_& token = *read_buffer_();
Mike DeSimone