OpenMesh 报错“Use dereferencing operators -> and * instead.”的解决

今天直接编译老师给的材料里几年前的代码,用的是OpenMesh 7.1的库,在 handle() 函数中遇到了“This function clutters your code. Use dereferencing operators -> and * instead.”的问题,搜索发现网上的解答不多,而且大多OpenMesh的教程都是前几年的,比较过时了。按照提示改代码后解决了,但由此引出了不少相关的问题,大多是之前的函数在 OpenMesh7 中不再支持的原因。在这里总结一下两个现在已经deprecated的函数。

1. handle()

示例代码:

        //输出所有的顶点
	for (auto it = mesh.vertices_begin(); it != mesh.vertices_end(); it++) 
	{
		auto point = mesh.point(it.handle());//这里会报错,应该改成auto point = mesh.point(*it);

		std::cout << point[0] << "," << point[1] << "," << point[2] << std::endl;
	}

在这里,it是迭代器,但mesh.point(it.handle())这里会报错“This function clutters your code. Use dereferencing operators -> and * instead.”,让你不要再用 handle(),而是用*。也就是把it.handle()改成 *it,就可以了,这两句代码功能是完全一样的。

错误原因:在下面handle的定义中可以看到,handle()就是返回hnd_。而这个 hnd_ 的定义是protected: value_handle hnd_。value_handle类型实际上就是迭代器的 value_type,被typedef来的。所以handle()就是返回迭代器所指向的值。现在handle功能被废弃了,在官方文档上也有说明。只要你用到,编译器就报错,所以改用 * 即可。

        /**
         * \brief Get the handle of the item the iterator refers to.
         * \deprecated 
         * This function clutters your code. Use dereferencing operators -> and * instead.
         */
        DEPRECATED("This function clutters your code. Use dereferencing operators -> and * instead.")
        value_handle handle() const {
            return hnd_;
        }

在 * 的定义里可以看到,*运算符的功能就是return hnd_;  替代了原来的handle()

        /// Standard dereferencing operator.
        reference operator*() const {
            return hnd_;
        }

        /// Standard pointer operator.
        pointer operator->() const {
            return &hnd_;
        }

2. 迭代器到值类型的隐式转换

示例代码:

        //获得每个边的顶点
	for (auto it = mesh.halfedges_begin(); it != mesh.halfedges_end(); ++it)
	{
            //下面这两句会报错,因为it是迭代器,而参数应该是个handle类型。应该吧it改为*it
	    std::cout << mesh.from_vertex_handle(it) << " ";
	    std::cout << mesh.to_vertex_handle(it) << std::endl;
	}

在老代码里,还是可以这样写的,因为在OpenMesh里定义了这样一个隐式转换:

        /**
         * \brief Cast to the handle of the item the iterator refers to.
         * \deprecated
         * Implicit casts of iterators are unsafe. Use dereferencing operators
         * -> and * instead.
         */
        DEPRECATED("Implicit casts of iterators are unsafe. Use dereferencing operators -> and * instead.")
        operator value_handle() const {
            return hnd_;
        }

但现在这被认为是不安全的,为了防止混淆迭代器和迭代器的hnd_,所以不再支持隐式转换。如果你使用隐式转换,就会提示"Implicit casts of iterators are unsafe. Use dereferencing operators -> and * instead."。

 

事实上,如果你非要使用的话,可以把库的头文件定义里相应的DERPRECATED()这一行删掉,就不会报错了。

 

 

你可能感兴趣的:(OpenMesh,C++)