cpp
cpp

Reputation: 3801

Using binder1st with custom functor

I'd like to bind the first argument of my print functor to 0:

#include<iostream>
#include<functional>
using namespace std;

class Print : public std::binary_function<int,int,void>{
public:
    void operator()(int val1, int val2)
    {   
        cout << val1 + val2 << endl;
    }   
};

int main()
{
    Print print;
    binder1st(print,0) f; //this is line 16
    f(3);  //should print 3
}

The program above (based on an example from C++ Primer Plus) does not compile:

line16 : error : missing template arguments before ‘(’ token

What is wrong?

I don't want to use C++11 nor boost features.

Edited: operator() return type has been changed from bool to void for simplicity

Upvotes: 1

Views: 258

Answers (3)

juanchopanza
juanchopanza

Reputation: 227390

std::binder1st is a class template, so it needs a template parameter.

binder1st<Print> f(print,0);
//       ^^^^^^^

But if you really want to bind the second argument, then you need to use the aptly named std::binder2nd.

Upvotes: 2

bash.d
bash.d

Reputation: 13207

binder1st needs template-arguments, try

 binder1st<Print> f(print, 0);

See the reference here.

Example

#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;

int main () {
  binder1st < equal_to<int> > equal_to_10 (equal_to<int>(),10);
  int numbers[] = {10,20,30,40,50,10};
  int cx;
  cx = count_if (numbers,numbers+6,equal_to_10);
  cout << "There are " << cx << " elements equal to 10.\n";
  return 0;
}

Upvotes: 2

doctorlove
doctorlove

Reputation: 19232

As the error message says, you are missing template arguments before the ( This is what you want

std::binder1st<Print> f(print, 0);

However, you also need to make your operator() const as follows

bool operator()(int val1, int val2) const

Finally, this function needs to return something.

Upvotes: 5

Related Questions