0

I have a weird union I am using for alignment reasons.

I have overloaded it so that it can be assigned a string value.

Now I wish to overload the = operator so that I can assign it TO a string value.

union Tag { std::string * path; long id; }; struct TextureID { Tag ID; int type; TextureID& operator= (std::string str){ ID.path = new std::string(str); type=0; } TextureID& operator= (long val){ ID.id = val; type=1; } }; 

In this case we have overloaded the operators such that

TextureID t = "hello"; 

Is a valid statement.

How may I overwrite the = operator to be able to do:

string s = t; 
15
  • Sounds like an XY problem - I cannot believe there is any reason for attempting to do this. Commented Jul 13, 2018 at 22:46
  • 1
    Is this Q&A any help? How do conversion operators work in C++? Commented Jul 13, 2018 at 22:47
  • Also if you compiler is up to date with the C++17 standard you should take a look at std::variant. Commented Jul 13, 2018 at 22:48
  • @NeilButterworth How is this an XY problem? All I want is to be able to assign to a string the value stored in the union. Seems pretty simple conceptually. Commented Jul 13, 2018 at 22:49
  • 1
    1201ProgramAlarm's posted as good an answer for the actual question as I think you can get, and the comments are wandering off topic for Stack Overflow. Once you have this all sorted out and working, I recommend making a little sample program demonstrating TextureID and how you use it and post over at Code Review to see what improvements/alternatives are out there. Commented Jul 13, 2018 at 23:30

1 Answer 1

3

You can create a conversion operator to convert your TextureID to a std::string

operator std::string() const { // logic to create a string to return } 

or create an explicit function to do the conversion

std::string to_string() const { // logic to create a string to return } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.