Can someone please explain the use of companion types in C++? I've gathered that they're meant to improve genericity, but can someone please explain, for example, why defining "len = line.size()" as size_type is preferable to giving it type "int"?
For one thing, sizes aren't negative, so it should at least be unsignedint
Also, the size of whatever you're examining might be bigger than the largest int, and the result will be trouble.
That said, it's fairly common to just use std::size_t rather than std::string::size_type or whatever your line is - I only know of one library where size_type can be potentially larger than size_t, and it's of questionable standard conformance.
size_type would not be int, in that case. Case in point:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
#include <limits>
int main()
{
std::cout << "Largest int: " << std::numeric_limits<int>::max() << '\n'
<< "Largest string::size_type: " << std::numeric_limits<std::string::size_type>::max() << '\n';
std::string line(3000000000, ' '); // that's 3,000,000,000 spaces
int len = line.size();
std::cout << "The size of my string is " << line.size()
<< " but I used 'int' and now I think the size is really " << len << '\n';
}
when I run this, I get
Largest int: 2147483647
Largest string::size_type: 18446744073709551615
The size of my string is 3000000000 but I used 'int' and now I think the size is really -1294967296