[英]converting boost type erased type back to original type gives me boost::bad_any_cast
我是提高類型擦除的新手,但在將對象轉換回其原始類型時遇到問題。 根據我對boost文檔的理解,我應該能夠使用boost :: any_cast將類型擦除的對象轉換回其原始類型,但是以下代碼失敗,並帶有bad_any_cast異常。 我究竟做錯了什么? 謝謝一群!
https://www.boost.org/doc/libs/1_67_0/doc/html/boost/any_cast.html
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 = boost::any_cast<xThing>(xconc);
return 0;
}
您需要調用boost::type_erasure::any_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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.