• Advertisement
Sign in to follow this  

Using type of element in a container as a parameter?

This topic is 1930 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
I think you missed typename before ContainerType::value_type
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
Sign in to follow this  

  • Advertisement