Rick C. Hodgin
Rick C. Hodgin

Reputation: 503

Visual C++ function call explicit / implicit parameter count

// Function prototype with default parameters
void func(int p1, int p2 = 0, int p3 = 0);

// Function body
void func(int p1, int p2, int p3)
{
    printf("The # of explicit parameters is %d\n", ??);
    printf("The # of implicit parameters is %d\n", ??);
}

// Use in code
int main(int argc, char* argv[])
{
    func(0);        // Should print 1 explicit, 2 implicit
    func(0, 0);     // Should print 2 explicit, 1 implicit
    func(0, 0, 0);  // Should print 3 explicit, 0 implicit

    return 0;
}

In the above example, how can I get the actual number of parameters passed in explicitly? And the number of parameters passed in implicitly?

Upvotes: 1

Views: 165

Answers (1)

Alex Guteniev
Alex Guteniev

Reputation: 13719

As @Igor pointed out in a comment, it is not possible to detect if a parameter is default or actually passed.

One of possible ways to emulate it is to switch from default parameters to overload.

Another is to make the default value distinct from explicit value. It can be done with std::optional if you wouldn't pass empty optional explcitly:

#include <stdio.h>
#include <optional>

void func(std::optional<int> p1 = std::nullopt, std::optional<int> p2 = std::nullopt, std::optional<int> p3 = std::nullopt);

// Function body
void func(std::optional<int> p1, std::optional<int> p2, std::optional<int> p3)
{
    printf("The # of explicit parameters is %d\n", p1.has_value() + p2.has_value() + p3.has_value());
    printf("The # of implicit parameters is %d\n", !p1.has_value() + !p2.has_value() + !p3.has_value());
}

// Use in code
int main(int argc, char* argv[])
{
    func(0);        // Should print 1 explicit, 2 implicit
    func(0, 0);     // Should print 2 explicit, 1 implicit
    func(0, 0, 0);  // Should print 3 explicit, 0 implicit

    return 0;
}

Also it can be emulated with variadic template parameters.

Upvotes: 1

Related Questions