Does C++ have a free function `size(object)`?

size is actually C++17 functionality. The real benefit to is akin to the benefit of begin and end from C++11.

Note that the first definition of size simply returns the container's size method.

So if I have a templated function like this:

template <typename T>
auto foo(const T& bar) { return bar.size(); }

This could only be used with containers, but if I change that to:

template <typename T>
auto foo(const T& bar) { return size(bar); }

It can be used with C-style arrays too. I've added a live example here: http://melpon.org/wandbox/permlink/Rlpi5wueA14JOW2P

In summary, you should always use size and other range based functions because of the improvements to generality and container agnostic code (see here for more).


MSVS 2015 has a size function defined in xutility

template<class _Container>
auto inline size(const _Container& _Cont)
    -> decltype(_Cont.size())
{   // get size() for container
return (_Cont.size());
}

This is the function that is being used when you call

cout << "Using size(myvar) = " << size(myvar) << endl;

This is not a standard C++11/14 function and will not run on gcc or clang

This was detailed in the blog post C++11/14/17 Features In VS 2015 RTM


According to http://blogs.msdn.com/b/vcblog/archive/2015/06/19/c-11-14-17-features-in-vs-2015-rtm.aspx VS2015 started to support non-member size n4280 proposal.

It's kinda weird they enable it out-of-the-box with out any define or compiler flag. But it seems like it. Currently it might be considered non-standard, although it is already voted in for c++17.