Does C++ have a free function `size(object)`?(C++ 有免费的函数`size(object)`吗?)
问题描述
似乎大多数人找到 string 大小的方式是他们只使用 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 中定义了一个 size 函数
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;
这不是标准的 C++11/14 函数,不会在 gcc 上运行a> 或 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)`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 有免费的函数`size(object)`吗?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
