samedi 23 septembre 2017

understanding template prototype through an example of comparing two containers

Consider the following code:

// get the return type of == for T1 and T2
template<typename T1, typename T2>
using equals_op_type = decltype(std::declval<T1>() == std::declval<T2>());

template <class Container1, class Container2>
equals_op_type<typename Container1::value_type, typename Container2::value_type>
operator==(const Container1& c1, const Container2& c2) {
    if(c1.size() != c2.size()) return false;
    auto itr2 = c2.begin();
    for(const auto& v : c1) {
        cout << v << " == " << *itr2 << "? ";
        if(v != *itr2++) return false;
    }
    return true;
}

This is a global function intended to compare two containers.

I don't understand the function's prototype. What is equals_op_type exactly?

Also, what is the purpose of equals_op_type<typename Container1::value_type, typename Container2::value_type>?

I'd appreciate your help, since I'm new to the templates concept.

Thanks

Aucun commentaire:

Enregistrer un commentaire