gpt4 book ai didi

c++ - 将>::iterator 设置为>::const_iterator

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:34 38 4
gpt4 key购买 nike

所以我看到了questions about casting std::shared_ptr<T> to std::shared_ptr<T const> 到目前为止效果很好。但我还有一个问题。我想返回一个 interator 到我的 std::set<std::shared_ptr<T>> ,其中Tstd::shared_ptr是常量。我一直无法将它们直接转换或转换为任何类型转换。我收到以下错误:

error: no viable conversion from returned value of type
'_Rb_tree_const_iterator<shared_ptr<tuple<...>>>' to function return type
'_Rb_tree_const_iterator<shared_ptr<const tuple<...>>>'
return ptrLut.begin();
^~~~~~~~~~~~~~

我看到的一种解决方法是存储 unionstd::set<std::shared_ptr<T>>std::set<std::shared_ptr<T const>> ,但我觉得这可能不是解决这个问题的正确方法。我只是想知道是否有好的方法来进行此转换?

最佳答案

set<A>set<B> 无关, 即使A可隐式转换为 B ,所以你不能得到 set<shared_ptr<T const>>::const_iterator来自set<shared_ptr<T>>::iterator .

你能做的最好的就是使用类似 boost::transform_iterator 的东西, 具有添加 const-ness 的功能。这就足够了,除非迭代器需要 set<shared_ptr<T const>>::const_iterator ,而不仅仅是具有与相同的行为

例如

#include <set>
#include <utility>
#include <boost/iterator/transform_iterator.hpp>

std::shared_ptr<T const> add_const (std::shared_ptr<T> ptr) { return ptr; };

int main()
{
std::set<std::shared_ptr<T>> the_set;
auto cbegin = boost::make_transform_iterator(std::as_const(the_set).begin(), add_const);
auto cend = boost::make_transform_iterator(std::as_const(the_set).end(), add_const);
return 0;
}

关于c++ - 将<shared_ptr<T>>::iterator 设置为<shared_ptr<T const>>::const_iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49324182/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com