I’m trying to have a simple function that is used for debugging in my program just for easeability and I’m wondering if there is a way to just not specify the kind of variable without instead overloading it for every kind possible. In my case would it be possible to have var be able to be any type of variable?
void debugPrinter(std::string name, int var )
{
std::cout << name << ": " << var << "\n";
}
>Solution :
Yes, you can make debugPrinter a template.
template <typename T>
void debugPrinter(std::string name, const T & var )
{
std::cout << name << ": " << var << "\n";
}
In C++ 20, that can be abbreviated as
void debugPrinter(std::string name, const auto & var )
{
std::cout << name << ": " << var << "\n";
}
I’ve taken the parameter by const reference, because you don’t need to copy the value to print it.