我将以下内容放入Ideone.com(和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");
}
Run Code Online (Sandbox Code Playgroud)
并得到这些错误:
prog.cpp:在函数'int main()'中:
prog.cpp:18:错误:在此范围内未声明'_1'
prog.cpp:19:错误:调用'(A)(const char [3])'不匹配
prog.cpp:18:警告:未使用的变量'f'
我不能为我的生活找出第18行的错误.
两个错误:
_1在命名空间中定义std::tr1::placeholders.您需要在using namespace std::tr1::placeholders; 内部main()或使用std::tr1::placeholders::_1.
第19行应该是f("Hi"),而不是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"); // <---------
}
Run Code Online (Sandbox Code Playgroud)