2012-01-16 133 views
2

中使用boost :: lexical_cast和自定義運算符<<給定兩個命名空間,每個命名空間爲std :: vector提供運算符< <的專門化,是否可以使用boost :: lexical_cast?如果我將其中一個操作符提升到全局命名空間,我知道代碼將起作用,但這隻會導致其他位置出現歧義錯誤。是否有一些巧妙的「使用」指令用法,我可以用它來允許boost :: lexical_cast找到合適的操作符?在命名空間

//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; 
}