通过比较两个容器的例子理解模板原型

understanding template prototype through an example of comparing two containers

考虑以下代码:

// 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;
}

这是一个全局函数,用于比较两个容器。

我不明白函数的原型。 equals_op_type 到底是什么?

另外,equals_op_type<typename Container1::value_type, typename Container2::value_type>的目的是什么?

非常感谢你的帮助,因为我是模板概念的新手。

谢谢

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

你是说

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

?

它不是函数原型;它定义了一个类型(T1{} == T2{} 的结果类型,粗略地说,应该是 bool,显然)但是 only if T1T2 具有可比性。

因此,当您定义函数时

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
}

变成

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

如果Container1::value_typeContainer2::value_type是可比较的类型;否则替换失败(因此运算符未实现但没有编译错误)。

这种操作方式使用由首字母缩略词 SFINAE 合成的规则:替换失败不是错误。

它在现代c++的模板编程中起着重要的作用。我建议你研究它。