Artur Pyszczuk
Artur Pyszczuk

Reputation: 1930

Pointer to function with default arguments

Lets assume that we have a function

int foo (std::string, size_t = 0) { return 42; }

and I would like to call this function using wrapper function

template <typename T>
auto boo (std::string s) {
    return (*T::value) (s);
}

So, T should contain a pointer to appropriate function, so I declare it like this

struct Foo : std::integral_constant<int (*) (std::string, size_t), &foo> {};

and now the usage looks like this

std::cout << boo<Foo> ("b") << "\n"; // 42

On GCC 5.3.1 this code compiles fine but on GCC 6.3.1 and GCC 7.2.1 this fails to compile with an error

error: too few arguments to function

As far as I am concerned if I use a pointer to a function without wrapper template function

using Ptr = int (*) (std::string, size_t);
Ptr p = &foo;
auto x = p ("10");

then the error is present in all mentioned versions of GCC.

According to the latter example, does it mean that I can not use a pointer without explicitly specifying second argument even though pointed function does not need it?

According to the main example does it mean that GCC 5.3.1 incorrectly implements this behavior in connection with template wrapper?

Upvotes: 0

Views: 115

Answers (1)

Sneftel
Sneftel

Reputation: 41464

It's fine to use a function with default arguments using any of its possible signatures, but you've introduced an inconsistency yourself. You've specifically defined Foo as wrapping a pointer to a two-argument function, so you'd better call it with two arguments. If you want to call it with one argument, use it as a pointer to a one-argument function.

I'm not sure what you're trying to accomplish with integral_constant.

Upvotes: 1

Related Questions