2017-02-17 6 views
1

인수로 을 취하여 vector<boost::variant<specific_type, ...>>을 다른 함수로 호출하는 함수 서명이 있습니다. 인수의 간단한 전송이 작동하지 않습니다. 재 포장 만이 유일한 해결책이라는 것을 알았지 만 이것이 가장 효과적인 해결책은 아닙니다. 어떻게 든 간단한 캐스트가 가능합니까?C++, 벡터 <specific_type>을 <boost :: variant>로 캐스팅하십시오.

최소 예 :

#include "boost/variant.hpp" 

#include <string> 
#include <vector> 

typedef boost::variant<int, std::string> test_t; 

void inner(std::vector<test_t> a) {} 

void outer(std::vector<int> a) { 
    // the following does not work: 
    //inner(a); 
    //inner((std::vector<test_t>) a); 
    //inner(const_cast<std::vector<test_t>>(a)); 
    //inner(reinterpret_cast<std::vector<test_t>>(a)); 
    //inner(static_cast<std::vector<test_t>>(a)); 
    //inner(dynamic_cast<std::vector<test_t>>(a)); 

    // only "valid" solution 
    std::vector<test_t> b; 
    for (const int i : a) { 
     b.push_back(i); 
    } 
    inner(b); 
} 

int main() 
{ 
    std::vector<int> a = { 1, 4, 2 }; 
    outer(a); 
} 

답변

3

간단한 캐스트가 가능 어떻게 든 있습니까?

아니요. 그러한 캐스트가 없습니다.

이 우리가 사용하여 조금 더 잘 할 수없는 가장 성능이 좋은 솔루션

수정 가능성이 vector range constructor : 우리가 같이 사용하는 것이

template< class InputIt > 
vector(InputIt first, InputIt last, 
     const Allocator& alloc = Allocator()); 

:

void outer(std::vector<int> const& a) { 
    inner({a.begin(), a.end()}); 
} 
+0

이렇게하면 메모리를 추가 할당하지 않아도 전체 벡터를 반복 할 수 있습니까? 구문은 꽤 좋습니다. – gerion

+0

@gerion 그럴리 없어. 각 요소에 대해 'variant'를 만들어야합니다. 실제로 모든 요소를 ​​보지 않고는 할 수 없습니다. – Barry

+0

@gerion 적어도 개체를 변형 벡터로 옮길 수 있습니까? –