您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ visitor函数代码示例

51自学网 2021-06-03 09:43:12
  C++
这篇教程C++ visitor函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中visitor函数的典型用法代码示例。如果您正苦于以下问题:C++ visitor函数的具体用法?C++ visitor怎么用?C++ visitor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了visitor函数的25个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: ACE_ERROR_RETURN

intbe_visitor_valuetype_cdr_op_cs::visit_valuetype (be_valuetype *node){  // Already generated and/or we are imported. Don't do anything.  if (node->cli_stub_cdr_op_gen ()      || node->imported ()      || ! node->is_defined ())    {      return 0;    }  // Generate helper functions implementation.  if (node->gen_helper_stubs () == -1)    {      ACE_ERROR_RETURN ((LM_ERROR,                         "(%N:%l) be_visitor_valuetype_cdr_op_cs::"                         "visit_valuetype - "                         "codegen for helper functions failed/n"),                        -1);    }  TAO_OutStream *os = this->ctx_->stream ();  node->cli_stub_cdr_op_gen (true);  if (this->visit_scope (node) == -1)    {      ACE_ERROR_RETURN ((LM_ERROR,                         "(%N:%l) be_visitor_valuetype_cdr_op_ci"                         "::visit_valuetype - "                         "codegen for scope failed/n"),                        -1);    }  *os << be_nl_2 << "// TAO_IDL - Generated from" << be_nl      << "// " << __FILE__ << ":" << __LINE__ << be_nl_2;  *os << be_global->core_versioning_begin () << be_nl;  //  Set the sub state as generating code for the output operator.  this->ctx_->sub_state(TAO_CodeGen::TAO_CDR_OUTPUT);  *os << "::CORBA::Boolean" << be_nl      << "operator<< (" << be_idt << be_idt_nl      << "TAO_OutputCDR &strm," << be_nl      << "const " << node->full_name ()      << " *_tao_valuetype" << be_uidt_nl      << ")" << be_uidt_nl      << "{" << be_idt_nl;  *os << "return" << be_idt_nl      << "::CORBA::ValueBase::_tao_marshal (" << be_idt << be_idt_nl      << "strm," << be_nl      << "_tao_valuetype," << be_nl      << "reinterpret_cast<ptrdiff_t> (&"      << node->full_name () << "::_downcast)"      << be_uidt_nl      << ");" << be_uidt << be_uidt << be_uidt_nl      << "}" << be_nl_2;  *os << "::CORBA::Boolean" << be_nl      << "operator>> (" << be_idt << be_idt_nl      << "TAO_InputCDR &strm," << be_nl      << node->full_name ()      << " *&_tao_valuetype" << be_uidt_nl      << ")" << be_uidt_nl      << "{" << be_idt_nl;  *os << "return " << node->full_name ()      << "::_tao_unmarshal (strm, _tao_valuetype);"      << be_uidt_nl      << "}" << be_nl_2;  if (be_global->gen_ostream_operators ())    {      node->gen_ostream_operator (os, false);    }  *os << be_global->core_versioning_end () << be_nl;  if (!node->is_abstract ())    {      // Functions that marshal state.      be_visitor_context new_ctx (*this->ctx_);      be_visitor_valuetype_marshal_cs visitor (&new_ctx);      visitor.visit_valuetype (node);    }  return 0;}
开发者ID:INMarkus,项目名称:ATCD,代码行数:87,


示例2: visitor

void SpatialAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos){	VectorResultVisitor visitor(result, this);	m_tree->pointLocationQuery(get_spatial_point(pos), visitor);}
开发者ID:juhdanad,项目名称:minetest,代码行数:5,


示例3: get_charmm_untyped_atoms

Atoms get_charmm_untyped_atoms(Hierarchy hierarchy) {  Atoms atoms;  FindUntypedVisitor visitor(&atoms);  IMP::core::visit_depth_first(hierarchy, visitor);  return atoms;}
开发者ID:AljGaber,项目名称:imp,代码行数:6,


示例4: assert

bool AssemblyLeafProbeVisitor::visit(    const vector<UniqueID>&             items,    const vector<GAABB3>&               bboxes,    const size_t                        begin,    const size_t                        end,    const ShadingRay::RayType&          ray,    const ShadingRay::RayInfoType&      /*ray_info*/,    const double                        tmin,    const double                        tmax,    double&                             distance){    assert(begin + 1 == end);    // Retrieve the assembly instance.    const AssemblyInstance* assembly_instance =        m_tree.m_scene.assembly_instances().get_by_uid(items[begin]);    assert(assembly_instance);    ShadingRay::RayType local_ray;    local_ray.m_tmin = tmin;    local_ray.m_tmax = tmax;    // Transform the ray to assembly instance space.    transform_ray_to_assembly_instance_space(        assembly_instance,        m_parent_shading_point,        ray,        local_ray);    const RayInfo3d local_ray_info(local_ray);    if (assembly_instance->get_assembly().is_flushable())    {        // Retrieve the region tree of this assembly.        const RegionTree& region_tree =            *m_region_tree_cache.access(                assembly_instance->get_assembly_uid(),                m_tree.m_region_trees);        // Check the intersection between the ray and the region tree.        RegionLeafProbeVisitor visitor(            m_triangle_tree_cache#ifdef FOUNDATION_BSP_ENABLE_TRAVERSAL_STATS            , m_triangle_bsp_stats#endif            );        RegionLeafProbeIntersector intersector;#ifdef FOUNDATION_BSP_ENABLE_TRAVERSAL_STATS        bsp::TraversalStatistics stats;        intersector.intersect(            region_tree,            local_ray,            local_ray_info,            visitor,            stats);#else        intersector.intersect(            region_tree,            local_ray,            local_ray_info,            visitor);#endif                // Terminate traversal if there was a hit.        if (visitor.hit())        {            m_hit = true;            return false;        }    }    else    {        // Retrieve the triangle tree of this leaf.        const TriangleTree* triangle_tree =            m_triangle_tree_cache.access(                assembly_instance->get_assembly_uid(),                m_tree.m_triangle_trees);        if (triangle_tree)        {            // Check the intersection between the ray and the triangle tree.            TriangleLeafProbeVisitor visitor;            TriangleLeafProbeIntersector intersector;            intersector.intersect(                *triangle_tree,                local_ray,                local_ray_info,                visitor#ifdef FOUNDATION_BSP_ENABLE_TRAVERSAL_STATS                , m_triangle_bsp_stats#endif                );            // Terminate traversal if there was a hit.            if (visitor.hit())            {                m_hit = true;                return false;            }        }//.........这里部分代码省略.........
开发者ID:tomcodes,项目名称:appleseed,代码行数:101,


示例5: visitor

  bool LocationService::HandleAdminRegionLocation(const LocationSearch& search,                                                  const LocationSearch::Entry& searchEntry,                                                  const AdminRegionMatchVisitor::AdminRegionResult& adminRegionResult,                                                  const LocationMatchVisitor::LocationResult& locationResult,                                                  LocationSearchResult& result) const  {    if (searchEntry.addressPattern.empty()) {      LocationSearchResult::Entry entry;      entry.adminRegion=locationResult.adminRegion;      entry.location=locationResult.location;      if (adminRegionResult.isMatch) {        entry.adminRegionMatchQuality=LocationSearchResult::match;      }      else {        entry.adminRegionMatchQuality=LocationSearchResult::candidate;      }      if (locationResult.isMatch) {        entry.locationMatchQuality=LocationSearchResult::match;      }      else {        entry.locationMatchQuality=LocationSearchResult::candidate;      }      entry.poiMatchQuality=LocationSearchResult::none;      entry.addressMatchQuality=LocationSearchResult::none;      result.results.push_back(entry);      return true;    }    //std::cout << "    Search for address '" << searchEntry.addressPattern << "'" << std::endl;    AddressMatchVisitor visitor(searchEntry.addressPattern,                                search.limit>=result.results.size() ? search.limit-result.results.size() : 0);    if (!VisitLocationAddresses(*locationResult.adminRegion,                                *locationResult.location,                                visitor)) {      log.Error() << "Error during traversal of region location address list";      return false;    }    if (visitor.results.empty()) {      LocationSearchResult::Entry entry;      entry.adminRegion=locationResult.adminRegion;      entry.location=locationResult.location;      if (adminRegionResult.isMatch) {        entry.adminRegionMatchQuality=LocationSearchResult::match;      }      else {        entry.adminRegionMatchQuality=LocationSearchResult::candidate;      }      if (locationResult.isMatch) {        entry.locationMatchQuality=LocationSearchResult::match;      }      else {        entry.locationMatchQuality=LocationSearchResult::candidate;      }      entry.poiMatchQuality=LocationSearchResult::none;      entry.addressMatchQuality=LocationSearchResult::none;      result.results.push_back(entry);      return true;    }    for (const auto& addressResult : visitor.results) {      //std::cout << "    - '" << addressResult->address->name << "'" << std::endl;      if (!HandleAdminRegionLocationAddress(search,                                            adminRegionResult,                                            locationResult,                                            addressResult,                                            result)) {        return false;      }    }    return true;  }
开发者ID:AQbernhard,项目名称:OSMScout-ubuntu,代码行数:88,


示例6: apply

 static inline void apply(variant<BOOST_VARIANT_ENUM_PARAMS(T)>& geometry1,       Geometry2 const& geometry2) {     return boost::apply_visitor(visitor(geometry2), geometry1); }
开发者ID:Abyss-z94,项目名称:samp-streamer-plugin,代码行数:6,


示例7: key

QIcon StereotypeController::createIcon(StereotypeIcon::Element element, const QList<QString> &stereotypes,                                       const QString &defaultIconPath, const Style *style, const QSize &size,                                       const QMarginsF &margins, qreal lineWidth){    IconKey key(element, stereotypes, defaultIconPath, style->uid(), size, margins, lineWidth);    QIcon icon = d->m_iconMap.value(key);    if (!icon.isNull())        return icon;    QString stereotypeIconId = findStereotypeIconId(element, stereotypes);    if (!stereotypeIconId.isEmpty()) {        StereotypeIcon stereotypeIcon = findStereotypeIcon(stereotypeIconId);        // calculate bounding rectangle relativ to original icon size        ShapeSizeVisitor sizeVisitor(QPointF(0.0, 0.0),                                     QSizeF(stereotypeIcon.width(), stereotypeIcon.height()),                                     QSizeF(stereotypeIcon.width(), stereotypeIcon.height()),                                     QSizeF(stereotypeIcon.width(), stereotypeIcon.height()));        stereotypeIcon.iconShape().visitShapes(&sizeVisitor);        QRectF iconBoundingRect = sizeVisitor.boundingRect();        // calc painting space within margins        qreal innerWidth = size.width() - margins.left() - margins.right();        qreal innerHeight = size.height() - margins.top() - margins.bottom();        // calculate width/height ratio from icon size        qreal widthRatio = 1.0;        qreal heightRatio = 1.0;        qreal ratio = stereotypeIcon.width() / stereotypeIcon.height();        if (ratio > 1.0)            heightRatio /= ratio;        else            widthRatio *= ratio;        // calculate inner painting area        qreal paintWidth = stereotypeIcon.width() * innerWidth / iconBoundingRect.width() * widthRatio;        qreal paintHeight = stereotypeIcon.height() * innerHeight / iconBoundingRect.height() * heightRatio;        // icons which renders smaller than their size should not be zoomed        if (paintWidth > innerWidth) {            paintHeight *= innerWidth / paintHeight;            paintWidth = innerWidth;        }        if (paintHeight > innerHeight) {            paintWidth *= innerHeight / paintHeight;            paintHeight = innerHeight;        }        // calculate offset of top/left edge        qreal paintLeft = iconBoundingRect.left() * paintWidth / stereotypeIcon.width();        qreal paintTop = iconBoundingRect.top() * paintHeight / stereotypeIcon.height();        // calculate total painting size        qreal totalPaintWidth = iconBoundingRect.width() * paintWidth / stereotypeIcon.width();        qreal totalPaintHeight = iconBoundingRect.height() * paintHeight / stereotypeIcon.height();        QPixmap pixmap(size);        pixmap.fill(Qt::transparent);        QPainter painter(&pixmap);        painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);        painter.setBrush(Qt::NoBrush);        // set painting origin taking margin, offset and centering into account        painter.translate(QPointF(margins.left(), margins.top()) - QPointF(paintLeft, paintTop)                          + QPointF((innerWidth - totalPaintWidth) / 2, (innerHeight - totalPaintHeight) / 2));        QPen linePen = style->linePen();        linePen.setWidthF(lineWidth);        painter.setPen(linePen);        painter.setBrush(style->fillBrush());        ShapePaintVisitor visitor(&painter, QPointF(0.0, 0.0),                                  QSizeF(stereotypeIcon.width(), stereotypeIcon.height()),                                  QSizeF(paintWidth, paintHeight), QSizeF(paintWidth, paintHeight));        stereotypeIcon.iconShape().visitShapes(&visitor);        icon = QIcon(pixmap);    }    if (icon.isNull() && !defaultIconPath.isEmpty())        icon = QIcon(defaultIconPath);    d->m_iconMap.insert(key, icon);    return icon;}
开发者ID:kai66673,项目名称:qt-creator,代码行数:80,


示例8: ctx

intbe_visitor_structure::visit_field (be_field *node){  // Instantiate a visitor context with a copy of our context. This info  // will be modified based on what type of node we are visiting.  be_visitor_context ctx (*this->ctx_);  ctx.node (node);  int status = 0;  switch (this->ctx_->state ())    {    case TAO_CodeGen::TAO_ROOT_CH:    case TAO_CodeGen::TAO_INTERFACE_CH:    case TAO_CodeGen::TAO_UNION_PUBLIC_CH:    case TAO_CodeGen::TAO_UNION_PRIVATE_CH:    case TAO_CodeGen::TAO_ARRAY_CH:      {        be_visitor_field_ch visitor (&ctx);        status = node->accept (&visitor);        break;      }    case TAO_CodeGen::TAO_ROOT_CI:      {        be_visitor_field_ci visitor (&ctx);        status = node->accept (&visitor);        break;      }    case TAO_CodeGen::TAO_ROOT_CS:    case TAO_CodeGen::TAO_UNION_PUBLIC_CS:      {        be_visitor_field_cs visitor (&ctx);        status = node->accept (&visitor);        break;      }    case TAO_CodeGen::TAO_ROOT_CDR_OP_CH:      {        be_visitor_field_cdr_op_ch visitor (&ctx);        status = node->accept (&visitor);        break;      }    case TAO_CodeGen::TAO_ROOT_CDR_OP_CS:      {        be_visitor_field_cdr_op_cs visitor (&ctx);        status = node->accept (&visitor);        break;      }    default:      {        ACE_ERROR_RETURN ((LM_ERROR,                           "(%N:%l) be_visitor_structure::"                           "visit_field - "                           "Bad context state/n"),                          -1);      }    }  if (status == -1)    {      ACE_ERROR_RETURN ((LM_ERROR,                         "(%N:%l) be_visitor_structure::"                         "visit_field - "                         "failed to accept visitor/n"),                        -1);    }  return 0;}
开发者ID:CCJY,项目名称:ATCD,代码行数:67,


示例9: distributeProjectedSizeAndPrimitiveCountIterative

//! Distribute the budget based on the projected size and the primitive count of the child nodes in an iterative manner for correct distribution.static void distributeProjectedSizeAndPrimitiveCountIterative(double value, const Util::StringIdentifier & attributeId, Node * node, FrameContext & context) {	static const Util::StringIdentifier primitiveCountId("PrimitiveCount");	struct PrimitiveCountAnnotationVisitor : public NodeVisitor {		const Util::StringIdentifier & m_primitiveCountId;		PrimitiveCountAnnotationVisitor(const Util::StringIdentifier & p_primitiveCountId) : m_primitiveCountId(p_primitiveCountId) {		}		virtual ~PrimitiveCountAnnotationVisitor() {		}		NodeVisitor::status leave(Node * _node) override {			auto geoNode = dynamic_cast<GeometryNode *>(_node);			uint32_t primitiveCount = 0;			if(geoNode != nullptr) {				const auto mesh = geoNode->getMesh();				primitiveCount = mesh == nullptr ? 0 : mesh->getPrimitiveCount();			} else {				const auto children = getChildNodes(_node);				for(const auto & child : children) {					primitiveCount += child->getAttribute(m_primitiveCountId)->toUnsignedInt();				}			}			_node->setAttribute(m_primitiveCountId, Util::GenericAttribute::createNumber(primitiveCount));			return CONTINUE_TRAVERSAL;		}	};	const auto children = getChildNodes(node);	// A pair stores the primitive count, the node and its projected size.	std::deque<std::tuple<uint32_t, Node *, float>> primitiveCountNodeProjSizeTuples;	double projSizeSum = 0.0;	const Geometry::Rect_f screenRect(context.getRenderingContext().getWindowClientArea());	for(const auto & child : children) {		if(!child->isAttributeSet(primitiveCountId)) {			PrimitiveCountAnnotationVisitor visitor(primitiveCountId);			child->traverse(visitor);		}		const auto primitiveCount = child->getAttribute(primitiveCountId)->toUnsignedInt();		// Clip the projected rect to the screen.		auto projRect = context.getProjectedRect(child);		projRect.clipBy(screenRect);		const auto projSize = projRect.getArea();		projSizeSum += projSize;		primitiveCountNodeProjSizeTuples.emplace_back(primitiveCount, child, projSize);	}	// Begin with the node with the lowest primitive count	std::sort(primitiveCountNodeProjSizeTuples.begin(), primitiveCountNodeProjSizeTuples.end());	/* Distribute budget until one node gets all budget it asked for.	 * This means the previous distributions would receive more budget,	 * thus remove that node from distribution (update value and projSizeSum)	 * and start again.	 */	std::deque<std::tuple<uint32_t, Node *, float>> tmpDeque(primitiveCountNodeProjSizeTuples); // TODO: fails to copy values correctly!!!	bool nodeRemoved;	double tmpValue;	double tmpProjSizeSum;	double remainingProjSizeSum = projSizeSum;	do{		nodeRemoved = false;		tmpValue = value;		tmpProjSizeSum = remainingProjSizeSum;		for(auto it=tmpDeque.begin(); it!=tmpDeque.end(); ++it) {			std::tuple<uint32_t, Node *, float> element = *it;			const auto primitiveCount = std::get<0>(element);			const auto projSize = std::get<2>(element);			const auto projSizeFactor = projSize / tmpProjSizeSum;			const auto primitiveAssignment = std::min(static_cast<uint32_t>(projSizeFactor * tmpValue), primitiveCount);			setOrUpdateAttribute(std::get<1>(element), attributeId, primitiveAssignment);			if(primitiveAssignment == primitiveCount){				nodeRemoved = true;				tmpDeque.erase(it);				value -= primitiveCount;				remainingProjSizeSum -= projSize;				break;			}			tmpValue -= primitiveAssignment;			tmpProjSizeSum -= projSize;		}	}while(nodeRemoved);	// distribute remaining part of value based on projected size only	if(tmpValue >= 1){		for(const auto & primitiveCountNodeProjSizeTuple : primitiveCountNodeProjSizeTuples) {			const auto projSize = std::get<2>(primitiveCountNodeProjSizeTuple);			const auto projSizeFactor = projSize / projSizeSum;			const auto attribute = dynamic_cast<Util::_NumberAttribute<double> *>(std::get<1>(primitiveCountNodeProjSizeTuple)->getAttribute(attributeId));			attribute->set(attribute->get() + projSizeFactor * tmpValue);		}	}}
开发者ID:MeisterYeti,项目名称:MinSG,代码行数:98,


示例10: sloan_start_end_vertices

  typename graph_traits<Graph>::vertex_descriptor   sloan_start_end_vertices(Graph& G,                            typename graph_traits<Graph>::vertex_descriptor &s,                            ColorMap color,                            DegreeMap degree)  {    typedef typename property_traits<DegreeMap>::value_type Degree;    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;    typedef typename std::vector< typename graph_traits<Graph>::vertices_size_type>::iterator vec_iter;    typedef typename graph_traits<Graph>::vertices_size_type size_type;        typedef typename property_map<Graph, vertex_index_t>::const_type VertexID;        s = *(vertices(G).first);    Vertex e = s;    Vertex i;    unsigned my_degree = get(degree, s );     unsigned dummy, h_i, h_s, w_i, w_e;    bool new_start = true;    unsigned maximum_degree = 0;        //Creating a std-vector for storing the distance from the start vertex in dist    std::vector<typename graph_traits<Graph>::vertices_size_type> dist(num_vertices(G), 0);    //Wrap a property_map_iterator around the std::iterator    boost::iterator_property_map<vec_iter, VertexID, size_type, size_type&> dist_pmap(dist.begin(), get(vertex_index, G));        //Creating a property_map for the indices of a vertex    typename property_map<Graph, vertex_index_t>::type index_map = get(vertex_index, G);        //Creating a priority queue    typedef indirect_cmp<DegreeMap, std::greater<Degree> > Compare;    Compare comp(degree);    std::priority_queue<Vertex, std::vector<Vertex>, Compare> degree_queue(comp);        //step 1    //Scan for the vertex with the smallest degree and the maximum degree    typename graph_traits<Graph>::vertex_iterator ui, ui_end;    for (boost::tie(ui, ui_end) = vertices(G); ui != ui_end; ++ui)    {      dummy = get(degree, *ui);            if(dummy < my_degree)      {        my_degree = dummy;        s = *ui;      }            if(dummy > maximum_degree)      {        maximum_degree = dummy;      }    }    //end 1        do{        new_start = false;     //Setting the loop repetition status to false            //step 2      //initialize the the disance std-vector with 0      for(typename std::vector<typename graph_traits<Graph>::vertices_size_type>::iterator iter = dist.begin(); iter != dist.end(); ++iter) *iter = 0;            //generating the RLS (rooted level structure)      breadth_first_search        (G, s, visitor         (           make_bfs_visitor(record_distances(dist_pmap, on_tree_edge() ) )           )          );            //end 2            //step 3      //calculating the depth of the RLS      h_s = RLS_depth(dist);            //step 4      //pushing one node of each degree in an ascending manner into degree_queue      std::vector<bool> shrink_trace(maximum_degree, false);      for (boost::tie(ui, ui_end) = vertices(G); ui != ui_end; ++ui)      {        dummy = get(degree, *ui);                if( (dist[index_map[*ui]] == h_s ) && ( !shrink_trace[ dummy ] ) )        {          degree_queue.push(*ui);          shrink_trace[ dummy ] = true;        }      }            //end 3 & 4            // step 5      // Initializing w      w_e = (std::numeric_limits<unsigned>::max)();      //end 5                  //step 6//.........这里部分代码省略.........
开发者ID:00liujj,项目名称:dealii,代码行数:101,


示例11: sloan_ordering

  OutputIterator  sloan_ordering(Graph& g,                 typename graph_traits<Graph>::vertex_descriptor s,                 typename graph_traits<Graph>::vertex_descriptor e,                 OutputIterator permutation,                  ColorMap color,                  DegreeMap degree,                  PriorityMap priority,                  Weight W1,                  Weight W2)  {    //typedef typename property_traits<DegreeMap>::value_type Degree;    typedef typename property_traits<PriorityMap>::value_type Degree;    typedef typename property_traits<ColorMap>::value_type ColorValue;    typedef color_traits<ColorValue> Color;    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;    typedef typename std::vector<typename graph_traits<Graph>::vertices_size_type>::iterator vec_iter;    typedef typename graph_traits<Graph>::vertices_size_type size_type;    typedef typename property_map<Graph, vertex_index_t>::const_type VertexID;        //Creating a std-vector for storing the distance from the end vertex in it    typename std::vector<typename graph_traits<Graph>::vertices_size_type> dist(num_vertices(g), 0);        //Wrap a property_map_iterator around the std::iterator    boost::iterator_property_map<vec_iter, VertexID, size_type, size_type&> dist_pmap(dist.begin(), get(vertex_index, g));         breadth_first_search      (g, e, visitor       (           make_bfs_visitor(record_distances(dist_pmap, on_tree_edge() ) )        )       );        //Creating a property_map for the indices of a vertex    typename property_map<Graph, vertex_index_t>::type index_map = get(vertex_index, g);        //Sets the color and priority to their initial status    unsigned cdeg;        typename graph_traits<Graph>::vertex_iterator ui, ui_end;    for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)    {        put(color, *ui, Color::white());        cdeg=get(degree, *ui)+1;        put(priority, *ui, W1*dist[index_map[*ui]]-W2*cdeg );      }        //Priority list    typedef indirect_cmp<PriorityMap, std::greater<Degree> > Compare;    Compare comp(priority);    std::list<Vertex> priority_list;    //Some more declarations    typename graph_traits<Graph>::out_edge_iterator ei, ei_end, ei2, ei2_end;    Vertex u, v, w;    put(color, s, Color::green());      //Sets the color of the starting vertex to gray    priority_list.push_front(s);                 //Puts s into the priority_list        while ( !priority_list.empty() )     {        priority_list.sort(comp);         //Orders the elements in the priority list in an ascending manner            u = priority_list.front();           //Accesses the last element in the priority list      priority_list.pop_front();               //Removes the last element in the priority list            if(get(color, u) == Color::green() )      {        //for-loop over all out-edges of vertex u        for (boost::tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei)         {          v = target(*ei, g);                    put( priority, v, get(priority, v) + W2 ); //updates the priority                    if (get(color, v) == Color::white() )      //test if the vertex is inactive          {            put(color, v, Color::green() );        //giving the vertex a preactive status            priority_list.push_front(v);                     //writing the vertex in the priority_queue          }                   }      }            //Here starts step 8      *permutation++ = u;                      //Puts u to the first position in the permutation-vector      put(color, u, Color::black() );          //Gives u an inactive status            //for loop over all the adjacent vertices of u      for (boost::tie(ei, ei_end) = out_edges(u, g); ei != ei_end; ++ei) {                v = target(*ei, g);                     if (get(color, v) == Color::green() ) {      //tests if the vertex is inactive                    put(color, v, Color::red() );        //giving the vertex an active status          put(priority, v, get(priority, v)+W2);  //updates the priority                            //for loop over alll adjacent vertices of v          for (boost::tie(ei2, ei2_end) = out_edges(v, g); ei2 != ei2_end; ++ei2) {//.........这里部分代码省略.........
开发者ID:00liujj,项目名称:dealii,代码行数:101,


示例12: pair

Player* ScriptedAI::GetPlayerAtMinimumRange(float fMinimumRange){    Player* player = NULL;    CellPair pair(Trinity::ComputeCellPair(me->GetPositionX(), me->GetPositionY()));    Cell cell(pair);    cell.data.Part.reserved = ALL_DISTRICT;    cell.SetNoCreate();    Trinity::PlayerAtMinimumRangeAway check(me, fMinimumRange);    Trinity::PlayerSearcher<Trinity::PlayerAtMinimumRangeAway> searcher(me, player, check);    TypeContainerVisitor<Trinity::PlayerSearcher<Trinity::PlayerAtMinimumRangeAway>, GridTypeMapContainer> visitor(searcher);    cell.Visit(pair, visitor, *(me->GetMap()));    return player;}
开发者ID:Cryostorm,项目名称:TBCPvP,代码行数:17,


示例13: main

int main(int argc, char **argv){#ifdef QT_BOOTSTRAPPED    initBinaryDir(#ifndef Q_OS_WIN            argv[0]#endif            );#else    QCoreApplication app(argc, argv);#ifndef Q_OS_WIN32    QTranslator translator;    QTranslator qtTranslator;    QString sysLocale = QLocale::system().name();    QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);    if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir)        && qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) {        app.installTranslator(&translator);        app.installTranslator(&qtTranslator);    }#endif // Q_OS_WIN32#endif // QT_BOOTSTRAPPED    ConversionData cd;    cd.m_verbose = true; // the default is true starting with Qt 4.2    bool removeIdentical = false;    Translator tor;    QStringList inputFiles;    QString outputFile;    for (int i = 1; i < argc; ++i) {        if (!strcmp(argv[i], "-compress")) {            cd.m_saveMode = SaveStripped;            continue;        } else if (!strcmp(argv[i], "-idbased")) {            cd.m_idBased = true;            continue;        } else if (!strcmp(argv[i], "-nocompress")) {            cd.m_saveMode = SaveEverything;            continue;        } else if (!strcmp(argv[i], "-removeidentical")) {            removeIdentical = true;            continue;        } else if (!strcmp(argv[i], "-nounfinished")) {            cd.m_ignoreUnfinished = true;            continue;        } else if (!strcmp(argv[i], "-markuntranslated")) {            if (i == argc - 1) {                printUsage();                return 1;            }            cd.m_unTrPrefix = QString::fromLocal8Bit(argv[++i]);        } else if (!strcmp(argv[i], "-silent")) {            cd.m_verbose = false;            continue;        } else if (!strcmp(argv[i], "-verbose")) {            cd.m_verbose = true;            continue;        } else if (!strcmp(argv[i], "-version")) {            printOut(LR::tr("lrelease version %1/n").arg(QLatin1String(QT_VERSION_STR)));            return 0;        } else if (!strcmp(argv[i], "-qm")) {            if (i == argc - 1) {                printUsage();                return 1;            }            outputFile = QString::fromLocal8Bit(argv[++i]);        } else if (!strcmp(argv[i], "-help")) {            printUsage();            return 0;        } else if (argv[i][0] == '-') {            printUsage();            return 1;        } else {            inputFiles << QString::fromLocal8Bit(argv[i]);        }    }    if (inputFiles.isEmpty()) {        printUsage();        return 1;    }    foreach (const QString &inputFile, inputFiles) {        if (inputFile.endsWith(QLatin1String(".pro"), Qt::CaseInsensitive)            || inputFile.endsWith(QLatin1String(".pri"), Qt::CaseInsensitive)) {            QFileInfo fi(inputFile);            parseHandler.verbose = evalHandler.verbose = cd.isVerbose();            ProFileOption option;#ifdef QT_BOOTSTRAPPED            option.initProperties(binDir + QLatin1String("/qmake"));#else            option.initProperties(app.applicationDirPath() + QLatin1String("/qmake"));#endif            ProFileParser parser(0, &parseHandler);            ProFileEvaluator visitor(&option, &parser, &evalHandler);            ProFile *pro;            if (!(pro = parser.parsedProFile(QDir::cleanPath(fi.absoluteFilePath())))) {//.........这里部分代码省略.........
开发者ID:KDE,项目名称:android-qt,代码行数:101,


示例14: Size

 // Calculates the size of serialized header in bytes. uint64_t Size() {   coding::binary::HeaderSizeOfVisitor visitor;   visitor(*this);   return visitor.m_size; }
开发者ID:milchakov,项目名称:omim,代码行数:7,


示例15: Deserialize

 void Deserialize(Source & source) {   coding::binary::HeaderDesVisitor<Source> visitor(source);   visitor(*this); }
开发者ID:milchakov,项目名称:omim,代码行数:5,


示例16: distributeProjectedSizeAndPrimitiveCount

//! Distribute the budget based on the projected size and the primitive count of the child nodes.static void distributeProjectedSizeAndPrimitiveCount(double value, const Util::StringIdentifier & attributeId, Node * node, FrameContext & context) {	static const Util::StringIdentifier primitiveCountId("PrimitiveCount");	struct PrimitiveCountAnnotationVisitor : public NodeVisitor {		const Util::StringIdentifier & m_primitiveCountId;		PrimitiveCountAnnotationVisitor(const Util::StringIdentifier & p_primitiveCountId) : m_primitiveCountId(p_primitiveCountId) {		}		virtual ~PrimitiveCountAnnotationVisitor() {		}		NodeVisitor::status leave(Node * _node) override {			auto geoNode = dynamic_cast<GeometryNode *>(_node);			uint32_t primitiveCount = 0;			if(geoNode != nullptr) {				const auto mesh = geoNode->getMesh();				primitiveCount = mesh == nullptr ? 0 : mesh->getPrimitiveCount();			} else {				const auto children = getChildNodes(_node);				for(const auto & child : children) {					primitiveCount += child->getAttribute(m_primitiveCountId)->toUnsignedInt();				}			}			_node->setAttribute(m_primitiveCountId, Util::GenericAttribute::createNumber(primitiveCount));			return CONTINUE_TRAVERSAL;		}	};	const auto children = getChildNodes(node);	// A tuple stores the primitive count, the node and its projected size.	std::vector<std::tuple<uint32_t, Node *, float>> primitiveCountNodeProjSizeTuples;	primitiveCountNodeProjSizeTuples.reserve(children.size());	double projSizeSum = 0.0;	const Geometry::Rect_f screenRect(context.getRenderingContext().getWindowClientArea());	for(const auto & child : children) {		if(!child->isAttributeSet(primitiveCountId)) {			PrimitiveCountAnnotationVisitor visitor(primitiveCountId);			child->traverse(visitor);		}		const auto primitiveCount = child->getAttribute(primitiveCountId)->toUnsignedInt();		// Clip the projected rect to the screen.		auto projRect = context.getProjectedRect(child);		projRect.clipBy(screenRect);		const auto projSize = projRect.getArea();		projSizeSum += projSize;		primitiveCountNodeProjSizeTuples.emplace_back(primitiveCount, child, projSize);	}	// Begin with the node with the lowest primitive count	std::sort(primitiveCountNodeProjSizeTuples.begin(), primitiveCountNodeProjSizeTuples.end());	for(const auto & primitiveCountNodeProjSizeTuple : primitiveCountNodeProjSizeTuples) {		const auto primitiveCount = std::get<0>(primitiveCountNodeProjSizeTuple);		const auto projSize = std::get<2>(primitiveCountNodeProjSizeTuple);		const auto projSizeFactor = projSize / projSizeSum;				const auto primitiveAssignment = std::min(static_cast<uint32_t>(projSizeFactor * value), primitiveCount);		setOrUpdateAttribute(std::get<1>(primitiveCountNodeProjSizeTuple), attributeId, primitiveAssignment);		value -= primitiveAssignment;		projSizeSum -= projSize;	}}
开发者ID:MeisterYeti,项目名称:MinSG,代码行数:64,


示例17: height

CSVRender::WorldspaceHitResult CSVRender::WorldspaceWidget::mousePick (const QPoint& localPos,    unsigned int interactionMask) const{    // (0,0) is considered the lower left corner of an OpenGL window    int x = localPos.x();    int y = height() - localPos.y();    // Convert from screen space to world space    osg::Matrixd wpvMat;    wpvMat.preMult (mView->getCamera()->getViewport()->computeWindowMatrix());    wpvMat.preMult (mView->getCamera()->getProjectionMatrix());    wpvMat.preMult (mView->getCamera()->getViewMatrix());    wpvMat = osg::Matrixd::inverse (wpvMat);    osg::Vec3d start = wpvMat.preMult (osg::Vec3d(x, y, 0));    osg::Vec3d end = wpvMat.preMult (osg::Vec3d(x, y, 1));    osg::Vec3d direction = end - start;    // Get intersection    osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector (new osgUtil::LineSegmentIntersector(        osgUtil::Intersector::MODEL, start, end));    intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::NO_LIMIT);    osgUtil::IntersectionVisitor visitor(intersector);    visitor.setTraversalMask(interactionMask);    mView->getCamera()->accept(visitor);    // Get relevant data    for (osgUtil::LineSegmentIntersector::Intersections::iterator it = intersector->getIntersections().begin();         it != intersector->getIntersections().end(); ++it)    {        osgUtil::LineSegmentIntersector::Intersection intersection = *it;        // reject back-facing polygons        if (direction * intersection.getWorldIntersectNormal() > 0)        {            continue;        }        for (std::vector<osg::Node*>::iterator it = intersection.nodePath.begin(); it != intersection.nodePath.end(); ++it)        {            osg::Node* node = *it;            if (osg::ref_ptr<CSVRender::TagBase> tag = dynamic_cast<CSVRender::TagBase *>(node->getUserData()))            {                WorldspaceHitResult hit = { true, tag, 0, 0, 0, intersection.getWorldIntersectPoint() };                if (intersection.indexList.size() >= 3)                {                    hit.index0 = intersection.indexList[0];                    hit.index1 = intersection.indexList[1];                    hit.index2 = intersection.indexList[2];                }                return hit;            }        }        // Something untagged, probably terrain        WorldspaceHitResult hit = { true, 0, 0, 0, 0, intersection.getWorldIntersectPoint() };        if (intersection.indexList.size() >= 3)        {            hit.index0 = intersection.indexList[0];            hit.index1 = intersection.indexList[1];            hit.index2 = intersection.indexList[2];        }        return hit;    }    // Default placement    direction.normalize();    direction *= CSMPrefs::get()["Scene Drops"]["distance"].toInt();    WorldspaceHitResult hit = { false, 0, 0, 0, 0, start + direction };    return hit;}
开发者ID:DavidDanielsson,项目名称:openmw,代码行数:75,


示例18: collectStackRoots

void collectStackRoots(TraceStack *stack) {    unw_cursor_t cursor;    unw_context_t uc;    unw_word_t ip, sp, bp;    // force callee-save registers onto the stack:    // Actually, I feel like this is pretty brittle:    // collectStackRoots itself is allowed to save the callee-save registers    // on its own stack.    jmp_buf registers __attribute__((aligned(sizeof(void*))));#ifndef NVALGRIND    if (RUNNING_ON_VALGRIND) {        memset(&registers, 0, sizeof(registers));        memset(&cursor, 0, sizeof(cursor));        memset(&uc, 0, sizeof(uc));        memset(&ip, 0, sizeof(ip));        memset(&sp, 0, sizeof(sp));        memset(&bp, 0, sizeof(bp));    }#endif    setjmp(registers);    assert(sizeof(registers) % 8 == 0);    //void* stack_bottom = __builtin_frame_address(0);    collectRoots(&registers, &registers + 1, stack);    unw_getcontext(&uc);    unw_init_local(&cursor, &uc);    TraceStackGCVisitor visitor(stack);    int code;    while (true) {        int code = unw_step(&cursor);        // Negative codes are errors, zero means that there isn't a new frame.        ASSERT(code >= 0 && "something broke unwinding!", "%d '%s'", code, unw_strerror(code));        assert(code != 0 && "didn't get to the top of the stack!");        unw_get_reg(&cursor, UNW_REG_IP, &ip);        unw_get_reg(&cursor, UNW_REG_SP, &sp);        unw_get_reg(&cursor, UNW_TDEP_BP, &bp);        void* cur_sp = (void*)sp;        void* cur_bp = (void*)bp;        //std::string name = g.func_addr_registry.getFuncNameAtAddress((void*)ip, true);        //if (VERBOSITY()) printf("ip = %lx (%s), stack = [%p, %p)/n", (long) ip, name.c_str(), cur_sp, cur_bp);        unw_proc_info_t pip;        unw_get_proc_info(&cursor, &pip);        if (pip.start_ip == (uintptr_t)&__libc_start_main) {            break;        }        if (pip.start_ip == (intptr_t)interpretFunction) {            // TODO Do we still need to crawl the interpreter itself?            gatherInterpreterRootsForFrame(&visitor, cur_bp);        }        collectRoots(cur_sp, (char*)cur_bp, stack);    }}
开发者ID:UIKit0,项目名称:pyston,代码行数:65,


示例19: visitor

intbe_visitor_amh_interface_ss::visit_operation (be_operation *node){  be_visitor_amh_operation_ss visitor (this->ctx_);  return visitor.visit_operation (node);}
开发者ID:CCJY,项目名称:ATCD,代码行数:6,


示例20: somMayGoBackwards

bool somMayGoBackwards(NFAVertex u, const NGHolder &g,                       const ue2::unordered_map<NFAVertex, u32> &region_map,                       smgb_cache &cache) {    /* Need to ensure all matches of the graph g up to u contain no infixes     * which are also matches of the graph to u.     *     * This is basically the same as firstMatchIsFirst except we g is not     * always a dag. As we haven't gotten around to writing an execute_graph     * that operates on general graphs, we take some (hopefully) conservative     * short cuts.     *     * Note: if the u can be jumped we will take jump edges     * into account as a possibility of som going backwards     *     * TODO: write a generalised ng_execute_graph/make this less hacky     */    assert(&g == &cache.g);    if (contains(cache.smgb, u)) {        return cache.smgb[u];    }    DEBUG_PRINTF("checking if som can go backwards on %u/n",                  g[u].index);    set<NFAEdge> be;    BackEdges<set<NFAEdge>> backEdgeVisitor(be);    depth_first_search(        g.g, visitor(backEdgeVisitor)                 .root_vertex(g.start)                 .vertex_index_map(get(&NFAGraphVertexProps::index, g.g)));    bool rv;    if (0) {    exit:        DEBUG_PRINTF("using cached result/n");        cache.smgb[u] = rv;        return rv;    }    assert(contains(region_map, u));    const u32 u_region = region_map.at(u);    for (const auto &e : be) {        NFAVertex s = source(e, g);        NFAVertex t = target(e, g);        /* only need to worry about big cycles including/before u */        DEBUG_PRINTF("back edge %u %u/n", g[s].index,                      g[t].index);        if (s != t && region_map.at(s) <= u_region) {            DEBUG_PRINTF("eek big cycle/n");            rv = true; /* big cycle -> eek */            goto exit;        }    }    ue2::unordered_map<NFAVertex, NFAVertex> orig_to_copy;    NGHolder c_g;    cloneHolder(c_g, g, &orig_to_copy);    for (NFAVertex v : vertices_range(g)) {        if (!is_virtual_start(v, g)) {            continue;        }        NFAVertex c_v = orig_to_copy[v];        orig_to_copy[v] = c_g.startDs;        for (NFAVertex c_w : adjacent_vertices_range(c_v, c_g)) {            add_edge_if_not_present(c_g.startDs, c_w, c_g);        }        clear_vertex(c_v, c_g);    }    NFAVertex c_u = orig_to_copy[u];    clear_in_edges(c_g.acceptEod, c_g);    add_edge(c_g.accept, c_g.acceptEod, c_g);    clear_in_edges(c_g.accept, c_g);    clear_out_edges(c_u, c_g);    if (hasSelfLoop(u, g)) {        add_edge(c_u, c_u, c_g);    }    add_edge(c_u, c_g.accept, c_g);    set<NFAVertex> u_succ;    insert(&u_succ, adjacent_vertices(u, g));    u_succ.erase(u);    for (auto t : inv_adjacent_vertices_range(u, g)) {        if (t == u) {            continue;        }        for (auto v : adjacent_vertices_range(t, g)) {            if (contains(u_succ, v)) {                add_edge(orig_to_copy[t], c_g.accept, c_g);                break;            }        }    }    pruneUseless(c_g);    be.clear();//.........这里部分代码省略.........
开发者ID:chris1201,项目名称:hyperscan,代码行数:101,


示例21: test_grid

static void test_grid(){	/* An empty grid behaves the same as a control so test here. */	test_control<gui2::tgrid>();	//std::cerr << __func__ << ": Detailed test./n";	/* Test the child part here. */	gui2::tgrid grid(2 ,2);	add_widget(grid, new gui2::tlabel(), "(1,1)", 0, 0);	add_widget(grid, new gui2::tlabel(), "(1,2)", 0, 1);	add_widget(grid, new gui2::tlabel(), "(2,1)", 1, 0);	add_widget(grid, new gui2::tlabel(), "(2,2)", 1, 1);	boost::scoped_ptr<gui2::iterator::twalker_> visitor(grid.create_walker());	/***** LABEL 1,1 *****/	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), static_cast<void*>(NULL));	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(1,1)");	/***** LABEL 2,1 *****/	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::valid);	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), static_cast<void*>(NULL));	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(2,1)");	/***** LABEL 1,2 *****/	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::valid);	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), static_cast<void*>(NULL));	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(1,2)");	/***** LABEL 2,2 *****/	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::valid);	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), false);	BOOST_REQUIRE_NE(visitor->get(gui2::iterator::twalker_::child), static_cast<void*>(NULL));	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child)->id(), "(2,2)");	/***** END *****/	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::invalid);	BOOST_CHECK_EQUAL(visitor->at_end(gui2::iterator::twalker_::child), true);	BOOST_CHECK_EQUAL(visitor->get(gui2::iterator::twalker_::child), static_cast<void*>(NULL));	/***** POST END *****/	BOOST_CHECK_EQUAL(visitor->next(gui2::iterator::twalker_::child), gui2::iterator::twalker_::fail);}
开发者ID:8680-wesnoth,项目名称:wesnoth-fork-old,代码行数:62,


示例22: pair

Player* ScriptedAI::GetPlayerAtMinimumRange(float minimumRange){    Player* player = NULL;    CellCoord pair(Trinity::ComputeCellCoord(me->GetPositionX(), me->GetPositionY()));    Cell cell(pair);    cell.SetNoCreate();    Trinity::PlayerAtMinimumRangeAway check(me, minimumRange);    Trinity::PlayerSearcher<Trinity::PlayerAtMinimumRangeAway> searcher(me, player, check);    TypeContainerVisitor<Trinity::PlayerSearcher<Trinity::PlayerAtMinimumRangeAway>, GridTypeMapContainer> visitor(searcher);    cell.Visit(pair, visitor, *me->GetMap(), *me, minimumRange);    return player;}
开发者ID:shaunk1593,项目名称:Crusade,代码行数:16,


示例23: Serialize

 void Serialize(Sink & sink) {   coding::binary::HeaderSerVisitor<Sink> visitor(sink);   visitor(*this); }
开发者ID:milchakov,项目名称:omim,代码行数:5,


示例24: GetCreatureListWithEntryInGrid

void GetCreatureListWithEntryInGrid(std::list<Creature*>& lList, WorldObject* pSource, uint32 uiEntry, float fMaxSearchRange){    CellPair pair(MaNGOS::ComputeCellPair(pSource->GetPositionX(), pSource->GetPositionY()));    Cell cell(pair);    cell.data.Part.reserved = ALL_DISTRICT;    cell.SetNoCreate();    AllCreaturesOfEntryInRange check(pSource, uiEntry, fMaxSearchRange);    MaNGOS::CreatureListSearcher<AllCreaturesOfEntryInRange> searcher(lList, check);    TypeContainerVisitor<MaNGOS::CreatureListSearcher<AllCreaturesOfEntryInRange>, GridTypeMapContainer> visitor(searcher);    CellLock<GridReadGuard> cell_lock(cell, pair);    cell_lock->Visit(cell_lock, visitor, *(pSource->GetMap()), *pSource, fMaxSearchRange);}
开发者ID:onrevax,项目名称:Mangos-Zero-Script,代码行数:14,


示例25: markPhase

void markPhase() {#ifndef NVALGRIND    // Have valgrind close its eyes while we do the conservative stack and data scanning,    // since we'll be looking at potentially-uninitialized values:    VALGRIND_DISABLE_ERROR_REPORTING;#endif    TraceStack stack(roots);    GCVisitor visitor(&stack);    threading::visitAllStacks(&visitor);    gatherInterpreterRoots(&visitor);    for (void* p : nonheap_roots) {        Box* b = reinterpret_cast<Box*>(p);        BoxedClass* cls = b->cls;        if (cls) {            ASSERT(cls->gc_visit, "%s", getTypeName(b));            cls->gc_visit(&visitor, b);        }    }    for (auto h : *getRootHandles()) {        visitor.visit(h->value);    }    // if (VERBOSITY()) printf("Found %d roots/n", stack.size());    while (void* p = stack.pop()) {        assert(((intptr_t)p) % 8 == 0);        GCAllocation* al = GCAllocation::fromUserData(p);        assert(isMarked(al));        // printf("Marking + scanning %p/n", p);        GCKind kind_id = al->kind_id;        if (kind_id == GCKind::UNTRACKED) {            continue;        } else if (kind_id == GCKind::CONSERVATIVE) {            uint32_t bytes = al->kind_data;            if (DEBUG >= 2) {                if (global_heap.small_arena.contains(p)) {                    SmallArena::Block* b = SmallArena::Block::forPointer(p);                    assert(b->size >= bytes + sizeof(GCAllocation));                }            }            visitor.visitPotentialRange((void**)p, (void**)((char*)p + bytes));        } else if (kind_id == GCKind::PRECISE) {            uint32_t bytes = al->kind_data;            if (DEBUG >= 2) {                if (global_heap.small_arena.contains(p)) {                    SmallArena::Block* b = SmallArena::Block::forPointer(p);                    assert(b->size >= bytes + sizeof(GCAllocation));                }            }            visitor.visitRange((void**)p, (void**)((char*)p + bytes));        } else if (kind_id == GCKind::PYTHON) {            Box* b = reinterpret_cast<Box*>(p);            BoxedClass* cls = b->cls;            if (cls) {                // The cls can be NULL since we use 'new' to construct them.                // An arbitrary amount of stuff can happen between the 'new' and                // the call to the constructor (ie the args get evaluated), which                // can trigger a collection.                ASSERT(cls->gc_visit, "%s", getTypeName(b));                cls->gc_visit(&visitor, b);            }        } else if (kind_id == GCKind::HIDDEN_CLASS) {            HiddenClass* hcls = reinterpret_cast<HiddenClass*>(p);            hcls->gc_visit(&visitor);        } else {            RELEASE_ASSERT(0, "Unhandled kind: %d", (int)kind_id);        }    }#ifndef NVALGRIND    VALGRIND_ENABLE_ERROR_REPORTING;#endif}
开发者ID:guangwong,项目名称:pyston,代码行数:81,



注:本文中的visitor函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ visualRect函数代码示例
C++ visit_type_str函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。