Home > Mobile >  C function type and callable object
C function type and callable object

Time:10-07

I'm trying to assign callable object to function object with conforming call signature. This is my code:

#include <functional>

int add(int i, int j) { return i   j; }

struct div {
    int operator()(int denominator, int divisor) {
        return denominator / divisor;
    }
};

int main() {
    auto mod = [](int i, int j) { return i % j; };

    std::function<int(int, int)> f1 = add;
    std::function<int(int, int)> f2 = div();
    std::function<int(int, int)> f3 = mod;

    return 0;
}

By compiling this I get:

function.cc: In function ‘int main()’:
function.cc:17:43: error: too few arguments to function ‘div_t div(int, int)’
   17 |     std::function<int(int, int)> f2 = div();
      |                                           ^
In file included from /usr/include/c  /9/cstdlib:75,
                 from /usr/include/c  /9/ext/string_conversions.h:41,
                 from /usr/include/c  /9/bits/basic_string.h:6496,
                 from /usr/include/c  /9/string:55,
                 from /usr/include/c  /9/stdexcept:39,
                 from /usr/include/c  /9/array:39,
                 from /usr/include/c  /9/tuple:39,
                 from /usr/include/c  /9/functional:54,
                 from function.cc:1:
/usr/include/stdlib.h:852:14: note: declared here
  852 | extern div_t div (int __numer, int __denom)
      |              ^~~

Why compiler raises too few arguments error in this case?

CodePudding user response:

Including <functional> includes <cstdlib> which brings a function div into your current namespace.

Change your struct div to struct Div and the error goes away.

  •  Tags:  
  • c
  • Related