2014-10-09 3 views
0

최근에 Boost C++ 라이브러리를 사용하기 시작했으며 모든 데이터 형식을 수용 할 수있는 any 클래스를 테스트하고 있습니다. 사실 나는 을 정의하여 any 유형의 변수의 내용을 쉽게 인쇄하려고합니다. 물론 내용의 클래스에도 operator<<이 정의되어 있어야합니다. 샘플 형식 (int, double ...)은 기본적으로 표시 되었기 때문에 시작되었습니다. 그리고 지금까지이 코드를 가지고 있습니다.부스트 :: 모든 인스턴스를 실제 형식으로

#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

당신은 "가능한 모든 유형"열거 할 수 없습니다. 그 타입은 * every *가 아닌 * any *라고 불린다. –

+0

더 자세한 유형 삭제 필요성을 위해 [부스트 유형 삭제] (http://www.boost.org/doc/libs/1_55_0/doc/html/boost_typeerasure.html)를 사용할 수 있습니다. 제목은 캐스팅 (잘못되었거나 잘못 알려졌을 때)에 관한 것이기 때문에 질문은 혼란 스럽습니다. 반면에 시체는 형식화에 관한 것이지 잘 이해되고 다소 다른 문제입니다. –

+0

나는'boost :: any'를 사용 해본 적이 없으며 꽤 기괴한 코드를 작성했습니다. 당신도 그것을 사용할 필요가 없습니다. 그것의 사용은 극소수입니다. –

답변

1

Boost.Any 당신이 할 수없는 boost::anyany

이미 다른 사람이 의견에 명시된대로 그. 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

중 파 더 좋은 방법은 사용 그러나 그의 코멘트에 Kerrek SB 언급 한 바와 같이 Boost.TypeErasureany.

사건 (<<의 사용)에 대한 예는 다음과 같습니다

#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; 
} 
관련 문제