Jump to content

Concept (generic programming)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 210.118.108.254 (talk) at 07:04, 24 March 2009 (See also). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In generic programming, a concept is a description of supported operations on a type, including syntax and semantics. In this way, concepts are related to abstract base classes but concepts do not require a subtype relationship. The term was in use as early as 1998 for STL[1], as this was one of the first libraries that extensively used templates.

For example, if a type I satisfies the Trivial Iterator concept in C++, and i is of type I, the following are valid expressions with corresponding semantics:[2]

  • I i default construction.
  • *i must be convertible to some type T.
  • i->m is valid if (*i).m is.

Primarily (in C++ 1998 standard), the Concept term was introduce to name just a simple description of the requirements for particular type, usually being a template parameter. It was never encoded in the language explicitly - the concept was expressed only by what operations are tried to be performed on objects of that type and what is expected to work (that is, to compile correctly).

However, for the next revision of C++ standard, there is proposed the feature named Concepts, which are this time requirements explicitly encoded in the language. Comparing to "implicit Concepts" they are better because:

  • they help getting more readable error messages (comparing to very long and complicated messages based on non-fulfilled requirements)
  • you can overload templates basing on concepts

As generics in Java and C# have some similarities to C++'s templates, the role of concepts there is played by interfaces. However there is one important difference between concepts and interfaces: when a template parameter is required to implement a particular interface, the matching type can only be a class that implements (explicitly) that interface. Concepts bring more flexibility because they can be satisfied by two ways:

  • explicitly defined as satisfied by using a concept map (defined separately to the type itself, unlike interfaces)
  • implicitly defined for "auto concepts", which can be used also for builtin types and other types that were not predestined for this use

See also

testing it

References

  1. ^ Austern, M.H. Generic programming and the STL: using and extending the C++ Standard Template Library. 1998. pp 17–18
  2. ^ Trivial Iterator