Question

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.

Was it helpful?

Solution

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");    // <---------
}

OTHER TIPS

You get prog.cpp:18: error: ‘_1’ was not declared in this scope because _1 is in the namespace std::tr1::placeholders, so you need to usestd::tr1::placeholders::_1 or a using namespace std::tr1::placeholders.

prog.cpp:19: error: no match for call to ‘(A)(const char [3])’ comes from the fact that you try to call a("Hi") when it should be f("Hi")

The fixed code compiles just fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top