c++ - 将 boost::any 实例转换为其真实类型

标签 c++ boost casting boost-any

我最近开始使用 Boost C++ 库,我正在测试 any可以容纳任何数据类型的类。实际上我正在尝试定义 operator<<轻松打印 any 类型的任何变量的内容(当然,内容的类别也应该定义 operator<<)。 我只从示例类型( intdouble ...)开始,因为默认情况下会显示它们。到目前为止,我有这段代码:

#include <boost/any.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace boost;

ostream& operator<<(ostream& out, any& a){
    if(a.type() == typeid(int))
        out << any_cast<int>(a);
    else if(a.type() == typeid(double))
        out << any_cast<double>(a);
    // else ...
    // But what about other types/classes ?!
}

int main(){
    any a = 5;
    cout << a << endl;
}

所以这里的问题是我必须枚举所有可能的类型。有没有办法将变量转换为 particular type拥有type_info这个 particular type

最佳答案

Boost.Any any

boost::any您不能像其他人已经在评论中指出的那样这样做。那是因为 boost::any忘记关于它存储的值(value)类型的一切,并要求你知道那里有什么类型。虽然您无法枚举所有可能的类型。

解决办法是改成boost::any这样它就忘记了有关它存储的值类型的所有信息,除了如何将其流出。 Mooing Duck 在评论中提供了一种解决方案。另一种方法是编写一个新版本的 boost::any但扩展其内部结构以支持流操作。

boost spirit hold_any

Boost.Spirit 已经在 <boost/spirit/home/support/detail/hold_any.hpp> 中提供了类似的东西.

Boost.TypeErasure any

然而,更好的方法是使用 Boost.TypeErasureany正如 Kerrek SB 在他的评论中提到的那样。

您的案例示例(使用 << )如下所示:

#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/operators.hpp>
#include <iostream>
#include <string>

int main() {
    typedef
        boost::type_erasure::any<
            boost::mpl::vector<
                boost::type_erasure::destructible<>,
                boost::type_erasure::ostreamable<>,
                boost::type_erasure::relaxed
            >
        > my_any_type;

    my_any_type my_any;

    my_any = 5;
    std::cout << my_any << std::endl;
    my_any = 5.4;
    std::cout << my_any << std::endl;
    my_any = std::string("text");
    std::cout << my_any << std::endl;
}

关于c++ - 将 boost::any 实例转换为其真实类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26268330/

相关文章:

C++ 定义类型转换

c++ - OpenGL 不让我画东西

c++ - 编译期间 boost xml 序列化失败

Java - 带返回值的异步方法

inheritance - 多态性没有像我想象的那样工作?

c++ - 将交换与对象自杀一起使用

c++ - 在C++中交换短语中单词的前两个字母

c++ - 如何在按下 "stop"按钮时捕获 clion 中捆绑的 GDB 发出的信号?

c++ - 全局变量,c++

c++ - 在 Boost 库 asio 示例中,处理程序分配之前的 [this, self] 是什么意思?