Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何理解STL源代码中此模板的用法?_C++_Stl_Iterator Traits_Sgi - Fatal编程技术网

C++ 如何理解STL源代码中此模板的用法?

C++ 如何理解STL源代码中此模板的用法?,c++,stl,iterator-traits,sgi,C++,Stl,Iterator Traits,Sgi,我目前正在查看SGI STL的源代码,特别是距离算法 正如我所看到的,为了最大限度地提高效率,SGI使用了大量的内联模板来最小化运行时间。但我真的不明白一件事 对于算法距离,SGI定义一个模板: 模板 内联类型名迭代器特征::迭代器类别 迭代器类(常量迭代器&){ typedef typename迭代器_traits::迭代器_category; 退货类别(); } 然后,定义了算法的公共接口 模板 内联迭代器特征::迭代器类别 距离(先输入计数器,后输入计数器) { typedef type

我目前正在查看SGI STL的源代码,特别是距离算法

正如我所看到的,为了最大限度地提高效率,SGI使用了大量的内联模板来最小化运行时间。但我真的不明白一件事

对于算法距离,SGI定义一个模板:

模板
内联类型名迭代器特征::迭代器类别
迭代器类(常量迭代器&){
typedef typename迭代器_traits::迭代器_category;
退货类别();
}
然后,定义了算法的公共接口

模板
内联迭代器特征::迭代器类别
距离(先输入计数器,后输入计数器)
{
typedef typename迭代器_traits::迭代器_category;
返回距离(第一、最后、类别());
}
在你对我的知识做出判断之前,我想说,我认为我理解STL的设计模式,我理解每一行的含义,我指的是语法

但据我所知,我只是不知道为什么SGI没有实现像距离这样的算法

模板
内联迭代器特征::迭代器类别
距离(先输入计数器,后输入计数器)
{
返回距离(第一、最后、迭代器类别(第一));
}
据我所知,函数调用将消耗一定的时间,但在这里,迭代器_类别是内联函数,它与大多数主流编译器中的宏具有相同的效果

使用迭代器_category()的唯一缺点可能是编译器由于pass by const引用而生成的临时对象


我说得对吗?还是有什么我还没有认识的天才设计模式,请随时告诉我

在实现中使用
迭代器\u category(first)
可能会被用于自定义迭代器的ADL劫持

namespace HiJack
{
class MyIter{/*..*/};

template <class T> // would be not templated with call like iterator_category(first)
auto iterator_category(const MyIer&){ /*..*/ }
}

我想你的意思是
iterator\u category(first)
我能看到的避免使用
iterator\u category
的唯一优势是提高调试构建的性能。在发布版本中,并没有什么不同。“为什么SGI并没有像“代码不能编译”那个样实现算法距离。@IndianaKernick是的,同意。这也是我的看法。
template <class Iterator>
inline iterator_traits<Iterator>::iterator_category
distance(InputIterator first, InputIterator last)
{
  return __distance(first, last, ::sgi::iterator_category<InputIterator>(first));
}