【问题标题】:tr1::function and tr1::bindtr1::function 和 tr1::bind
【发布时间】:2012-06-28 18:38:53
【问题描述】:

我将以下内容放入 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 main()”中:

prog.cpp:18: 错误:'_1' 未在此范围内声明

prog.cpp:19: error: no match for call to ‘(A)(const char [3])’

prog.cpp:18:警告:未使用的变量“f”

我终其一生都无法弄清楚第 18 行出了什么问题。

【问题讨论】:

  • 试试std::tr1::placeholders::_1
  • 那里也需要一个 tr1::。我想我最近才使 tr1 占位符和 c++11 占位符相互兼容
  • @JonathanWakely,哎呀,从未使用过 tr1 的。我忘了。

标签: c++ tr1


【解决方案1】:

两个错误:

  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");    // <---------
}

【讨论】:

  • 强调 within main().
【解决方案2】:

你得到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])’ 来自于您尝试调用 a("Hi") 而应该是 f("Hi")

fixed code 编译得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多