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.
Solution
Two errors:
_1
is defined within the namespacestd::tr1::placeholders
. You need to eitherusing namespace std::tr1::placeholders;
withinmain()
, or usestd::tr1::placeholders::_1
.Line 19 should be
f("Hi")
, nota("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.