Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tr1::function and tr1::bind

Tags:

c++

tr1

I put the following into Ideone.com (and codepad.org):

#include <iostream>
#include <string>
#include <tr1/functional>
 
struct A {
    A(const std::string& n) : name_(n) {}
    void printit(const std::string& s) 
    {
        std::cout << name_ << " says " << s << std::endl;
    }
private:
    const std::string name_;
};
 
int main()
{
    A a("Joe");
    std::tr1::function<void(const std::string&)> f = std::tr1::bind(&A::printit, &a, _1);
    a("Hi");
}

And got these errors:

prog.cpp: In function ‘int main()’:

prog.cpp:18: error: ‘_1’ was not declared in this scope

prog.cpp:19: error: no match for call to ‘(A)(const char [3])’

prog.cpp:18: warning: unused variable ‘f’

I can't for the life of me figure out what's wrong on line 18.

like image 640
John Avatar asked Sep 25 '26 07:09

John


1 Answers

Two errors:

  1. _1 is defined within the namespace std::tr1::placeholders. You need to either using namespace std::tr1::placeholders; within main(), or use std::tr1::placeholders::_1.

  2. Line 19 should be f("Hi"), not a("Hi").

#include <iostream>
#include <string>
#include <tr1/functional>

struct A {
    A(const std::string& n) : name_(n) {}
    void printit(const std::string& s) 
    {
        std::cout << name_ << " says " << s << std::endl;
    }
private:
    const std::string name_;
};

int main()
{
    using namespace std::tr1::placeholders;  // <-------

    A a("Joe");
    std::tr1::function<void(const std::string&)> f = std::tr1::bind(&A::printit, &a, _1);
    f("Hi");    // <---------
}
like image 88
kennytm Avatar answered Sep 28 '26 06:09

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!