C ++ templates and namespace access

Let's say I use a template class with something simple:

template <class T> 
class MyClass

I want to use elements from the T namespace, for example T could be a string, and I wanted to use

T::const_iterator myIterator; 

... or something like that. How do I achieve this? Perhaps this is either impossible or very simple, but I have no idea.

Thanks for answers!

+3
source share
2 answers

By default, if it Tis a template parameter, as in your example, it is assumed that it T::some_memberdoes not indicate a type. You must explicitly state what it is, prefix it with typename:

typename T::const_iterator myIterator;

This fixes some parsing issues, as in the following example.

// multiplication, or declaration of a pointer?
T::const_iterator * myIterator;

, typename, , , . .

+12

.

template< typename T >
class Example
{
    void foo( const T& t )
    {
        typedef typename T::value_type Type;
        typedef typename T::const_iterator Iter;
        Iter begin = t.begin();
        Iter end = t.end();

        std::copy( begin, end, std::ostream_iterator<Type>(std::cout) );
    }
};

- typedef.

+5

Source: https://habr.com/ru/post/1726544/


All Articles