简体   繁体   中英

Why cant cast from pointer to reference to pointer in template function

I have error in compile time

INLINE template<typename T> T *&Animation::GetKey(int subAnim, int node, int frameInSubAnim)
{
    const int keyIndex = GetKeyIndex(subAnim, node, frameInSubAnim);
    return static_cast<T*>(m_Keys[keyIndex]);
}

With following error

d:\before_me\motion\pipeline\animation\AnimationData.inl(98): 
error C2440: 'return' : cannot convert from 'Motion::Animation::Key *' to 'Motion::Animation::Key *&'

and how i can workaround it?

The compiler is telling you that the static_cast<T*>(...) yields a temporary ( rvalue ) and that cannot be bound by a non-const reference (return type is T*& ). Note that even it it would bind to T*const& you don't really want that.

It is not clear what you are trying to achieve, but consider returning T* (drop the reference).

I think this captures what you want and provides a hideous workaround

void* m_keys[] = { 0, 0, 0 };

template<typename T>
T*& foo(const int index)
{
    return *reinterpret_cast<T**>(&m_keys[index]);
}

int main()
{
 foo<int>(0) = new int();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM