Placeholder Syntax
Let's learn about placeholder syntax in this lesson.
We'll cover the following
With auto
, C++11 has unconstrained placeholders. We can use concepts in C++20 as constrained placeholders. Decisive quantum leap does not look so thrilling at the first glimpse. C++ templates will become easy to use C++ features.
According to our definition, C++98 is not a consistent language. By consistent, we mean that you have to apply a few rules to derived C++ syntax from it. C++11 is something in between. For example, we have consistent rules like initializing all with curly braces (see { } - Initialization). Of course, even C++14 has a lot of features where we miss a consistent principle. One of the favorites is the generalized lambda function.
Placeholder Syntax: auto
auto genLambdaFunction= [](auto a, auto b) {
return a < b;
};
template <typename T, typename T2> // 3
auto genFunction(T a, T2 b){ // 4
return a < b;
}
Inconsistency in C++14
By using the placeholder auto
for the parameter a
and b
, the generalized lambda function becomes - in a magic way - a function template. We know, genLambdaFunction
is a function object that has an overloaded call operator which accepts two type parameters. The genFunction
is also a function template. But wouldn’t it be nice to define a function template by just using auto
in a function definition? This would be consistent but is not possible. Hence, we have to use a lot more syntax (line 3 and 4). That syntax is often too difficult for a lot of C++ programmer.
Exactly that inconsistency will be removed with the placeholder syntax. Therefore, we have a new simple principle and C++ will become - according to my definition - a lot easier to use.
Generic Lambdas introduced a new way to define templates.
Constrained and Unconstrained Placeholders
We will get unconstrained and constrained placeholders. auto
is an unconstrained placeholder because a
with auto
defined variable can be of any type. A concept
is a constrained placeholder because it can only be used to define a variable that satisfies the concept
.
General Rule: Constrained Concepts can be used where unconstrained templates (
auto
) are usable.
Let’s define and use a simple concept
before we dig into the details.
Example:
Get hands-on with 1400+ tech skills courses.