簡単な答え: キャストまたはを使用し続けるかtoStr()
、独自の関数を記述しますoperator<<
。(私はしたいl1.toStr()
です(string)l1
。)
長い答え: 標準ライブラリに関数がある場合、これは機能する可能性があります
std::ostream& operator<<( std::ostream&, std::string const& );
それはほとんどですが、技術的にはそうではありません。ostream
とは両方とも、string
実際にはテンプレートのインスタンス化の typedef です。そして、一方を他方に挿入するためのテンプレート機能があります。
// This is somewhat simplified. For the real definitions, see the Standard
// and/or your complying implementation's headers.
namespace std {
typedef basic_string<char> string;
typedef basic_ostream<char> ostream;
template <typename CharT>
basic_ostream<CharT>& operator<<(
basic_ostream<CharT>&,
basic_string<CharT> const&);
}
そのためcout << str
、 where の type str
isstd::string
を使用すると、そのテンプレート関数を with で使用することがわかりますCharT = char
。
しかし、C++ では、同じ呼び出しでコンパイラに暗黙的な型変換 ( Literal
to string
) とテンプレート関数のテンプレート パラメーターの推定( )の両方を理解させることはできません。CharT = char