【问题标题】:std::bind and std::function term does not evalue as taking 0 arguments?std::bind 和 std::function 术语不评估为 0 参数?
【发布时间】:2020-05-23 05:18:34
【问题描述】:

我正在研究通用类,该类将用于运行不同原型的函数以进行算法性能测试。

我卡住了,因为std::function 无法执行它所绑定的内容,这里是示例代码,并在错误发生的地方附上注释:

#include <utility>
#include <functional>

template<typename ReturnType>
class Performance
{
public:
    template<typename... Args>
    using Algorithm = std::function<ReturnType(Args...)>;

    template<typename... Params>
    void run(const Algorithm<Params...>& ref, const Algorithm<Params...>& target)
    {
        // ERROR: term does not evaluate as taking 0 args
        ref();
        target();
    }
};

void bar1(int, int)
{
    // algorithm 1
}

void bar2(int, int)
{
    // algorithm 2
}

int main()
{
    using test = Performance<void>;
    using Algorithm = test::Algorithm<int, int>;

    int x = 0;
    int y = 1;

    Algorithm ref = std::bind(bar1, std::ref(x), std::ref(y));
    Algorithm target = std::bind(bar2, std::ref(x), std::ref(y));

    test foobar;

    foobar.run(ref, target);
}

【问题讨论】:

  • 两者都应该占用两个ints,不是吗?
  • 是的,他们已经与ints 和std::bind 绑定在一起,在我看来std::bind 在这里什么也没做,有没有其他解决方案?

标签: c++ c++11 templates std-function stdbind


【解决方案1】:

问题是,std::function 类型,即Algorithm 被声明接受两个参数(类型为int);调用它们时需要两个参数。

std::bind 应用后,返回的函子不带参数;参数(std::ref(x)std::ref(y))已被绑定。 Algorithm 应该声明为

using Algorithm = test::Algorithm<>;

LIVE

【讨论】:

  • @metablaster 这可能会让人感到困惑,因为您可以设置从 std::bind 返回的函子,该函子不接受任何内容,而 std::function 声明接受两个 ints。 std::function 具有类型擦除特性。顺便说一句:如果您尝试在原始代码中传递两个ints,您会发现它可以编译,但传递的ints 根本不使用。使用绑定的参数。 LIVE
猜你喜欢
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
相关资源
最近更新 更多