3 ms·
In essence, they are used to allow template writers to easily put constraints on the type parameters that their templates require, and provide better diagnostic
by svalorzen 11y ago
In essence, they are used to allow template writers to easily put constraints on the type parameters that their templates require, and provide better diagnostics to users of template classes when they try to instantiate a template with the wrong parameters.
Normally when you wrongly instantiate a template you get a block of text which describes exactly what went wrong. In terms of the language as it is now, the whole block is necessary, but the ability to mentally parse it is a skill that requires time and is otherwise relatively useless. In addition, for library users, errors could happen way inside the internals of the library, and the users would have little to no information as on how to parse such errors.
To try to mitigate this, type traits were introduced. These are used by template writers, and their task is to check that template parameters satisfy certain given requirements or else a certain overload is discarded (using SFINAE for example). In this way, errors would be caught before trying to actually instantiate a template, and users would not be exposed to errors within the internals, but just at a boundary when a template was being instantiated. But still this approach has limitations, and the errors are still not quite pretty.
Concepts tries to fix all this with an approach that resembles java's "implements". It provides a way to easily specify and check at compile time the interface required by template parameters, so that it can be checked before instantiating the template and give better errors in terms of the concept rather than type traits features.