Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function with default parameter value as template parameter

Tags:

c++

templates

I am a bit puzzled with the following behavior. I pass a function with two parameter, one having a default value, as a template parameter and call the function with one argument. Why does it fail to compile? And, what is the solution/workaround?

#include <iostream>
using namespace std;

template<typename Function> 
void eval(Function function) {
    function(10);
}

void sum(int i, int j = 0) {
    cout << "Sum is " << i + j;
}

int main() {
    sum(10);    // OK, of course :)
    eval(sum);  // Error!
}

Note that this question is not about calling a templated function with default parameter.

The error message:

prog.cpp: In instantiation of 'void eval(Function) [with Function = void (*)(int, int)]':
prog.cpp:15:10:   required from here
prog.cpp:6:10: error: too few arguments to function
  function(10);
          ^
like image 769
Eissa N. Avatar asked May 19 '16 05:05

Eissa N.


People also ask

Can template parameters have default values?

Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char.

Can default argument be used with the template class?

Can default arguments be used with the template class? Explanation: The template class can use default arguments.

Can we pass Nontype parameters to templates?

Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.

Which case default argument passing in function is not allowed?

Default arguments are only allowed in the parameter lists of function declarations and lambda-expressions, (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarations.


1 Answers

That's because the optional parameter is part of function declaration. When you call using a function pointer, essentially all the compiler knows is the type of the function pointer. So this line function(10) roughly translates to:

void (*)(int, int) sm = function; // the equivalent happens at the type deduction step 
sm(10); // whoops, where is the second int

The compiler will need the second argument because it has no way of knowing whether sm is pointing to sum which has a default argument, or some other void foo(int a, int b) which doesn't have a default argument.

like image 136
bashrc Avatar answered Oct 09 '22 09:10

bashrc