Alinshans/MyTinySTL

iterator.h文件下的一个小问题

Guotianyu-2020 opened this issue · 4 comments

has_iterator_cat这个结构体的定义中,有一行是 template <class U> static two test(...);,这一句的(...)是什么意思呀

其实 这个 ... 这三个点是 八成是 任意类型的意思,但是不明白这个 test 模板函数 是没有 定义的。

我想知道 这个 test 函数模板 应该是有定义的,不是很懂

首先回答(...)variadic function,大概就是可以接受任意类型的任意数量的参数,详情见https://en.cppreference.com/w/cpp/utility/variadic。
然后不知道你清不清楚为什么有这么一坨东西,我稍微讲一下,也顺便让大家看看我说得对不对。

  struct two { char a; char b; };
  template <class U> static two test(...);
  template <class U> static char test(typename U::iterator_category* = 0);

这里利用了SFINAE,作用是用来检测T这个类型有没有iterator_category这个成员类型别名,如果有,就会匹配到template <class U> static char test(typename U::iterator_category* = 0)然后返回类型是char,否则匹配到template <class U> static two test(...)返回类型是two,注意到chartwo的大小是不一样的。所以看到

static const bool value = sizeof(test<T>(0)) == sizeof(char);

就可以轻松靠判断test返回类型的大小是否等于sizeof(char)来判断T有没有iterator_category这个成员了,功能正好这就是类型名has_iterator_cat描述的。以前没有concept的时候就只能靠这样嗯造。test没有定义是正常的,因为sizeof运算符不会真的运行这个函数,只会推导出函数返回类型,说白了这个函数就纯纯工具人,只是用来获取类型而已。SFINAE详情看https://en.cppreference.com/w/cpp/language/sfinae。
如果有哪里说得不对的还请指正。

楼上对的