Jump to content

Custom Cast() function with templates


Josh
 Share

Recommended Posts

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>());
	}

 

  • Like 1

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

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;
}

 

Link to comment
Share on other sites

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.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...