Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is there a way to use an unspecified parameter in c++?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading