samedi 16 mai 2015

enum and static const member variable in template class

I want to test whether operator << is overloaded to a class.
I have read this and this posts and tried to write another version with c++11.
This is my code:

#include <iostream>
#include <type_traits>

namespace TEST{
  class NotDefined{};

  template<typename T> 
  NotDefined& operator << (::std::ostream&, const T&);

  template <typename T>
  struct StreamInsertionExists {
    static std::ostream &s;
    static T const &t;
    enum { value = std::is_same<decltype(s << t), NotDefined>() };
  };
}

struct A{
  int val;
    friend ::std::ostream& operator<<(::std::ostream&, const A&);
};

::std::ostream& operator<<(::std::ostream& os, const A& a)
{
  os << a.val;
  return os;
}

struct B{};

int main() {
  std::cout << TEST::StreamInsertionExists<A>::value << std::endl;
  std::cout << TEST::StreamInsertionExists<B>::value << std::endl;

}

But there are errors:

test_oper.cpp:40:57: error: reference to overloaded function could not be resolved; did you mean to call it?
std::cout << TEST::StreamInsertionExists::value << std::endl;

/Applications/http://ift.tt/1cGqyke: note:
possible target for call
endl(basic_ostream<_CharT, _Traits>& __os)

test_oper.cpp:30:17: note: candidate function not viable: no known conversion from 'TEST::NotDefined' to '::std::ostream &'
(aka 'basic_ostream &') for 1st argument
::std::ostream& operator<<(::std::ostream& os, const A& a)

test_oper.cpp:15:15: note: candidate template ignored: couldn't infer template argument 'T'
NotDefined& operator << (::std::ostream&, const T&);

If I replace the line
enum { value = std::is_same<decltype(s << t), NotDefined>() };
to
static const bool value = std::is_same<decltype(s << t), NotDefined>();
then everything goes fine.

Why this happens?

Aucun commentaire:

Enregistrer un commentaire