Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function default parameters are ignored

For this simplified piece of code I'm getting following error:

error: too few arguments to function std::cout << f();

int g(int a = 2, int b = 1)
{
    return a + b;
}

template<class Func>
void generic(Func f)
{
    std::cout << f();
}

int main()
{
    generic(g);
}

I cannot clue the reason for why the default parameters of function f are not passing into a function generic. It behaves like f doesn't have any default parameters ...

What's wrong there?

How do I forward default parameters correctly?

like image 818
ampawd Avatar asked Sep 13 '17 19:09

ampawd


People also ask

Which function Cannot have default parameters?

Constructors cannot have default parameters.

What is the default parameter in a function?

The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

Can all the parameters of a function can be default parameters?

All the parameters of a function can be default parameters.

What are the parameters that are default values?

A parameter with a default value, is often known as an "optional parameter". From the example above, country is an optional parameter and "Norway" is the default value.


1 Answers

g may have default arguments, but the type of &g is still int(*)(int, int), which is not a type that can be called with no arguments. Within generic, we can't differentiate that - we've already lost the context about default arguments.

You can just wrap g in a lambda to preserve the context:

generic([]{ return g(); });
like image 99
Barry Avatar answered Oct 02 '22 12:10

Barry