相关疑难解决方法(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万
查看次数

C++ 11中的递归lambda函数

我是C++ 11的新手.我正在编写以下递归lambda函数,但它不编译.

sum.cpp

#include <iostream>
#include <functional>

auto term = [](int a)->int {
  return a*a;
};

auto next = [](int a)->int {
  return ++a;
};

auto sum = [term,next,&sum](int a, int b)mutable ->int {
  if(a>b)
    return 0;
  else
    return term(a) + sum(next(a),b);
};

int main(){
  std::cout<<sum(1,10)<<std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

vimal @ linux-718q:〜/ Study/09C++/c ++ 0x/lambda> g ++ -std = c ++ 0x sum.cpp

sum.cpp:在lambda函数中:sum.cpp:18:36:错误:' ((<lambda(int, int)>*)this)-><lambda(int, int)>::sum'不能用作函数

gcc版本

gcc版本4.5.0 20091231(实验性)(GCC)

但如果我改变sum()下面的声明,它的作用是:

std::function<int(int,int)> sum = [term,next,&sum](int a, …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++11

127
推荐指数
8
解决办法
6万
查看次数

在声明它的同一行中调用C++递归lambda

这主要是一种单线型问题,出于可读性原因,我通常会将这些代码写成多行.

所以我的问题是我可以在定义它的同一语句中调用递归lambda吗?

所以不是这样的:

int n=3;
function<void(int)> f {[n,&f](int i){if (i>1) { cout << "func(a, "; f(i-1); cout << ")";} else cout << "a";}};
f(n);
Run Code Online (Sandbox Code Playgroud)

n在定义f的同一行中调用该函数.

c++ recursion lambda c++11

17
推荐指数
3
解决办法
2001
查看次数

为什么此递归lambda函数不安全?

这个问题来自lambda函数可以递归吗?。该接受的答案说,下面的作品显示递归lambda函数。

std::function<int (int)> factorial = [&] (int i) 
{ 
    return (i == 1) ? 1 : i * factorial(i - 1); 
};
Run Code Online (Sandbox Code Playgroud)

但是,有评论指出

这样的功能不能安全地返回

,并且此注释中提供了原因:

返回它会破坏局部变量,并且该函数具有对该局部变量的引用

我不明白原因。据我所知,捕获变量等效于将其保留为数据成员(根据捕获列表的按值或按引用)。那么在这种情况下什么是“局部变量”?此外,即使使用7.4.0中的-Wall -Wextra -std=c++11选项,下面的代码也可以编译并正常工作g++

#include <iostream>
#include <functional>

int main() {

    std::function<int (int)> factorial = [&factorial] (int i)
    {
        return (i == 1) ? 1 : i * factorial(i - 1);
    };

    std::cout << factorial(5) << "\n";

}
Run Code Online (Sandbox Code Playgroud)

为什么功能不安全?此问题是否仅限于此函数或整个lambda表达式?

c++

8
推荐指数
1
解决办法
155
查看次数

标签 统计

c++ ×4

c++11 ×3

lambda ×2

recursion ×1

std-function ×1

templates ×1