mardi 27 octobre 2015

Is there a way to write a SFINAE test of "for-eachability" of a type?

I have used SFINAE expressions to test for if a type supports operator<<

namespace details
{
  template<typename T>
  struct sfinae_true : std::true_type
  {
  };

  template<typename T>
  sfinae_true<decltype (std::declval<std::ostream &> () << std::declval<T const &> ())> test_for_ostream (int);

  template<typename T>
  std::false_type test_for_ostream (long);
}

template<typename T>
struct supports_ostream : decltype (details::test_for_ostream<T> (0))
{
};

What I would like to test is if this a type T can be iterated over like this

for (auto && v : vs) {} // vs is T const &

The dilemma is that this is a statement and not an expression which makes it incompatible to use with decltype

I was thinking to use lambdas to convert a statement to an expression like this

auto x = [] () { for (auto && v : vs) {}; return 0; } (); // vs is T const &

However decltype of expressions containing lambdas seems to be explicitly forbidden:

// Won't compile in clang, gcc nor VC++
using x_t = decltype ([] () { for (auto && v : vs) {}; return 0; } ()); // vs is T const &

So that disqualifies it for use in a test function like this:

namespace details
{
  template<typename T>
  sfinae_true<decltype (
    [] () { for (auto && v : std::declval<T const &> ()) ; } () 
    )> test_for_container (int); 
  // Won't work because lambdas aren't allowed in unevaluated contexts

  template<typename T>
  std::false_type test_for_container (long);
}

template<typename T>
struct is_container : decltype (details::test_for_container<T> (0))
{
};

So I have run out of ideas, so I thought perhaps someone @Stackoverflow can come up with something interesting.

PS.

I can somewhat understand why decltype ([] () {}) isn't allowed but decltype ([] () {} ()) should always be well-defined ie void.

Aucun commentaire:

Enregistrer un commentaire