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){}: } 
3
  • Please present a complete example that readers that can try out. Commented Aug 1, 2018 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. Commented Aug 1, 2018 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! Commented Aug 1, 2018 at 11:04

1 Answer 1

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);.

Sign up to request clarification or add additional context in comments.

9 Comments

but why I can't use operator=, if c++ allows you, or is it only can return Token?
@RamzanChasygov read the relevant part of this: stackoverflow.com/questions/4421706/…
@RamzanChasygov You can't overload operator= to accomplish this, I added some explanations at the beginning. And you can get more from the link I posted.
@songyuanyao Sorry, I did't see it
For a bonus point recommend explicit (if supported) to fix the implicit conversion "problem".
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.