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

标签 c++ boost boost-type-erasure

我是 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/

相关文章:

具有多个构造函数签名的 C++ 通用工厂?

c++ - 使用 const 成员函数 boost type_erasure any

c++ - 使用 SendMessage() C++ 获取文本

c++ - 无法编译应该从 Bjarne stroustrup 的编程原理和实践的第 12 章工作的图形代码

c++ - PBYTE 和 BYTE* 有什么区别?

c++ - 当 boost deadline_timer 在超时处理程序中被销毁时会发生什么

c++ - boost::random::discrete_distribution 是否可以动态调整大小?

c++ - boost::polygon bool 减法会产生额外的行

c++ - 具有前向声明类型的 Boost.TypeErasure

c++ - 为什么无符号短(乘)无符号短转换为有符号整数?