cppn00b cppn00b - 25 days ago 7
C++ Question

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

Answer Source

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

Do you mean

template<typename T1, typename T2>
using equals_op_type = decltype(std::declval<T1>() == std::declval<T2>());

?

It isn't a function prototipe; it defines a type (the type of the result of T1{} == T2{}, roughly, that should be bool, obviously) but only if T1 and T2 are comparable.

So, when you define the function

template <class Container1, class Container2>
equals_op_type<typename Container1::value_type, typename Container2::value_type>
operator==(const Container1& c1, const Container2& c2) {
    // function code
    return true; // or false
}

it becomes

template <class Container1, class Container2>
bool
operator==(const Container1& c1, const Container2& c2) {
    // function code
    return true; // or false
}

if Container1::value_type and Container2::value_type are comparable types; the substitution fail (so the operator isn't implemented but without compilation error) otherwise.

This way of operate use the rule that is synthesized with the acronym SFINAE: Substitution Failure Isn't An Error.

It plays an important role in template programming in modern c++. I suggest you of study it.