Ensure that std :: container :: size_type is std :: size_t

Following this question , I decided to use std::size_t as size_type for each container with obvious readability considerations. I know that it is theoretically possible that std::container<T>::size_type not std::size_t , but I assume this does not apply to my current and future configurations.

However, to avoid evil bugs, I check that the types are the same when I use them. For instance:

 BOOST_STATIC_ASSERT(boost::is_same< std::vector<double>::size_type , std::size_t >::value); std::vector<double> x; /* fill x */ for(std::size_t i = 0; i < x.size(); ++i) { /* do something */ } 

Another place in the code, I use std::vector<long int> , then also check:

 BOOST_STATIC_ASSERT(boost::is_same< std::vector<long int>::size_type , std::size_t >::value); 

And then, oh no! I use std::vector<std::list<std::string>*> and std::vector<std::list<double*>*> , then I check:

 BOOST_STATIC_ASSERT(boost::is_same< std::vector<std::list<std::string>*>::size_type , std::size_t >::value); BOOST_STATIC_ASSERT(boost::is_same< std::vector<std::list<double*>*>::size_type , std::size_t >::value); 

Well, I think you understand the problem. Ugly lines, hard to maintain code. It is a bad idea.

Then my question is: If I check std::vector<any_common_type>::size_type for std::size_t , is there any chance that std::vector<another_type>::size_type NOT std::size_t ? Is it enough to check some common types in a separate file to make sure that std::container::size_type always std::size_t in my compiler?

Note. I do not use C ++ 11 for compatibility reasons.

+5
source share
1 answer

The approach you follow in your question seems to be the way to go if you really need to do this.

However, I think you are too worried, as size_t can handle size_type .

If you ever find yourself in an unlikely situation where the platform implements size_t so that it is not large enough to contain all the size_type values, then I'm sure you will get a compiler warning for any comparison that you try to perform.

'size_t' vs 'container :: size_type' mentions:

Standard containers define size_type as a typedef for Allocator :: size_type (Allocator is a template parameter), which for std :: allocator is usually defined as size_t (or a compatible type). Therefore, for the standard case, they are the same.


So, if I were you, I would be sure that my compiler would lie in a typical case. However, if I used non-standard containers, I would have bothered to follow you - as you said, an ugly approach, put it in a file and let it do its job in a hidden dark corner.

+4
source

Source: https://habr.com/ru/post/1271596/


All Articles