views:

126

answers:

2

I have the following operator defined in a C++ class called StringProxy:

operator std::string&()
{
    return m_string;
}

a) What is this and how does this work? I understand the idea of operator overloading, but they normally look like X operator+(double i).

b) Given an instance of StringProxy, how can I use this operator to get the m_string?

+3  A: 

This is a conversion method. To get the m_string, simply use an explicit cast: (std::string)stringProxy to perform the conversion. Depending on context (e.g. if you're assigning to a string), you may be able to do without the cast.

Joey Adams
I believe in general the C++ static_cast would be preferable to the old style C cast.
Stephen Nutt
Joey Adams
@Joey: IMO that article is largely based on a premise that when people program in C, they are all gurus, whereas C++ programmers are untrainable noobs. The C-style cast does not automatically do the *right* thing, it will do *some* thing, more often than not a reinterpret cast. One still needs to know what exactly it does in each case to know if it does the desired thing. - And there is one place where you absolutely need type-safe alternatives to C's corresponding non-typesafe functionality: *templates*.
visitor
+2  A: 

It's a cast operator. They take the form of operator T() and enable casting between custom types. You can get the std::string out by simply assigning it to a regular string or reference.

DeadMG