I have a class that holds an array of elements, and I want to give it a GetSize member function. But what return type should I give that function?
I’m using the pimpl idiom, and so in the header file it is not known what the implementation will use to store the elements. So I cannot just say std::vector<T>::size_type, for example:
class FooImpl;
class Foo {
FooImpl* impl_;
public:
TYPE GetSize(); // what TYPE??
};
If the client code can only see
Foo(which is the purpose of pimpl idiom), then there’s no use in define a specificsize_typein the concrete implementation – it won’t be visible/accessible to the client anyway. Standard containers can do that since they are built on so called “compile-time polymorphism”, while you are specifically trying to use a [potentially] run-time implementation hiding method.In your situation the only choice would be to choose an integer type that “should be enough for all possible implementations” (like
unsigned long, for example) and stick with it.Another possibility is to use the
uintptr_ttype, if it is available in your implementation (it is standardized in C99, but not in C++). This integer type is supposed to cover the entire storage address range available to the program, which means that it will always be sufficient for representing the size of any in-memory container. Note, that other posters often use the same logic, but incorrectly arrive at the conclusion that the appropriate type to use here issize_t. (This is usually a result of lack of experience with non-flat memory model implementatioons.) If your containers are always based on physical arrays,size_twill work. However, if your containers are not always array-based,size_tis not even remotely the correct type to use here, since its range is generally smaller than the maximum size of a non-continuous (non-array-based) container.But in any case, regardelss of what size you are end up using, it is a good idea to hide it behind a typedef-name, just like it is done in standard containers.