Chris Bigart
Chris Bigart

Reputation: 51

C++(11) Default arguments for functions as template parameters, or as function pointers

Basically, I want a function pointer to be able to be called with default arguments. Take a look at the following:

#include <iostream>
using namespace std;

int function(int arg1 = 23)
    {
        printf("function called, arg1: %d\n", arg1);
        return arg1 * 3;
    }

template<typename Fn> int func(Fn f)
{
    int v = 3;
    f(); //error here 'error: too few arguments to function'
    f(23); //this compiles just fine
    return v;
}


int main() {
    func(&function);
    printf("test\n");
    return 0;
}

Is there any way (trickery or otherwise) to be able to call a function with default arguments from a function pointer (or a template argument) without specifying the argument explicitly?

Upvotes: 0

Views: 183

Answers (2)

Devesh Agrawal
Devesh Agrawal

Reputation: 9212

Yes There is a Good way. Function Object. I highly recommend you to see this link.

http://www.stanford.edu/class/cs106l/course-reader/Ch13_Functors.pdf

Upvotes: 2

jrok
jrok

Reputation: 55395

With std::bind. It returns a function object that calls the function with arguments that you passed to bind expression:

auto f = std::bind(&function, 23);
func(f);

Upvotes: 1

Related Questions