gpt4 book ai didi

c++ - 将 boost 类型删除类型转换回原始类型给我 boost::bad_any_cast

转载 作者:行者123 更新时间:2023-11-28 04:40:36 25 4
gpt4 key购买 nike

我是 boost 类型删除的新手,在将对象转换回其原始类型时遇到问题。根据我对 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;
}

关于c++ - 将 boost 类型删除类型转换回原始类型给我 boost::bad_any_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50249390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com