是否可以在基于范围的 for 循环中使用模板化的开始/结束方法
can one use templated begin/end methods in range based for loops
我处理一个在基于循环的范围中可迭代的类,因此它定义了一个迭代器类,begin-和end-method。现在在我正在处理的示例中,这三个是模板化的(我有一个最小的例子,其中模板参数并没有真正的意义,而只是模板化的开始和结束(:
#include <cstddef>
#include <tuple>
#include <vector>
struct Iterable {
using Widget = std::tuple<int, float>;
template <typename access_type>
struct Iterator {
Iterable* m_iterable;
std::size_t m_pos;
bool operator==( const Iterator& other ) { return m_iterable == other.m_iterable && m_pos == other.m_pos; }
bool operator!=( const Iterator& other ) { return !( this->operator==( other ) ); }
access_type operator*() {
Widget tmp = m_iterable->m_storage[m_pos];
return std::get<access_type>( tmp );
}
Iterator operator++() {
m_pos++;
return *this;
}
};
template <typename access_type = int>
Iterator<access_type> begin() {
return {this, 0};
}
template <typename access_type = int>
Iterator<access_type> end() {
return {this, m_storage.size()};
}
std::vector<Widget> m_storage;
};
现在这个可迭代对象在基于 for 循环的范围内工作
Iterable container;
for (auto element: container) { … }
这使用begin<int>
和end<int>
,这在 cppinsights 中有些可见(请注意基于范围的循环版本中迭代器的类型(。
我不清楚的是,除了退回到 c++11 之前的循环之外,有没有办法为 for 循环指定模板参数?
for (auto iter = container.begin<float>(); iter != container.end<float>(); ++iter) { … }
编辑以澄清讨论的范围。可迭代类被认为是上游代码中预先存在的,我不想讨论将其放入世界的原因。别人的代码只是存在,我必须处理它。
另请参阅编译器资源管理器
您需要的是一个适配器,用于包装容器并提供您希望它具有的迭代器。 那会给你一个像
template<typename T>
struct Adapter
{
Iterable & it;
Adapter(Iterable& it) : it(it) {}
auto begin()
{
return it.begin<T>();
}
auto end()
{
return it.end<T>();
}
};
你会像这样使用它
int main()
{
Iterable container;
for ( auto element : Adapter<float>{container} )
{
static_assert( std::is_same_v<decltype( element ), float> );
}
}
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么擦除方法会影响结束方法
- 是否可以在基于范围的 for 循环中使用模板化的开始/结束方法
- 将数组作为函数参数传递,并在其上调用开始/结束方法
- C++ 结束此 8 位 for 循环的最佳方法是什么
- 单击“关闭控制台窗口”结束 C++ 控制台程序是正确的方法
- 类中的 bool 方法 控件可能到达结束 o 非空函数
- 在c++中,如果一个对象是在一个方法中创建的,那么该对象使用的内存是在该方法结束后自动释放的
- 这种递归方法不应该在返回后立即结束吗?
- 还有什么比使用istream eof更好的方法来读取文件直到它结束呢?
- 为什么方法调用结束复制构造函数
- CUDA:可能一个宿主方法调用内核/cudaMemcpy在内核/memcpy结束之前返回
- 为什么在方法作用域结束后要更改向量内容
- 如何定义运算符结束<<方法?
- 结束使用 ShellExecute 函数启动的C++程序的最佳方法是什么?
- 在<int>代码块结束之前释放分配给 std::vector 的内存的正确方法