通过比较两个容器的示例了解模板原型
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>
的目的是什么?
感谢您的帮助,因为我是模板概念的新手。
谢谢
我不明白函数的原型。
equals_op_type
到底是什么?
你的意思是
template<typename T1, typename T2>
using equals_op_type = decltype(std::declval<T1>() == std::declval<T2>());
?
它不是一个函数原型;它定义了一个类型(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++ 的模板编程中起着重要作用。我建议你研究一下。
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 正在尝试了解输入验证循环
- 了解 GLM- openGL 中的相机转换
- C++我需要了解在哪里使用指针和双指针
- 如何深入了解明显的腐败
- 了解嵌套循环打印星号图案
- 功能原型的目的
- getline() 的原型/库是什么;
- 具有enable_if外部类原型的模板类构造函数定义
- 函数如何通知用户它基于函数原型抛出异常?
- 了解每月第一天函数的代码
- 了解C++标准::shared_ptr
- 在C++中包含原型文件的正确方法是什么?
- 尝试了解在导入的静态方法上使用删除方法时的错误
- C++:需要帮助了解运算符重载错误
- 在函数中拥有函数原型的目的是什么?
- 了解共享_ptr混叠构造函数的原型
- 了解此函数原型
- Protobuf:了解原型文件的编译输出
- 通过比较两个容器的示例了解模板原型