Search code examples
c++c++11templatesgeneric-programming

Question about template's value_type usage in Stroustrup's book example


In Stroustrup's "A Tour of C++" there is a code snippet

template<typename C>
using Value_type = typename C::value_type;  // the type of C’s elements

template<typename Container>
void algo(Container& c)
{
    /* (1) */ 
    Vector<Value_type<Container>> vec;  // keep results here
    // ...
}

Why we need this using, how it differs from writing in (1) just

Vector<Container::value_type> vec;

Solution

  • The reason is this declaration:

    Vector<Container::value_type> vec;
    

    is not actually valid, and is an error. Instead you need to write:

    Vector<typename Container::value_type> vec;
    

    which is more verbose.

    The purpose of the alias template Value_type is to make it more convenient to use a member type alias of Container without having to say typename each time.