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

筅森魡賤 提交于 2019-11-27 07:40:29

问题


It seems that the way that most people find the size of a string is they just use the my_string.size() and it works fine. Well, I recently did an assignment for class where I did...

if (size(my_string) < 5)
    store[counter].setWeight(stoi(my_string));

Instead of....

if (my_string.size() < 5)
    store[counter].setWeight(stoi(my_string));

But to my suprise my instructor, who I believe is running an older compiler, wasn't able to run that line of code. On my compiler it works both ways and I'm not quite sure why.

A complete program (it outputs 4 for both):

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string myvar = "1000";
    cout << "Using size(myvar) = " << size(myvar) << endl;
    cout << "Using myvar.size() = " << myvar.size() << endl;
}

If anyone can shed some light on why my solution to the problem worked on my Machine but not my Professors? Also, I'm currently running VS2015.


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/33442629/does-c-have-a-free-function-sizeobject

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