jeudi 30 juin 2016

Template overload precedence


I want to have two overloads of a template function but have one take precedence. I am trying to define a size() function that uses the size member function if available but falls back to using std::begin() and std::end() (This is needed for say std::forward_list()). This is what they look like:

template <class Container>
constexpr auto size(const Container& cont) -> decltype (cont.size())
{
    return cont.size();
}

template <class Container>
auto size(const Container& cont) -> decltype (
    std::distance(std::begin(cont), std::end(cont)))
{
    return std::distance(std::begin(cont), std::end(cont));
}

The problem is that the compiler can't decide which overload to use for containers with a size() and a begin()/end(). How do I make it choose the first implementation when possible? (I know SFINAE is part of the solution, but I am not knowledgeable enough in the arcane arts to figure it out)

Also (unrelated), is there an easier way to declare the return type for the second function?


Aucun commentaire:

Enregistrer un commentaire