2015-02-05 3 views
3

boost::optional<A>boost::optional<B>으로 캐스팅하는 우아한 방법이 있는지 궁금합니다. BA에서 구성 할 수 있습니다. 작동 방식 :boost :: optional and type conversion

하지만 결코 사용하지 않을 값을 입력해야 할 필요가 있습니다. 더 좋은 제안이 있습니까?

답변

6
template<class T, class U> 
boost::optional<T> optional_cast(U&& u) { 
    if (u) return T(*std::forward<U>(u)); 
    else return {}; 
} 

또한 재미있게 포인터를 사용합니다. C++ 03

template<class T, class U> 
boost::optional<T> optional_cast(U const& u) { 
    if (u) return T(*u); 
    else return boost::none; 
} 

대신 작동하지만 다수의 경우에 덜 효율적이 될 것이다


int main() { 
    boost::optional<int> i; 
    ... // i gets initialized or not 
    boost::optional<Foo> foo = optional_cast<Foo>(i); 
    return 0; 
} 

에서.

관련 문제