2

それぞれが std::vector の operator<< の特殊化を提供する 2 つの名前空間が与えられた場合、boost::lexical_cast を使用できますか? オペレーターの 1 つをグローバル名前空間に昇格させれば、コードが機能することはわかっていますが、他の場所であいまいなエラーが発生するだけです。boost::lexical_cast が正しい演算子を見つけられるようにするために使用できる「using」ディレクティブの巧妙な使用法はありますか?

//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 の std 名前空間にプルすることです。これは、.cpp が 1 つのバージョンのみを必要とする場合は機能しますが、.cpp が複数のバージョンを必要とする一般的なケースでは機能しません。

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

1 に答える 1

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;
}
于 2012-01-16T20:32:09.127 に答える