How can I draw C++ concepts in UML class diagram?

Viewed 491

How would I draw C++ concepts in an UML class diagram?

Specifically, I have the following code:

template<typename T>
concept Printable = requires(T a, std::ostream &where) {
    { where << a };
};

template<typename T>
concept Identifiable = requires(T a) {
    { a.getId() } -> std::convertible_to<std::string>;
};

template<typename T>
concept Listable = Identifiable<T> && Printable<T>;

and then a class:

template<Listable T>
class Liste {
    ...
    void add(T *data);
    ...
}

If it were a regular template, I would just put the T in a square in the corner of the class. But what about the concepts?

1 Answers

The C++ concepts defines constraints on the types associated with a template class:

  • Since UML supports class template, you would typically express this constraints for its parameters, between curly brackets, either in natural language or in OCL. The former is perfect at an early design stage. But you could as well consider to pragmatically express it using the same syntax than C++ instead of natural language, if you need this level of accuracy.

  • Alternatively, you may as well handle the C++ concept as a kind of generic type in UML. You could then use the concept in a much more readable way in the the type definition of the template parameters in class templates. This would be more convenient to read, and closer to the C++ idea. The problem is that nothing is foreseen in UML to define such generic types. You may therefore extend UML with an and-hoc profile to use a «concept» stereotype. You would then define concepts exactly like classes, define the constraints using the UML constraints, and use the concepts in UML class templates.

Here, how the second approach would look like. Note the realization dependency between two concepts:

enter image description here

Related