[英]tr1::function and tr1::bind
I put the following into Ideone.com (and codepad.org): 我将以下内容放入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");
}
And got these errors: 并得到这些错误:
prog.cpp: In function 'int main()': prog.cpp:在函数'int main()'中:
prog.cpp:18: error: '_1' was not declared in this scope prog.cpp:18:错误:在此范围内未声明'_1'
prog.cpp:19: error: no match for call to '(A)(const char [3])' prog.cpp:19:错误:调用'(A)(const char [3])'不匹配
prog.cpp:18: warning: unused variable 'f' prog.cpp:18:警告:未使用的变量'f'
I can't for the life of me figure out what's wrong on line 18. 我不能为我的生活找出第18行的错误。
Two errors: 两个错误:
_1
is defined within the namespace std::tr1::placeholders
. _1
在命名空间std::tr1::placeholders
。 You need to either using namespace std::tr1::placeholders;
你需要using namespace std::tr1::placeholders;
within main()
, or use std::tr1::placeholders::_1
. 在main()
,或使用std::tr1::placeholders::_1
。
Line 19 should be f("Hi")
, not a("Hi")
. 第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"); // <---------
}
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 use std::tr1::placeholders::_1
or a using namespace std::tr1::placeholders
. 你得到prog.cpp:18: error: '_1' was not declared in this scope
因为_1
在命名空间std::tr1::placeholders
,所以你需要使用std::tr1::placeholders::_1
或者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")
prog.cpp:19: error: no match for call to '(A)(const char [3])'
来自于你应该调用a("Hi")
它应该是f("Hi")
的事实
The fixed code compiles just fine. 固定代码编译得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.