How should I define a std::function variable with default arguments?

To set a std::function variable to a lambda function with default argument I can use auto as in:

auto foo = [](int x = 10){cout << x << endl;};
foo();

This will print 10.

But I want the foo variable to reside in a struct. In a struct I cannot use auto.

struct Bar
{
    auto foo = [](int x = 10}(cout << x << endl}; //error: non-static data member declared ‘auto’
};
Bar bar;
bar.foo();

Replacing auto with std::function

struct Bar
{
    std::function<void(int x = 10)> foo = [](int x = 10}(cout << x << endl}; //error: default arguments are only permitted for function parameters
};
Bar bar;
bar.foo();

or

struct Bar
{
    std::function<void(int)> foo = [](int x = 10}(cout << x << endl};
};
Bar bar;
bar.foo(); //error: no match for call to ‘(std::function<void(int)>) ()’

Without the struct and replacing auto for std::function:

std::function<void(int x)> foo = [](int x = 10){cout << x << endl;};
foo(); //error: no match for call to ‘(std::function<void(int)>) ()’

So how should I declare foo?

The signature in std::function is based on how you plan to call it and not on how you construct/assign it. Since you want to call it two different ways, you'll need to store to different std::function objects, as in:

struct Call
{
    template<typename F>
    explicit Call(F f) : zero_(f), one_(std::move(f)) {}

    void operator()() { zero_(); }
    void operator()(int i) { one_(i); }

    std::function<void()>    zero_;
    std::function<void(int)> one_;
};

Alternatively, you can do the type erasure yourself (what std::function does behind the scenes) to only store the lambda once, as in:

class TECall
{
    struct Concept
    {   
        Concept() = default;
        Concept(Concept const&) = default;
        virtual ~Concept() = default;

        virtual Concept* clone() const = 0;

        virtual void operator()() = 0;
        virtual void operator()(int) = 0;
    };  

    template<typename T>
    struct Model final : Concept
    {   
        explicit Model(T t) : data(std::move(t)) {}
        Model* clone() const override { return new Model(*this); }

        void operator()() override { data(); }
        void operator()(int i) override { data(i); }

        T data;
    };  

    std::unique_ptr<Concept> object;

public:
    template<typename F>
    TECall(F f) : object(new Model<F>(std::move(f))) {}

    TECall(TECall const& that) : object(that.object ? that.object->clone() : nullptr) {}
    TECall(TECall&& that) = default;
    TECall& operator=(TECall that) { object = std::move(that.object); return *this; }

    void operator()() { (*object)(); }
    void operator()(int i) { (*object)(i); }
};

Default arguments - cppreference.com, std::greater in C++ with Examples � Top 10 Programming Languages A default argument is a value provided in a function declaration that is using namespace std; Default arguments are overwritten when calling function provides definition is invalid as subsequent argument of default variable z is� Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target-- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

Don't know if that will help you, but you can store a lambda in a templated struct.

template <typename F>
struct Bar {
  F foo;
  Bar (F fun): foo (std::move (fun)) {}
};

auto f = [](int x = 10) {cout << x << endl;};
Bar<decltype (f)> bar (f);
bar.foo();

auto makeFun = [](){return [](int x = 10) {cout << x << endl;};};

Bar<decltype (makeFun())> bar2 (makeFun());
bar2.foo();

Default Arguments in C++, In this tutorial, we will learn C++ default arguments and their working with the help of examples. We can provide default values for the function parameters in C++. C++ Variables and Literals � C++ Data Types � C++ Basic I/O � C++ Type #include <iostream> using namespace std; // defining the default arguments void � In Python, there are other ways to define a function that can take variable number of arguments. Three different forms of this type are described below. Python Default Arguments. Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.

One way you could solve this would be to wrap your std::function in a functor object which implements the default arguments for you:

struct MyFunc
{
    void operator()(int x = 10) { f(x); }
    std::function<void(int x)> f;
};

struct Bar
{
    MyFunc foo = {[](int x){std::cout << x << "\n";}};
};

int main() {
    Bar bar;
    bar.foo();
}

C++ Programming Default Arguments (Parameters), Default arguments are an excellent option when the function needs a value that the void openLogFile(std::string filename="default.log"); and a function definition, the default argument can be declared in either the forward Default parameters must be compile-time constants, and deck is a variable. Well, if you can use RTTI, you can define a MultiFuncObject like this, and you can easily bind other functions. Also, you can easily call them. But unfortunately, this approach only works for a limited number of arguments. But actually boost::bind also supports limited number of arguments (by default 9). So you can extend this class to satisfy

In C++20 you will be able to do this:

struct foo {
    decltype([](int a = 10){std::cout << a << '\n';}) my_lambda{};
};

int main() {
    foo f;
    f.my_lambda();
    f.my_lambda(5);
}
Live on Godbolt

It does look a bit strange, but it works just fine.

What makes this possible is the ability to use lambdas in unevaluated contexts and default construct stateless lambdas.

7.7 — Default arguments, In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C to the standard output std::cout (typically the screen ). In the first call, there is only one required argument and the rest arguments use the default values. In the second call, lastname and standard arguments value is replaced from default value to new passing value. We can see order of arguments is important from 2nd, 3rd, and 4th call of function. Example #2: Calling functions with keyword arguments

Default argument, Default parameters are a useful tool to make code more expressive. cost of this is to make the definition of the class visible from the function declaration. std:: cout << sum(10) << '\n'; // usage that relies on the default value. Assume that the std::function stores some object with a operator() const, but it also has some mutable data members which it modifies (how rude!). In the std::function<> const& case, the mutable data members modified will propagate out of the function call. In the std::function<> case, they won't. This is a relatively strange corner case.

Default Parameters in C++: The Facts (Including Secret Ones , Default arguments are only allowed in function declarations, and are not If a friend declaration specifies a default, it must be a friend function definition, and error: default argument already } // specified in class scope void C::g(int i = 88, void f() { int n = 1; extern void g(int x = n); // error: local variable cannot be a default }. For a member function of a non-template class, the default arguments are allowed on the out-of-class definition, and are combined with the default arguments provided by the declaration inside the class body. If these out-of-class defaults would turn a member function into a default, copy, or move constructor the program is ill-formed.

Default arguments, The default arguments are used when you provide no arguments or only few For example, lets say you have a user-defined function sum declared like this: int #include <iostream> using namespace std; int sum(int a, int b=10, int c=20); C++ Tutorial � First C++ Program � C++ Variables � C++ Data types � C++ Operators� By default a PHP function uses $_GET variables. Sometimes this function should be called in an situation where $_GET is not set. In this case I will define the needed variables as parameter like:

Comments
  • There is no way to make an std::function with default arguments.