Dai Haoci
Dai Haoci

Reputation: 209

Why my implicit conversion function doesn't work?

I have a wrapper class and I want to modify the data and convert it back to its original type.

class A
{
public:
    A ( unsigned __int64 _a ) : a (_a)
    {
    }
    operator unsigned __int64 () const
    {
        return a;
    }
    unsigned __int64 a;
}; 

I want the object of this class to implicitly convert back to unsigned __int64, but it failed.

Say,

 A a( 0x100ull );
 unsigned __int64 b = (a >> 16);  // Error

Compiler gives C2678 error, no operator found or there is no acceptable conversion. It seems this function operator unsigned __int64 () const doesn't work.


To be more specific, compiler says there is no acceptable conversion. I cannot accept the complain, because I have already given a good one. Can someone legitimize it?

Upvotes: 2

Views: 276

Answers (1)

Tony The Lion
Tony The Lion

Reputation: 63190

It doesn't work because you haven't created an operator>> overload for your class that takes an integer and does something with it.

I'm guessing you're trying to do a right shift on your int, but I'm not sure that overloading your operator>> is a good idea for that, as these operators in a context like that, are normally used for streaming. It might confuse a reader or maintainer of your code afterwards.

See here for more info on operator overloading

Perhaps rethink your implementation strategy?

Upvotes: 3

Related Questions