我将以下内容放入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");
}并得到了这些错误:
prog.cpp:在函数‘int()’中: prog.cpp:18:错误:“_1”未在此范围内声明 prog.cpp:19:错误:对“(A)(Const 3)”的调用没有匹配 prog.cpp:18:警告:未使用变量f
我一辈子都找不出18号线上出了什么问题。
发布于 2012-06-28 18:42:53
两个错误:
_1是在命名空间std::tr1::placeholders中定义的。您需要在main(),中使用using namespace std::tr1::placeholders; 或使用std::tr1::placeholders::_1。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"); // <---------
}发布于 2012-06-28 18:43:18
获得prog.cpp:18: error: ‘_1’ was not declared in this scope是因为_1位于名称空间std::tr1::placeholders中,因此需要使用std::tr1::placeholders::_1或using namespace std::tr1::placeholders。
prog.cpp:19: error: no match for call to ‘(A)(const char [3])’来自于这样一个事实:您试图在应该是f("Hi")的时候调用a("Hi")
固定码编译得很好。
https://stackoverflow.com/questions/11250900
复制相似问题