Workaround for the Lack of MSVC++ Template Support

I’ve been bitten by MSVC++’s inability to have templated methods without the whole class being templated and today I figured out a workaround that allows you to maintain most of the elegant design and still compiles under MSVC++.

Often, templated members are used to provide default implementation for pure virtual functions. Here’s an example:

 class CPushMe {public:	virtual void PushDown() = 0;private:	template	static void PushDownImpl(TVal val, TContainer container)	{		TContainer::iterator it = container.begin();		while( it != container.end() )		{			it->Apply(val);			it->Push();			++it		}	};};


Unfortunately, the above class doesn’t compile. Here’s the workaround that I used in my latest project:

 class CPushMe {public:	virtual void PushDown() = 0;private:	template	class Impl {		static void PushDownImpl(TVal val, TContainer container)	{			TContainer::iterator it = container.begin();			while( it != container.end() )	{				it->Apply(val);				it->Push();				++it			}		}	};};

Now, a generic implementation is provided and everything compiles.

 class CPushMe2 : public CPushMe {public:	virtual void Push {		Impl::PushDownImpl(m_myVal, m_someCollection);	}};
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: