8

Reading a book A tour of c++ (second edition), 2018, I didn't understand an explanation about templates (I'll explain below).

Two function signatures are given for a find_all function that returns a vector of iterators to all occurrences of a given value in a given container.

#1 :

template<typename C, typename V>
vector<typename C::iterator> find_all(C& c, V v);

#2 :

template<typename T>
using Iterator = typename T::iterator;
template<typename C, typename V>
vector<Iterator<C>> find_all(C& c, V v) ;

Both can be used like this :

string m {"Mary had a little lamb"};
for (auto p : find_all(m,'a')) // here p is a string::iterator
    cout << *p << endl; // spoiler alert : this will print 'a's

The #2 using alias template is said to

hide the implementation detail by introducing a type alias for Iterator

by the author.

Although I think I understand both usage of templates, I don't understand why would #2 "hide the implementation detail" and why it is preferred ... Can anyone explain me ?

Thanks !

Ps : I didn't provide the post with the definition of the functions (same for both signatures) because I think it isn't relevant, but I'll add it if anyone needs it.

1 Answer 1

6

Lets say you have a code base like

template<typename C, typename V>
vector<typename C::iterator> first(C& c, V v);
template<typename C, typename V>
vector<typename C::iterator> second(C& c, V v);
template<typename C, typename V>
vector<typename C::iterator> third(C& c, V v);
template<typename C, typename V>
vector<typename C::iterator> fourth(C& c, V v);
...

If you decide you want to change to return a vector of const_iterator instead of iterator, you'd need to change all of those functions. When using

template<typename T>
using Iterator = typename T::iterator;
template<typename C, typename V>
vector<Iterator<C>>  first(C& c, V v);
template<typename C, typename V>
vector<Iterator<C>>  second(C& c, V v);
template<typename C, typename V>
vector<Iterator<C>>  third(C& c, V v);
template<typename C, typename V>
vector<Iterator<C>>  fourth(C& c, V v);

all you would have to do is change

template<typename T>
using Iterator = typename T::iterator;

to

template<typename T>
using Iterator = typename T::const_iterator;

and you're done. This is how it "hides the implementation detail".

2
  • See, I was thinking along those lines, but I was thinking of specializing using, which apparently isn't a thing. That concept makes a lot more sense.
    – user10957435
    Jan 8, 2021 at 22:56
  • 1
    @limserhane: Also consider that you can have an arbitrarily complicated expression on the right side of = (so long as it results in a type). The alias usually turns it into a very simple and understandable type instead.
    – AndyG
    Jan 8, 2021 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.