Sign in to follow this  
Servant of the Lord

Using type of element in a container as a parameter?

Recommended Posts

I have the following code that won't compile:
[code]template<class ContainerType>
void MyFunc(ContainerType &container, ContainerType::value_type fallback = ContainerType::value_type())[/code]

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: [b]std::vector<int>::value_type fallback = std::vector<int>::value_type()[/b], which should be [b]int fallback = int()[/b].

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:
[i]error: 'ContainerType::value_type' is not a type[/i]

(This is for: [b]ContainerType::value_type fallback[/b])

[i]error: expected initializer before ')' token[/i]

(This is for: [b]= ContainerType::value_type()[/b])

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

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

And got these errors:
[i]error: expected type-specifier[/i]
[i]error: expected '>'[/i]

Where is my thinking going awry?

Share this post


Link to post
Share on other sites
wqking    761
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] Edited by wqking

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this