c++visual-studio-2015c++17non-member-functions

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


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.


Solution

  • 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