Using type of element in a container as a parameter?

Started by
1 comment, last by Servant of the Lord 11 years, 6 months ago
I have the following code that won't compile:
template<class ContainerType>
void MyFunc(ContainerType &container, ContainerType::value_type fallback = ContainerType::value_type())


It will be passed something like an std::vector<> of unknown element-type.
I want it to take as the second parameter a variable of type 'element type of the container'.
I want the second parameter to default to "default initialized version of said type".

Isn't 'value_type' a standardized C++ container typedef? It's definitely present in the compiler I'm using (MinGW 4.6).

For example, if passing in a std::vector<int> into the function, it should be: std::vector<int>::value_type fallback = std::vector<int>::value_type(), which should be int fallback = int().

However, even before using the template, I get a compile error in any source files that #include the header with the templated function in it.

MinGW errors:
error: 'ContainerType::value_type' is not a type

(This is for: ContainerType::value_type fallback)

error: expected initializer before ')' token

(This is for: = ContainerType::value_type())

Why isn't ContainerType::value_type a type? std::vector<int>::value_type exists in the vector header.

I also tried this:
template<class ContainerType, class ElementType = ContainerType::value_type>
void MyFunc(ContainerType &container, ElementType fallback)


And got these errors:
error: expected type-specifier
error: expected '>'

Where is my thinking going awry?
Advertisement
I think you missed typename before ContainerType::value_type
[source]
template <class ContainerType>
void MyFunc(ContainerType &container, typename ContainerType::value_type fallback = typename ContainerType::value_type())
[/source]

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.

Yep, thanks a bunch!

This topic is closed to new replies.

Advertisement