Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit conversions and polymorphism

Tags:

c++

pretty straight-forward question, I am attempting to get an implicit conversion working with a polymorphic parameter, is there any way to get this working?

main.cpp

nickname nick("somenick");
client.send(nick_request(nick)); // original
client.send(nick); // Implicit conversion from nickname to nick_request

client.hpp

virtual void send(const request & rq)

nick_request.hpp

class nick_request : public request
{
    nick_request(const nickname & nick);
    ...
};

nickname.hpp

nickname(const std::string & name)

One solution would be to write out an overload for each type of "request", but that's tedious and defeats the point of the polymorphism.

like image 873
Francisco Aguilera Avatar asked Dec 02 '25 09:12

Francisco Aguilera


1 Answers

You might write a conversion function (from nickname to nick_request) in nickname.

class nickname {
public:
    nickname(const std::string & name) {}
    operator nick_request() const { return nick_request(*this); }
};

LIVE

See user-defined conversion

like image 112
songyuanyao Avatar answered Dec 04 '25 01:12

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!