Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ function type and callable object

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading