devxlogo

Workaround for the Lack of MSVC++ Template Support

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);	}};
See also  Monetize TikTok For Your Business
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist