JP van Oosten

C++ expected initializer

13 Apr 2009

When I was developing a new feature for Flexc++, I ran into a compiler error stating “expected initializer before ‘const’”.

I was building a function which returned an object of an inner class. However, the outer class was a class template, and the template parameter was used in the inner class:

template <typename StreamInfo>
class ScannerTemplate
{
	protected:
	struct BufferData
	{
		StreamInfo d_streamInfo;
	};
	public:
	BufferData const switchBuffer(StreamInfo const &streamInfo);
};

The implementation of switchBuffer looked like this:

template <typename StreamInfo>
inline ScannerTemplate<StreamInfo>::BufferData const       
	ScannerTemplate<StreamInfo>::switchBuffer(StreamInfo const &streamInfo)
{
	// ...
}

Why did I get the error that an initializer was expected?

After some digging, I found that this is a (deprecated) implicit typename: At compile time, the compiler does not know what the instantiation of ScannerTemplate looks like.

To turn this into an explicit typename, just prefix typename to the return type:

template <typename StreamInfo>
inline typename ScannerTemplate<StreamInfo>::BufferData const       
	ScannerTemplate<StreamInfo>::switchBuffer(StreamInfo const &streamInfo)
{
	// ...
}

For more information, look in the C++ Annotations as usual :)