2012-01-16 4 views
2

std :: vector에 대해 각각 < <의 연산자를 제공하는 두 개의 네임 스페이스가 주어지면 boost :: lexical_cast를 사용할 수 있습니까? 연산자 중 하나를 전역 네임 스페이스로 승격해도 코드가 작동하지만 다른 위치에서 모호성 오류가 발생한다는 것을 알고 있습니다. boost :: lexical_cast가 올바른 연산자를 찾을 수 있도록 "using"지시어를 영리하게 사용합니까?boost :: lexical_cast with namespace

//In some .h file 
namespace A 
{ 
    template <typename T, typename A> 
    std::ostream & operator<<(std::ostream & os, const std::vector<T, A> & v) 
    { 
    ... 
    } 
} 

namespace B 
{ 
    template <typename T, typename A> 
    std::ostream & operator<<(std::ostream & os, const std::vector<T, A> & v) 
    { 
    ... 
    } 
} 

//Later in a .cpp 
namespace A 
{ 
    std::vector<int> v; 
    std::string s = boost::lexical_cast<std::string>(v); //Fails because operator<< is not defined for std::vector in the std namespace 
} 

namespace B 
{ 
    std::stringstream stream; 
    std::vector<int> v; 
    stream << v; //This will be ambiguous if we promote the A::operator<< into the std namespace 
} 

편집 : 지금까지 가지고 올 것 중에 최고는 .CPP의 표준 네임 스페이스에 연산자를 당겨하는 것입니다. .cpp에 하나의 버전 만 있으면되지만 .cpp에는 여러 버전이 필요한 일반적인 경우에는 작동하지 않습니다.

namespace std 
{ 
    using A::operator<<; 
} 

답변

2

당신은 (lexical_cast으로 검증되지 않은 있지만, 다른 것들과 함께 작동) 이름없는 네임 스페이스를 사용할 수 있습니다

namespace B 
{ 
    operator<<(x, y) { } 
} 

namespace A 
{ 
    operator<<(x, y) { } 

    namespace 
    { 
     using B::operator<<; 

     std::string _s = boost::lexical_cast<std::string>(v); 
    } 

    std::string& s = _s; 
} 
관련 문제