通过比较两个容器的示例了解模板原型

understanding template prototype through an example of comparing two containers

本文关键字:了解 原型 比较 两个      更新时间:2023-10-16

请考虑以下代码:

// 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>的目的是什么?

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

谢谢

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

你的意思是

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

它不是一个函数原型;它定义了一个类型(T1{} == T2{}结果的类型,粗略地说,显然应该是bool的),但前提是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++ 的模板编程中起着重要作用。我建议你研究一下。