When using a container class like vector, list, etc., I can use the type of the elements by writing vector<type>::value_type.
However, the following code
template<class container> void foo(container& c) { typedef container::value_type elementtype; elementtype b; }
fails with the error ‘expected initializer before ‘elementtype’‘. Is it possible to infer the element type when the container type is given as a template argument or do I have to give the element type as an extra template argument?
You’re missing the required typename keyword:
This is because
containeris a dependent name in this template, so the compiler has no way of knowing whether container::value_type is always a type or not, as it may depend on the choice ofcontainer.Surely this question is a FAQ somewhere?
Edit, it is: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18