Re: Overloading reference operator
On 05/12/2010 05:51 PM, sebastian wrote:
On May 11, 11:56 am, samjam86 <samkitj...@gmail.com> wrote:
Hi,
I overloaded reference operator in a templatized class like below:
template<class T>
MyClass
{
public:
MyClass() : m_data(10) { }
operator T&() { return m_data; }
private:
T m_data;};
Now I wrote a code to utilize reference operator as below:
int main()
{
MyClass instance;
instance++; // this works fine
++instance; // this too works fine
instance = 105; // this gives compile error. Why ?
return 0;
}
The pre and post increment operators work fine, but a simple
assignment operator is giving compilation error.
Is there a valid reason for this or is this undefined behavior ?
Thank you.
Regards,
Samkit
The result of the implicit conversion operator can't be used as an l-
value, unfortunately (major language flaw, IMO).
Perhaps the following will reveal why using an implicit conversion as an
l-value fails, and is not a flaw.
The problem here is there is neither of these 2 member functions are
implemented in the class
MyClass(const T &inp) ( m_data = inp; }
MyClass &operator = (const T &inp) ( m_data = inp; return *this }
both of which provide a method for assignment to MyClass using a
variable of type T. Try it with my updated code sample.
template<class T>
class MyClass
{
public:
MyClass() : m_data(10) { }
//MyClass(const T&inp) { m_data = inp; }
operator T&() { return m_data; }
MyClass &operator=(const T&inp) { m_data = inp;return *this; }
private:
T m_data;
};
int main()
{
MyClass<int> instance;
instance++; // this works fine
++instance; // this too works fine
instance = 105; // this gives compile error. Why ?
return 0;
}
Note the constructor use will not work if it is made explicit.
Hope this clarifies things.
JB