I was thinking to be more pedantic in choosing data type in a block of code where I would need to choose between size_typesize_t in general or container::size_type for container types. My problem is that if I have the following block of code, I don't know how to do it. Can anybody there help?
template<typename some_container>
int func(some_container& input)
{
//Some code...
//...
decltype(input.size()) variable_x; //Choose this if defined,
size_t variable_x; //otherwise choose this
//... Some more code...
}
In this case some_container may be a custom container and does not provide size() function. What led me to this thinking was reading the difference between size_t and container::size_type at size_t vs container::size_type. I also read Determine if a type is an STL container at compile time, but the approach feels a bit heavy-handed for my situation.
Following is one way to determine if a
classcontains a type (e.g.size_type) or not:And following is the way to choose between 2 types:
Edit start: Here is another simpler approach:
Edit end.
So finally, use as below:
So now
typeis eithersize_typeorsome_container::size_type, if it has that.