Search code examples
c++templatescontainersc++-conceptstemplate-templates

How to get at a C++ Container<T>'s T if no Container::value_type is provided?


It's rather common that container templates contain a value_type typedef. This makes it easy to create other templated code, most recently concepts, which are able to extract the T if only having been given Container and not Container<T>.

However, not all containers (or other templated classes) define such a value_type, especially older ones. Is it possible to get to the contained T even without it?

I know there are tricks like "if it is an iterator then .begin() should return a value of that type", but that does not help us to e.g. write a concept-requirement that checks whether a class's .begin() indeed follows the requirements that iterators have.


Solution

  • Here's a solution that's similar to Quimby's solution but using partial template specialization instead:

    template<typename...>
    struct inner_type_impl;
    
    template<template<typename...> typename C, typename T, typename...Args>
    struct inner_type_impl<C<T,Args...>>
    {
        using type = T;
    };
    
    template<typename T>
    using inner_type = typename inner_type_impl<T>::type;
    

    Here's a demo that's borrowed from Quimby's solution.