C++ 将boost类型擦除的类型转换回原始类型会给我boost::bad_any_cast
我是一名新的boost类型擦除技术人员,在将对象转换回其原始类型时遇到了问题。从我对boost文档的理解来看,我应该能够使用boost::any_cast将类型擦除对象转换回其原始类型,但是以下代码失败,出现了一个错误的_any_cast异常。我做错了什么? 非常感谢C++ 将boost类型擦除的类型转换回原始类型会给我boost::bad_any_cast,c++,boost,boost-type-erasure,C++,Boost,Boost Type Erasure,我是一名新的boost类型擦除技术人员,在将对象转换回其原始类型时遇到了问题。从我对boost文档的理解来看,我应该能够使用boost::any_cast将类型擦除对象转换回其原始类型,但是以下代码失败,出现了一个错误的_any_cast异常。我做错了什么? 非常感谢 BOOST类型擦除成员((has_x),x,0) 名称空间bte=boost::type_erasure; 使用xConcept=boost::mpl::vector; 使用AnyXobject=bte::any; 结构xThi
BOOST类型擦除成员((has_x),x,0)
名称空间bte=boost::type_erasure;
使用xConcept=boost::mpl::vector;
使用AnyXobject=bte::any;
结构xThing{
浮点数x(){
返回4。;
}
浮动y(){
返回5。;
}
};
int main(){
//具体实施情况
xThing i;
//使用具体实现构造类型擦除对象
任意对象xconc(i);
//调用x()可以正确打印4
std::cout您需要调用boost::type\u erasure::any\u cast
下面是正确的程序:
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/member.hpp>
#include <iostream>
BOOST_TYPE_ERASURE_MEMBER((has_x), x, 0)
namespace bte = boost::type_erasure;
using xConcept = boost::mpl::vector<has_x <float(), bte::_self> ,
bte::copy_constructible<>,
bte::relaxed>;
using AnyXobject = bte::any<xConcept, bte::_self>;
struct xThing{
float x(){
return 4.;
}
float y(){
return 5.;
}
};
int main(){
// instance of concrete implementation
xThing i;
// using concrete implementation to construct type erased object
AnyXobject xconc(i);
// calling x() correctly prints 4
std::cout << xconc.x() << std::endl;
// converting back to concrete implementation fails with boost::bad_any_cast at runtime
auto j = bte::any_cast<xThing>(xconc);
return 0;
}
#包括
#包括
#包括
#包括
BOOST类型擦除成员((has x),x,0)
名称空间bte=boost::type_erasure;
使用xConcept=boost::mpl::vector;
使用AnyXobject=bte::any;
结构xThing{
浮点数x(){
返回4。;
}
浮动y(){
返回5。;
}
};
int main(){
//具体实施情况
xThing i;
//使用具体实现构造类型擦除对象
任意对象xconc(i);
//调用x()可以正确打印4
std::难道你不应该使用bte::any_cast吗?它真的必须像你的建议一样简单,我希望你是对的,但是boost::type_擦除不包含任何可以更正的内容…非常感谢!
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/member.hpp>
#include <iostream>
BOOST_TYPE_ERASURE_MEMBER((has_x), x, 0)
namespace bte = boost::type_erasure;
using xConcept = boost::mpl::vector<has_x <float(), bte::_self> ,
bte::copy_constructible<>,
bte::relaxed>;
using AnyXobject = bte::any<xConcept, bte::_self>;
struct xThing{
float x(){
return 4.;
}
float y(){
return 5.;
}
};
int main(){
// instance of concrete implementation
xThing i;
// using concrete implementation to construct type erased object
AnyXobject xconc(i);
// calling x() correctly prints 4
std::cout << xconc.x() << std::endl;
// converting back to concrete implementation fails with boost::bad_any_cast at runtime
auto j = bte::any_cast<xThing>(xconc);
return 0;
}