Skip to main content
GameDev.net gamedev.net
🔒 Locked

Using type of element in a container as a parameter?

Started by Servant of the Lord Oct 7, 2012 at 5:10 AM 1 replies 1.8k views
Original Post
Servant of the Lord
Servant of the Lord
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 into the function, it should be: std::vector::value_type fallback = std::vector::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::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?
wqking
wqking
I think you missed typename before ContainerType::value_type
[source]
template
void MyFunc(ContainerType &container, typename ContainerType::value_type fallback = typename ContainerType::value_type())
[/source]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.