C++ template specialization, calling methods on types that could be pointers or references unambiguously

后端 未结 1 1934
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 21:04

Summary

Is there a way to call a class method on a templated type that could be a pointer or a reference without knowing which and not get compiler/

相关标签:
1条回答
  • 2020-12-07 21:23

    Small overloaded functions can be used to turn reference into pointer:

    template<typename T>
    T * ptr(T & obj) { return &obj; } //turn reference into pointer!
    
    template<typename T>
    T * ptr(T * obj) { return obj; } //obj is already pointer, return it!
    

    Now instead of doing this:

     if(elem->Intersects(_bounds) == false) return false;
     if(elem.Intersects(_bounds) == false) return false;
    

    Do this:

     if( ptr(elem)->Intersects(_bounds) == false) return false;
    

    If elem is a reference, the first overload ptr will be selected, else the second will be selected. Both returns pointer, which means irrespective of what elem is in your code, the expression ptr(elem) will always be a pointer which you can use to invoke the member functions, as shown above.

    Since ptr(elem) is pointer, which means checking it for NULL be good idea:

     if( ptr(elem) && (ptr(elem)->Intersects(_bounds) == false)) return false;
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题