我目前正在从事一个项目,我使用:
我遇到了一个关于const_cast的问题。我到处搜索,在网上找不到能帮我的消息来源。当我在测试方法中调用BOOST_FOREACH时,问题就出现了。我一直收到以下错误:
/usr/include/boost/foreach.hpp: In member function
'boost::foreach_detail_::rvalue_probe<T>::operator T&() const [with T =
boost::unordered_map<std::basic_string<char>, std::basic_string<char> >]':
... instantiated from here /usr/include/boost/foreach.hpp:476:90:
error: invalid cast from type
Dereferee::const_cast_helper<boost::foreach_detail_::rvalue_probe<boost::unordered_map<std
::basic_string<char>, std::basic_string<char> > >*>
to type 'boost::unordered_map<std::basic_string<char>, std::basic_string<char> >*const_cast_helper
我开始剖析这个问题,发现const_cast操作符为了一些运行时检查而超载,我不知道是什么原因。总之,存在一个Dereferee::const_cast_helper,它是cxxtest依赖项的一部分,是const_cast操作符的重载。
此助手未定义const_cast运算符(!)
#ifdef const_cast
#undef const_cast
#endif最后,重新引入const_cast操作符:
#define const_cast ::Dereferee::const_cast_helper
这样,每次调用const_cast时,都会调用该助手的适当构造函数。构造函数接受指针、引用、const指针和const引用。
来源在这里:cast.h
rvalue_probe
Boost还使用强制转换,以查看正在迭代的集合是否为lvalue或rvalue,以避免复制/重新计算表达式。
编译器抱怨如下:
template<typename T>
struct rvalue_probe
{
...
operator T &() const { return *reinterpret_cast<T *>(const_cast<rvalue_probe *>(this)); }
};在我的例子中,T是boost::unordered_map,在某种程度上,这个转换和助手的重载结合在一起.
解决它的方法?
我研究了可能的解决方案是什么,但我不知道如何实际实现它们,我没有太多的C++经验。我一点也不在乎在我的测试中是否会有这些编译时检查,我可以解决这个问题。所以,在这三个方向上的任何一个帮助都是最有帮助的!
const_cast_helper。当我运行我的测试程序(与测试项目不同的项目)时,我的代码会像预期的那样编译和运行,const_cast的过载会产生问题。const_cast_helper还是rvalue_probe中这样做,但没有起到任何作用。template <typename T> const_cast_helper(rvalue_probe<U>* value_to_cast) : cast_value(const_cast<U*>(value_to_cast)) { }
感谢您的提前投入!
发布于 2013-08-09 15:16:23
经过进一步的挖掘,我设法找到了一个解决办法。我为我的构建配置定义了一个符号DEREFEREE_NO_CONST_CAST。这使得const_cast_helper无法编译。希望不会有虫子爬进来,测试现在正在进行.
https://stackoverflow.com/questions/18145466
复制相似问题