C ++有一个自由函数`size(object)`? [英] Does C++ have a free function `size(object)`?
问题描述
看来,大多数人发现字符串
的大小是他们只是使用 my_string.size()
和它工作正常。好,我最近做了一个类的任务,我做了...
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));
而不是....
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.
一个完整的程序(它输出4两者):
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;
}
如果任何人可以说明为什么我的问题的解决方案在我的机器,但不是我的教授?此外,我目前正在运行VS2015。
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.
推荐答案
MSVS 2015有在xutility中定义的函数
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());
}
这是调用
cout << "Using size(myvar) = " << size(myvar) << endl;
这不是标准的C ++ 11/14函数,不会在gcc 或 clang
This is not a standard C++11/14 function and will not run on gcc or clang
这在博客文章在VS 2015 RTM中的C ++ 11/14/17功能
这篇关于C ++有一个自由函数`size(object)`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!