【问题标题】:g++ 4.8.2: could not convert from function pointer to std::function<>g++ 4.8.2:无法从函数指针转换为 std::function<>
【发布时间】:2015-05-12 01:28:11
【问题描述】:

我正在尝试编写一个类,该类将一个工厂函数作为构造函数参数,该工厂函数在输入的转换版本上创建同一类的另一个实例。举个简单的例子,一个仿函数类,它接受一个 int,打印它,然后返回另一个打印输入后继的仿函数。

我收到表单错误

error: could not convert 'foo' from 'Type(*)(int)' to 'std::function<Type(int)>'

似乎只有工厂函数传入构造函数。

使用函数指针而不是 std::function&lt;&gt; 可以正常工作,但我希望使用 C++11 能够避免使用函数指针。

这是一个例子:

#include <functional>
#include <iostream>

// std::function-returning-int param in ctor with default value
// This works fine

class PrInc; // "print and increment"

using Worker = std::function<int(int)>;

int foo(int i) {
    std::cout << i << std::endl;
    return i+1;
}

class PrInc {
  public:
    PrInc(int i, Worker fn = foo) : i_(i), fn_(fn) {}
    int operator()() { return fn_(i_); }
  private:
    int i_;
    Worker fn_;
};

// std::function-returning-PrInc2 param in ctor with default value
// This fails, at least on g++ 4.8.2 --std=c++11

class PrInc2;

using Factory = std::function<PrInc2(int)>;
// Use function ptrs (instead of std::function<>s) and it works fine
//typedef PrInc2 (*Factory)(int);

PrInc2 bar(int);

class PrInc2 {
  public:
    PrInc2(int i, Factory fn = bar) : i_(i), fn_(fn) {}
    PrInc2 operator()() { return fn_(i_); }
  private:
    int i_;
    Factory fn_;
};

PrInc2 bar(int i) {
    std::cout << i << std::endl;
    return PrInc2(i+1);
    // error: could not convert 'bar' from 'PrInc2 (*)(int) to 'Factory {aka std::function<PrInc2(int)>'
}

int main() {
    auto p1 = PrInc {1};
    auto p2 = PrInc{p1()};
    p2();

    auto p3 = PrInc2 {1};
    // error: could not convert 'bar' from 'PrInc2 (*)(int) to 'Factory {aka std::function<PrInc2(int)>'
    auto p4 = p3();
    p4();

    return 0;
}

我做错了什么?

编辑: thelink2012 建议尝试PrInc2(int i, Factory fn = Factory(bar)) 在上面的“repro”上工作正常,但在motivating example 上失败(GitHub 链接;相关代码是 erdos.h:35-54 左右ParseStep 和 ParseFunction)。回到绘图板以获得更好的再现......

【问题讨论】:

标签: c++ c++11


【解决方案1】:

您的代码的以下部分似乎与您所询问的编译器错误相关,它使用-std=c++11 模式与 gcc 4.9.2 一起干净地编译:

#include <functional>
#include <iostream>

using Worker = std::function<int(int)>;

int foo(int i) {
    std::cout << i << std::endl;
    return i+1;
}

class PrInc {
  public:
    PrInc(int i, Worker fn = foo) : i_(i), fn_(fn) {}
    int operator()() { return fn_(i_); }
  private:
    int i_;
    Worker fn_;
};

很可能是您正在使用的旧版 gcc 中的错误。升级到更新版本的 gcc。

【讨论】:

  • 实际上,这是我不感兴趣的代码部分;它是为了对比。错误是 std::function 周围的东西。为了清楚起见,我将编辑原件;我知道我在哪里搞砸了这个例子。
猜你喜欢
  • 2021-12-22
  • 1970-01-01
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 2015-03-09
相关资源
最近更新 更多