2014-10-09 67 views
0

我最近开始使用Boost C++库,并且正在测试可以容纳任何数据类型的any类。实际上,我试图定义operator<<以轻松打印any类型的任何变量的内容(当然,内容的类别也应该有operator<<)。 我只开始样本类型(int,double ...),因为它们默认显示。直到现在,我有这个代码:Cast boost ::将任何实例转换为其实际类型

#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 typetype_info这个particular type

+1

无法枚举“所有可能的类型”。该类型被称为* any *,而不是* every *。 – 2014-10-09 00:07:06

+0

也许您可以使用[Boost type erasure](http://www.boost.org/doc/libs/1_55_0/doc/html/boost_typeerasure.html)获取更具体的类型擦除需求。就目前而言,这个问题令人困惑,因为标题是关于演员的(这可能是错误的或不明智的),而机构是关于格式化的,这是一个很好理解而且不同的问题。 – 2014-10-09 00:08:04

+0

我从来没有使用'boost :: any',而且我写了一些非常奇怪的代码。你也不需要使用它。它的用途很少。 – 2014-10-09 00:12:40

回答

1

Boost.Any any

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

解决方案是更改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; 
} 
相关问题