Search code examples
c++typestype-members

classes and templates companion types


I'm learning C++ and every now and then I bump into something like "companion types" or some "machine dependent integral type" that is used on different occasions, such as:

vector<int>::size_type

or

std::size_t

or lately I was reading about IO types and objects and I read about a type that is "defined by IO classes" such as:

istream::iostate

that apparently is an integral type used by some kind of bit-patterns used to indicate the state of a stream object.

I know that classes can include (besides member functions and data members) type members, in the form of type alias declarations (typedef and using alias declaration), but it doesn't make sense to me completely, there must be something I haven't read about yet. Can you please explain?

thanks a lot!


Solution

  • If the standard doesn't specify the exact type of something, but rather only it's behavior, it is up to the implementation to decide how they want to handle it.

    For example, say that the standard says that there must be a class Foo that also has a foo_t. This foo_t is required to be able to represent some range of integral values, but it doesn't say that they must be fixed size (like std::int32_t). In my implementation, I could just say

    class Foo
    {
    public:
        using foo_t = long;
    };
    

    Then the users of this class would not need to know the internals that foo_t is actually a long under the hood, nor should they depend on that being true for all compilers (as others may choose to implement it differently). They simply know that foo_t is capable of holding some range of integral values, based on whatever the C++ standard says it should.

    int main()
    {
        Foo::foo_t x = 10;
        std::cout << x;
    }