0

I have struct Token, to which I'm trying assign operator=. I wanna be able to assign to char. I tried char operator=(const Token& token){ return token.kind; }, which throws error, says is not unary operator, tried char operator=(const char& ch, const Token& token){ return token.kind; } didn't help either. Yes I can do just char ch { token.kind };, but I wanna do it through operator in case if add some logic. Can you help me?

REPL EXAMPLE

struct Token {
  char kind;
  int value;

  Token(char kind, int value): kind(kind), value(value){}:
}
Rami Chasygov
  • 2,714
  • 7
  • 25
  • 37
  • Please present a complete example that readers that can try out. – Cheers and hth. - Alf Aug 01 '18 at 10:37
  • 1
    You want `Token::operator char() const;` in in your token class. Beware this can give unexpected results. Prefer `Token::as_char() const;` instead. – Richard Critten Aug 01 '18 at 10:38
  • For the record, that explicit conversion is (IMO) much better. Adding implicit conversions to primitive types is the route to madness. Your logic that you want to give `Token` the power to decide how the conversion should be performed is reasonable, so a conversion operator makes some sense... but at least make it `explicit`! – Lightness Races in Orbit Aug 01 '18 at 11:04

1 Answers1

7

You can't overload operator= for built-in types like char, to allow assign Token to char. operator= must be overloaded as member function.

As the workaround, you can add a conversion function, which allows implicit conversion from Token to char. Note that implicit conversion might cause potential issues, e.g. it allows to pass a Token to a function which expects a char.

struct Token {
  char kind;
  int value;

  Token(char kind, int value): kind(kind), value(value){}
  operator char() const { return kind; }
};

BTW: You can make the conversion function explicit, to avoid the issues of implicit conversion. And then in the assignment from Token to char you have to apply explicit conversion, like c = static_cast<char>(token);.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405