相关疑难解决方法(0)

std :: function vs template

感谢C++ 11,我们收到了std::functionfunctor包装器系列.不幸的是,我一直只听到关于这些新增内容的不好的事情.最受欢迎的是它们非常慢.我对它进行了测试,与模板相比,它们真的很糟糕.

#include <iostream>
#include <functional>
#include <string>
#include <chrono>

template <typename F>
float calc1(F f) { return -1.0f * f(3.3f) + 666.0f; }

float calc2(std::function<float(float)> f) { return -1.0f * f(3.3f) + 666.0f; }

int main() {
    using namespace std::chrono;

    const auto tp1 = system_clock::now();
    for (int i = 0; i < 1e8; ++i) {
        calc1([](float arg){ return arg * 0.5f; });
    }
    const auto tp2 = high_resolution_clock::now();

    const auto d = duration_cast<milliseconds>(tp2 - tp1);  
    std::cout << …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11 std-function

156
推荐指数
7
解决办法
6万
查看次数

我应该通过const-reference传递std :: function吗?

假设我有一个函数,它需要std::function:

void callFunction(std::function<void()> x)
{
    x();
}
Run Code Online (Sandbox Code Playgroud)

我应该x通过const-reference来代替吗?:

void callFunction(const std::function<void()>& x)
{
    x();
}
Run Code Online (Sandbox Code Playgroud)

这个问题的答案是否会根据函数的作用而改变?例如,如果它是一个类成员函数或构造函数,它存储或初始化std::function成成员变量.

c++ reference function

123
推荐指数
3
解决办法
5万
查看次数

标签 统计

c++ ×2

c++11 ×1

function ×1

reference ×1

std-function ×1

templates ×1