3

我最近开始使用BoostC++ 库,并且正在测试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_infothis 的particular type

4

1 回答 1

1

Boost.Anyany

正如其他人已经在boost::any评论中指出的那样,你不能这样做。那是因为boost::any忘记了它存储的值类型的所有内容,并要求您知道存在什么类型。虽然您无法枚举所有可能的类型。

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

升压精神hold_any

Boost.Spirit 已经在<boost/spirit/home/support/detail/hold_any.hpp>.

Boost.TypeErasureany

然而,更好的方法是使用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;
}
于 2016-03-06T09:32:31.810 回答