首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TR1:函数和tr1::bind

TR1:函数和tr1::bind
EN

Stack Overflow用户
提问于 2012-06-28 18:38:53
回答 2查看 8.6K关注 0票数 3

我将以下内容放入Ideone.com (和codepad.org)中:

代码语言:javascript
复制
#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号线上出了什么问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-28 18:42:53

两个错误:

  1. _1是在命名空间std::tr1::placeholders中定义的。您需要在main(),中使用using namespace std::tr1::placeholders; 或使用std::tr1::placeholders::_1
  2. 第19行应该是f("Hi"),而不是a("Hi")
代码语言:javascript
复制
#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");    // <---------
}
票数 7
EN

Stack Overflow用户

发布于 2012-06-28 18:43:18

获得prog.cpp:18: error: ‘_1’ was not declared in this scope是因为_1位于名称空间std::tr1::placeholders中,因此需要使用std::tr1::placeholders::_1using namespace std::tr1::placeholders

prog.cpp:19: error: no match for call to ‘(A)(const char [3])’来自于这样一个事实:您试图在应该是f("Hi")的时候调用a("Hi")

固定码编译得很好。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11250900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档