Home > Net >  cpp - alias for member functions` return types
cpp - alias for member functions` return types

Time:05-10

I've been watching this CppCon talk where the speaker was talking about writing classes resistant to future changes. He provided the following code as an example (that I show here abridged):

template< typename Type, size_t Cap >
class FixedVector final
{
    using iterator = Type*;
    
    iterator begin();
}

My question is, basically the following - Does he use type aliasing here only because the type itself is already provided by the user of the class (and is a priory know to them)? I mean, if that was not the case, then there is not way the user can use the aliased return type, right?

CodePudding user response:

The point they are trying to make is if they had

template< typename Type, size_t Cap >
class FixedVector final
{
    Type* begin();
}

and later they decide that instead of a Type*, they want to use a my_custom_iterator<Type>, then they need to make that change to all places that use Type*. By using

class FixedVector final
{
    using iterator = Type*;
    
    iterator begin();
}

if you want to make that same change it is as simple as changing

using iterator = Type*;

to be

using iterator = my_custom_iterator<Type>;
  • Related