tr1 :: function和tr1 :: bind

Joh*_*ohn 3 c++ tr1

我将以下内容放入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行的错误.

ken*_*ytm 7

两个错误:

  1. _1在命名空间中定义std::tr1::placeholders.您需要在using namespace std::tr1::placeholders; 内部main()或使用std::tr1::placeholders::_1.

  2. 第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)


Gri*_*zly 5

你得到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])’来自你a("Hi")应该在应该的时候打电话的事实f("Hi")

固定代码编译就好了.