Josh Posted March 28, 2018 Share Posted March 28, 2018 I'm trying to create a simpler Cast() function: template <class T> shared_ptr<T> Cast(shared_ptr<SharedObject> o); Function definition: template <class T> shared_ptr<T> Cast(shared_ptr<SharedObject> o) { #ifdef DEBUG return dynamic_pointer_cast<T>(o); #else return static_pointer_cast<T>(o); #endif } But whenever I try to use it I get an unresolved external symbol error: shared_ptr<Entity> entity = CreateBox(); shared_ptr<Model> model = Cast<Model>(entity); I'm basically just wrapping dynamic_pointer_cast. Here is that function's definition: template<class _Ty1, class _Ty2> shared_ptr<_Ty1> dynamic_pointer_cast(const shared_ptr<_Ty2>& _Other) _NOEXCEPT { // dynamic_cast for shared_ptr that properly respects the reference count control block const auto _Ptr = dynamic_cast<typename shared_ptr<_Ty1>::element_type *>(_Other.get()); if (_Ptr) { return (shared_ptr<_Ty1>(_Other, _Ptr)); } return (shared_ptr<_Ty1>()); } 1 Quote My job is to make tools you love, with the features you want, and performance you can't live without. Link to comment Share on other sites More sharing options...
Josh Posted March 28, 2018 Author Share Posted March 28, 2018 This does not work either. template <class T, class Y> shared_ptr<T> Cast(shared_ptr<Y> o); Quote My job is to make tools you love, with the features you want, and performance you can't live without. Link to comment Share on other sites More sharing options...
thehankinator Posted March 28, 2018 Share Posted March 28, 2018 I don't know what the signature of CreateBox() is nor what Entity and Model classes look like but this compiles for me under VS2015 and MinGW 5.3.0 (Debug and Release for both). Entity had to have a virtual function to make it polymorphic. #include <memory> class Entity { public: virtual ~Entity() {} }; class Model : public Entity { public: virtual ~Model() {} }; template <class T, class Y> std::shared_ptr<T> Cast(std::shared_ptr<Y> o) { #ifdef DEBUG return std::dynamic_pointer_cast<T>(o); #else return std::static_pointer_cast<T>(o); #endif } std::shared_ptr<Entity> CreateBox() { return std::dynamic_pointer_cast<Entity>(std::make_shared<Model>()); } int main() { std::shared_ptr<Entity> entity = CreateBox(); std::shared_ptr<Model> model = Cast<Model>(entity); return 0; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.