Использование SFINAE для проверки глобального оператора <<?

Я хочу иметь несколько перегруженных, глобальных to_string() функции, которые принимают некоторый тип T и преобразовать его в строковое представление. В общем случае я хочу написать:

template<typename T,class OutputStringType> inline
typename enable_if<!std::is_pointer<T>::value
                && has_insertion_operator<T>::value,
                   void>::type
to_string( T const &t, OutputStringType *out ) {
  std::ostringstream o;
  o << t;
  *out = o.str();
}

Моя реализация has_insertion_operator пока что есть:

struct sfinae_base {
  typedef char yes[1];
  typedef char no[2];
};

template<typename T>
struct has_insertion_operator : sfinae_base {
  template<typename U> static yes& test( U& );
  template<typename U> static no& test(...);

  static std::ostream &s;
  static T const &t;

  static bool const value = sizeof( test( s << t ) ) == sizeof( yes ); // line 48
};

(Это заимствует из этого и этого.) Это, кажется, работает. Но теперь я хочу иметь перегруженную версию to_string для типов, которые не имеют operator<< но есть свои to_string() функция- член, то есть:

template<class T,class OutputStringType> inline
typename enable_if<!has_insertion_operator<T>::value
                && has_to_string<T,std::string (T::*)() const>::value,
                   void>::type
to_string( T const &t, OutputStringType *out ) {
  *out = t.to_string();
}

Реализация has_to_string является:

#define DECL_HAS_MEM_FN(FN_NAME)                                      \
  template<typename T,typename S>                                     \
  struct has_##FN_NAME : sfinae_base {                                \
    template<typename SignatureType,SignatureType> struct type_check; \
    template<class U> static yes& test(type_check<S,&U::FN_NAME>*);   \
    template<class U> static no& test(...);                           \
    static bool const value = sizeof( test<T>(0) ) == sizeof( yes );  \
  }

DECL_HAS_MEM_FN( to_string );

(Эта часть, кажется, работает нормально. Это адаптировано из этого.) Однако, когда у меня есть:

struct S {
  string to_string() const {
    return "42";
  }
};

int main() {
  string buf;
  S s;
  to_string( s, &buf ); // line 104
}

Я получил:

foo.cpp: In instantiation of ‘const bool has_insertion_operator<S>::value’:
foo.cpp:104:   instantiated from here
foo.cpp:48: error: no match for ‘operator<<’ in ‘has_insertion_operator<S>::s << has_insertion_operator<S>::t’

Похоже, сфина не происходит. Как мне написать has_insertion_operator правильно, что он определяет, является ли глобальный operator<< доступен?

К вашему сведению: я использую g++ 4.2.1 (тот, который поставляется как часть Xcode в Mac OS X). Кроме того, я хотел бы, чтобы код был только стандартным C++03 без сторонних библиотек, например, Boost.

Спасибо!

2 ответа

Решение

Я должен был просто быть более верным этому ответу. Рабочая реализация это:

namespace has_insertion_operator_impl {
  typedef char no;
  typedef char yes[2];

  struct any_t {
    template<typename T> any_t( T const& );
  };

  no operator<<( std::ostream const&, any_t const& );

  yes& test( std::ostream& );
  no test( no );

  template<typename T>
  struct has_insertion_operator {
    static std::ostream &s;
    static T const &t;
    static bool const value = sizeof( test(s << t) ) == sizeof( yes );
  };
}

template<typename T>
struct has_insertion_operator :
  has_insertion_operator_impl::has_insertion_operator<T> {
};

Я считаю, что это на самом деле не зависит от SFINAE.

Инициализатор value в строке 48 не в контексте, где работает SFINAE. Попробуйте переместить выражение в объявление функции.

#include <iostream>

struct sfinae_base {
  typedef char yes[1];
  typedef char no[2];
};

template<typename T>
struct has_insertion_operator : sfinae_base {

  // this may quietly fail:
  template<typename U> static yes& test(
      size_t (*n)[ sizeof( std::cout << * static_cast<U*>(0) ) ] );

  // "..." provides fallback in case above fails
  template<typename U> static no& test(...);

  static bool const value = sizeof( test<T>( NULL ) ) == sizeof( yes );
};

Тем не менее, я должен подвергнуть сомнению степень сложности, которая входит в это. Я вижу неортогональные механизмы, которые будут шлифовать друг против друга (to_string против operator<<) и я слышу, как меня бросают плохие предположения (например, что operator<< является глобальным по отношению к члену, хотя реализованный код выглядит нормально в этом отношении).

Другие вопросы по тегам