views:

230

answers:

3

Hi all! I have the following class CppProperty class that holds value:

template<typename TT>
class CppProperty
{
    TT val;
public:
    CppProperty(void)
    {
    }

    CppProperty(TT aval) : val(aval)
    {
    }

    CppProperty(const CppProperty & rhs)
    {
        this->val = rhs.val;
    }

    virtual ~CppProperty(void)
    {
    }

    TT operator=(TT aval)
    {
        this->val = aval;
        return this->val;
    }

    friend TT operator++(CppProperty & rhs);
    friend TT operator--(CppProperty & rhs);
    friend TT operator++(CppProperty & rhs, int);
    friend TT operator--(CppProperty & rhs, int);

    //template<typename RR>
    //friend RR operator=(RR & lhs, const CppProperty & rhs);
    //friend int & operator=(int & lhs, const CppProperty & rhs);
    //int reinterpret_cast<int>(const CppProperty & rhs);
};

I want to do assignment like this:

CppProperty<char> myproperty(10);
myproperty++;
int count = myproperty;

How this can be done? I can't override the operator=. Any help is greatly appreciated! Thank you!

+1  A: 

You need to provide operator int() to your class to allow the implicit conversion to int.

Naveen
Hi Naveen! Thanks for quick reply. Then how to convert to different classes/datatypes using operators?
Viet
+5  A: 

You'd need a conversion operator:

operator const TT&(void) const
{
    return val;
}


operator TT&(void)
{
    return val;
}

There is a brief tutorial on conversion operators here. In short, when the compiler tries to convert a type, it will first look at the right-hand side for an operator that will convert it to the desired type. What we are doing is saying "Whatever TT is, this class can be converted to it".

If no operators are found, it looks to see if the left-hand side can be constructed from the right-hand side, and so on. (Until, if it cannot find a conversion, it emits an error.)


You can remove your explicitly defined default constructor if you declare your other constructor like this:

// If not specified, construct with default-constructed type.
CppProperty(TT aval = TT()) : val(aval)
{
}
GMan
Thanks GMan! Looks cool! Let me try and get back to you in a short while ;)
Viet
It works like charm! Thanks again!
Viet
No problem, make sure your `const`'s are in the correct location, I had them backwards in the first post.
GMan
I've noted. Thanks again ;)
Viet
Naveen
thanks for the explanation and link.
Naveen
Indeed. Did you mean you didn't understand it before or until now?
GMan
I knew about the conversion operators..but didn't think that it can be used with templates..I thought I should always hardcode the class name in the operator.
Naveen
Ah, I see. Yup any type will do, even if it's a template.
GMan
+1  A: 

You may overload a typecast:

http://www.learncpp.com/cpp-tutorial/910-overloading-typecasts/

Hi shaleo! Thanks for your help. I've managed to get things done using GMan's advice. I'm looking into yours now :)
Viet