Discussion: A Constant Struggle
Execute the code to understand the output and gain insights into template argument deduction.
We'll cover the following...
Run the code
Now, it’s time to execute the code and observe the output.
Press + to interact
#include <iostream>#include <type_traits>template <typename T>void byValue(T t){std::cout << std::is_const_v<T>; // true if T is const}template <typename T>void byReference(T &t){std::cout << std::is_const_v<T>; // true if T is const}int main(){int nonConstInt = 0;const int constInt = 0;byValue(nonConstInt);byValue(constInt);byReference(nonConstInt);byReference(constInt);}
Understanding the output
The two function templates byValue
and byReference
take their parameters by value and by reference, respectively. We then call these two function templates with a non-const
and a const int
as arguments. In which cases is T
deduced as const
?
Template parameter
Before we start digging into the deduction rules, let’s clarify two concepts that can be easily mixed up. The T
in template <typename T>
is called the template parameter. The goal of template argument deduction is to find T
. On the other hand, the T
and T &
in the function signatures byValue(T
...