Need C++ help with overloading definition of a value
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Need C++ help with overloading definition of a value
The title is probably misleading, but here is what I am trying to do... and of course it doesn't compile. Any idea why I cannot get a TokenString to auto-convert to an std::string or const char* that can be used for string assignment?
Code:
#include <string>
#include <cstdlib>
class TokenString
{
public:
TokenString(const std::string& str) : m_str(str) {}
operator std::string() const { return m_str; }
operator int() const { return atoi(m_str.c_str()); }
operator unsigned int() const { return atoi(m_str.c_str()); }
operator double() const { return strtod(m_str.c_str(), 0); }
operator const char*() const { return m_str.c_str(); }
private:
std::string m_str;
};
int main()
{
TokenString tk("foo");
// This is ok
std::string str1 = tk;
// This is ok
std::string str2;
str2 = "foo";
// This is NOT ok
std::string str3;
str3 = tk; <--- Will not compile!
}
It's an ambiguous overload. std::string has assignment operator overloads for const std::string &, const char *, and char, and can't decide which combination of conversion operators and assignment operators to use.
I suggest you do what some boost code does: create a template as() member function which is specialized for each kind of conversion. Or for that matter, use std::string rather than a special type and boost::lexical_cast to convert to whatever.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.