Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a Boost.Bind function be called with extra parameters?

#include <iostream>
#include <string>

#include <boost/bind.hpp>

void foo(std::string const& dummy)
{
    std::cout << "Yo: " << dummy << std::endl;
}

int main()
{
    int* test;
    std::string bar("platypus");
    (boost::bind(&foo, bar))(test, test, test, test, test, test, test, test);
}

When run, it prints out, "Yo: platypus." It appears to completely ignore extra parameters. I'd expect to get a compile error. I accidentally introduced a bug into my code this way.

like image 906
Joseph Garvin Avatar asked Jul 23 '10 18:07

Joseph Garvin


People also ask

What is the use of boost bind function?

These placeholders tell boost::bind() to return a function object that expects as many parameters as the placeholder with the greatest number. If, as in Example 41.3, only the placeholder _1 is used, boost::bind() returns an unary function object – a function object that expects a sole parameter.

What is a function pointer in boost?

Using boost::function boost::function makes it possible to define a pointer to a function with a specific signature. Example 40.1 defines a pointer f that can point to functions that expect a parameter of type const char* and return a value of type int. Once defined, functions with matching signatures can be assigned to the pointer.

How do you bind a function with parameters?

Below syntax bind function with parameters. . This is because a member function has access to class data and if not called from an instance any access to class data would result in undefined behaviour. . To bind arguments, use placeholder.

What is boost function in C++?

Boost.Function Boost.Function provides a class called boost::function to encapsulate function pointers. It is defined in boost/function.hpp. If you work in a development environment supporting C++11, you have access to the class std::function from the header file functional.


1 Answers

I don't know why this is allowed, but I do know it is expected behavior. From here:

bind can handle functions with more than two arguments, and its argument substitution mechanism is more general:

bind(f, _2, _1)(x, y);                 // f(y, x)
bind(g, _1, 9, _1)(x);                 // g(x, 9, x)
bind(g, _3, _3, _3)(x, y, z);          // g(z, z, z)
bind(g, _1, _1, _1)(x, y, z);          // g(x, x, x)

Note that, in the last example, the function object produced by bind(g, _1, _1, _1) does not contain references to any arguments beyond the first, but it can still be used with more than one argument. Any extra arguments are silently ignored (emphasis mine), just like the first and the second argument are ignored in the third example.

like image 112
SCFrench Avatar answered Nov 12 '22 23:11

SCFrench