Search⌘ K
AI Features

Discussion: A Constant Struggle

Explore how C++ deduces template arguments in function templates when using by value and by reference parameters. Understand the effect of const qualifiers and how deduction rules treat these, helping you predict function behavior and improve code reliability with template parameters.

Run the code

Now, it’s time to execute the code and observe the output.

C++
#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 ...