Grant Schulte
Grant Schulte

Reputation: 153

How do I create a function in C++ that has multiple parameters but only one is required?

I have a function takes two "optional" parameters, but the logic of the function expects that at least one be specified. If a is provided, then a is used. If b is provided, then b is used. If neither parameter is provided, then an exception is thrown because this function needs at least one of the parameters to be given to be able to run successfully. See the code snippet for an example:

void print_it(A* a = nullptr, B* b = nullptr)
{
    std::cout << "The parameter provided was ";
    if (a != nullptr)
    {
        std::cout << a->print();
    }
    else if (b != nullptr)
    {
        std::cout << b->print();
    }
    else
    {
        throw std::invalid_argument();
    }
}

I'd say it's bad practice to have a function like this that crashes during runtime when its default form is called instead of using type-safety and having the compiler check for errors.

How do I change this function signature to require that one of the values be provided with minimal code duplication?

Upvotes: 0

Views: 1053

Answers (1)

user15401571
user15401571

Reputation:

You can overload this like so:

void print_it(A a, B b)
{
//use a and b
}

void print_it(A a) {
//use a
}
void print_it(B b) {
//use b
}

Or, you can use std::optional like explained here: https://en.cppreference.com/w/cpp/utility/optional. Example:

void print_it(std::optional<A> a, std::optional<B> b)
{
    if (a.has_value()) {
        //use a
    }
    if (b.has_value()){
        //use b
    }
    else {
        throw std::invalid_argument();
    }
}

Upvotes: 5

Related Questions