1

<<オペレーターが処理できるものは何でも受け取る関数を作成したいと考えていますstd::cout。壊れる例があります。

#include <iostream>

template <typename T>
void my_print(const T &t) {
  std::cout << t;
}

int main() {
  my_print("hello\n"); // works
  my_print(4); // works
  my_print(std::endl); // compiler error
  return 0;
}

に変更しても失敗しますvoid my_print(T t)。コンパイルエラーは

エラー: 'my_print(<unresolved overloaded function type>)' の呼び出しに一致する関数がありません
注:候補は
注: template<class T> void my_print(const T&)

t引数が に入れられていることを確認したときに、コンパイラがそれを解決できないのはなぜcoutですか?

これを修正する良い方法はありますか、または追加の<<ケースを手動で提供する必要がありますか?void my_print(ostream& (*pf)(ostream&));

編集:関数であることは知っendlています。関数型はテンプレートとして受け入れられないというのが答えですか? 私が持つことができないように[T = ostream& (*)(ostream&)]

4

1 に答える 1

0

std::endl実際には関数テンプレートです。ここまたはここで完全なドキュメントを読むことができます。次のように定義されています。

template< class CharT, class Traits >
std::basic_ostream<charT,traits>& endl( std::basic_ostream<CharT, Traits>& os );

編集:このソリューションを使用して、必要なものを達成できます(ここから漠然と適応しました)

#include <iostream>

// handles the other types
template <typename T>
void my_print(const T &t) {
  std::cout << t;
}

// alias a few things to make the prototypes readable
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
typedef CoutType& (*StandardEndLine)(CoutType&);

int main() {
  my_print("hello\n"); // works
  my_print(4); // works
  my_print((StandardEndLine)std::endl); // <- NOTE: there is an explicit cast
  return 0;
}
于 2013-04-22T23:52:50.557 に答える