C ++ using typedefs in non-built-in functions

I have a class like this

template< typename T >
class vector {
  public:
    typedef T &       reference;
    typedef T const & const_reference;
    typedef size_t    size_type;

    const_reference at( size_t ) const;
    reference at( size_t );

and then in the same file

template< typename T >
typename vector<T>::const_reference    // Line X
vector<T>::at( size_type i ) const
{
    rangecheck();
    return elems_[ i ];
}


template< typename T >
reference                              // Line Y
vector<T>::at( size_type i )
{
    rangecheck();
    return elems_[ i ];
}

Line X compiles fine, but line Y does not compile. Error message from g ++ (version 4.4.1):

foo.h:Y: error: expected initializer before 'vector'

From this, I understand that if I want to have non-built-in functions, then I must fully qualify the typedef name as on line X. (Note that size_typethere is no problem for that .)

However, at least for me, line X looks awkward.

Is there an alternative approach?

+3
source share
3 answers

, . , BTW, . .

, , , typename.

.

template< typename T >
typename vector<T>::const_reference
  vector<T>::some_method( const_reference r ) const
{
  // ...
}

, , ( ): typename

template< typename T >
typename vector<T>::const_reference
  vector<T>::some_method( typename vector<T>::const_reference r ) const
{
  // ...
}
+4

++. 42: " , , typename". size_t , . typedef, size_t.

: size_type DID .

#include <cstddef>

template< typename T >
class vector {
  public:
    typedef T &       reference;
    typedef T const & const_reference;

    const_reference at( typename T::size_type ) const;
    reference at( typename T::size_type );
};

template< typename T >
typename vector<T>::const_reference
vector<T>::at( typename T::size_type i ) const
{
    // ...
}

template< typename T >
typename vector<T>::reference
vector<T>::at( typename T::size_type i )
{
    // ...
}

struct Foo
{
    typedef size_t size_type;
};

int main()
{
    vector<Foo> f;
    return 0;
}

size_type - Foo.

+3

; , typedefs , . , , . , , , ? , IMHO, .

+2

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


All Articles