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

老子叫甜甜 提交于 2019-11-28 04:31:50

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!