Search code examples
c++eclipsecastingtypecast-operator

"invalid cast from type 'const myClass' to type 'int'", how can I make it valid?


I am getting an error about the return statement (or cast) in the final function in the following extract from a library header

///////////////////////////////////////////////////////////
// class __HashMapDefaultProviderT

/**
* @internal
* @class    __HashMapDefaultProviderT
* @brief    This is an implementation of the IHashCodeProviderT interface for the HashMap class.
* @since    1.0
*/
template<class KeyType>
class __HashMapDefaultProviderT
    :   public IHashCodeProviderT<KeyType>,
    public Object
{
public:

    // Lifecycle

    /**
    * This is the default constructor for this class.
    *
    * @since     1.0
    */
    __HashMapDefaultProviderT(void) {}


    /**
    * This is the destructor for this class.
    *
    * @since     1.0
    */
    virtual ~__HashMapDefaultProviderT(void) {}


    // Operation

    /**
    * Gets the hash code of the specified object
    *
    * @since        1.0
    * @return       The hash code of the specified object
    * @see          Osp::Base::Object::GetHashCode
    */
    int GetHashCode(const KeyType& obj) const
    {
        return (int)obj;
    }


};

the error is:

invalid cast from type 'const myClass' to type 'int'

What is the fix for this? The header file is called FBaseColHashMapT.h

I've added operator> and operator< methods already but I don't know how else to get my class to hash or how to permit the cast that is required above, short of inheriting it, but I'd like to see if I can avoid that. To support those two operators I wrote:

inline int GetHashCode() const {return myIntMember/4 + clientRect.GetHashCode();}

Maybe it could be of re-use again here?

I am supplying myClass as the key to this template class and int as the value.


Solution

  • Obviously the class expects the KeyType (in your case myDescriptor) to be convertible to int. Therefore the fix would be to add that conversion to myDescriptor:

    class myDescriptor
    {
    public:
      operator int() const { return (whatever the library expects, probably a hash key); }
      // ...
    };