STL typedef 的可移植性如何?

发布于 2024-07-13 16:35:03 字数 787 浏览 3 评论 0原文

下面的代码可以移植吗?

template<typename In>
struct input_sequence_range : public pair<In,In> {
    input_sequence_range(In first, In last) : pair<In,In>(first, last) { }
};

template<typename Arr>
input_sequence_range<Arr*> iseq(Arr* a,
                                typename iterator_traits<Arr*>::difference_type n)
{
    return input_sequence_range<Arr*>(a, a + n);
}

template<typename Iter>
input_sequence_range<Iter> iseq(Iter first, Iter last)
{
    return input_sequence_range<Iter>(first, last);
}

具体来说,我质疑 std::iterator_traits<>::difference_type 重载的可移植性。 如果它的类型定义为 int* (这可能很奇怪;我认为标准并不禁止这样做),那么为 int 数组调用 iseq() 将是不明确的。

关于 iterator_traits<> 的标准保证是什么? 类型定义?

Is the following code portable?

template<typename In>
struct input_sequence_range : public pair<In,In> {
    input_sequence_range(In first, In last) : pair<In,In>(first, last) { }
};

template<typename Arr>
input_sequence_range<Arr*> iseq(Arr* a,
                                typename iterator_traits<Arr*>::difference_type n)
{
    return input_sequence_range<Arr*>(a, a + n);
}

template<typename Iter>
input_sequence_range<Iter> iseq(Iter first, Iter last)
{
    return input_sequence_range<Iter>(first, last);
}

Specifically I question the portability of overloading on std::iterator_traits<>::difference_type. If it's typedeffed to, say, int* (as bizzare as that may be; I think the standard doesn't forbid this) then calling iseq() for an array of ints would be ambiguous.

What does the standard guarantee about iterator_traits<> typedefs?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

人间☆小暴躁 2024-07-20 16:35:03

difference_type 必须是整型,因此 int* 不适用。

difference_type must be an integral type so int* is out.

薔薇婲 2024-07-20 16:35:03

根据 Josuttis 的说法,您应该使用 typedef 以便更加灵活和适当通用。 他的所有示例都以“这是一种快速的方法来完成它”的内容开始,最终导致了基于 STL typedef 的示例。

According to Josuttis, you should use the typedefs in order to be more flexible and properly generic. All of his examples that started off with something along the lines of "here's a fast way to do it" led to examples that were based on the STL typedefs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文