2012-01-16 127 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; 
}