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

北城以北 提交于 2019-11-28 13:22:42

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

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 if you have C++17 or better support because it will improve reusability across container and array types.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!