理解模板雏形通过比较两个容器
问题描述:
的例子考虑下面的代码:理解模板雏形通过比较两个容器
// 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>());
?
这不是一个功能prototipe;它定义了一种类型(结果的类型大致为T1{} == T2{}
,显然应该是bool
),但是只有如果T1
和T2
是可比的。
所以,当你定义函数
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_type
和Container2::value_type
是可比的类型;替换失败(所以操作符没有实现,但没有编译错误),否则。
这种操作方法使用与首字母缩写SFINAE合成的规则:替换失败不是错误。
它在现代C++的模板编程中扮演着重要的角色。我建议你学习它。
你的问题没有什么意义**,因为代码包含一个解释'equals_op_type'的目的的注释。**所以你的问题的答案正是上述代码中的第一个注释:** //获取返回类型为T1的T1和T2 **。 – Phil1970