小编mem*_*tum的帖子

C++中Deduce类型的模板类型

在为"迭代器"范围编写通用函数时,我通常会这样做:

template <typename Iter> auto func(Iter &first, Iter &last)
{
    using IterType = typename std::decay<decltype(*first)>::type;
    ...
}
Run Code Online (Sandbox Code Playgroud)

另一种方式似乎是:

template <typename Iter> auto func(Iter &first, Iter &last)
{
    using IterType = typename std::iterator_traits<Iter>::value_type;
    ...
}
Run Code Online (Sandbox Code Playgroud)

而第三个:

template <typename Iter> auto func(Iter &first, Iter &last)
{
    using IterType = typename Iter::value_type;
    ...
}
Run Code Online (Sandbox Code Playgroud)

没有申请iterator_traits.

从理论上讲,我的函数应该只接收迭代器,first并且last第二种形式理想地(imho)是获得该类型的最惯用的方式.但是使用typename std::decay<decltype(*first)>::type最通用的习惯用语是为了不对限定Iter喜欢value_type定义?

c++ c++11

17
推荐指数
2
解决办法
1038
查看次数

C++中rvalue引用(&&)的迭代器

在C++中使用Deduce类型的模板类型跟随我自己的问题,有些人提到通过iterators引用传递不是惯用的,并且在给定的用例中它不起作用:

template <typename Iter> iterate(Iter &first, Iter &last)
{
    // Do something with the iterators
}

iterate(container.begin(), container.end());  // error, binding non-const ref to rvalue!
Run Code Online (Sandbox Code Playgroud)

更深入地发现(至少)其他两个主题涉及前者:

但似乎没有问题/答案,通过rvalue引用&&传递迭代器是否(甚至)比通过值传递它们更好.如在

template <typename Iter> iterate(Iter &&first, Iter &&last)
{
    // Do something with the iterators
}

iterate(container.begin(), container.end());
Run Code Online (Sandbox Code Playgroud)

我的代码使用rvalue引用编译并运行良好,因此我对此有所了解.

c++ c++11

3
推荐指数
1
解决办法
1152
查看次数

标签 统计

c++ ×2

c++11 ×2