相关疑难解决方法(0)

C++ lambda,捕获为函数指针

我正在玩C++ lambdas以及它们对函数指针的隐式转换.我的开始示例是将它们用作ftw函数的回调.这按预期工作.

#include <ftw.h>
#include <iostream>

using namespace std;

int main()
{
    auto callback = [](const char *fpath, const struct stat *sb,
        int typeflag) -> int {
        cout << fpath << endl;
        return 0;
    };

    int ret = ftw("/etc", callback, 1);

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

修改后使用捕获:

int main()
{

    vector<string> entries;

    auto callback = [&](const char *fpath, const struct stat *sb,
        int typeflag) -> int {
        entries.push_back(fpath);
        return 0;
    };

    int ret = ftw("/etc", callback, 1);

    for (auto entry : entries …
Run Code Online (Sandbox Code Playgroud)

c++ lambda function-pointers c++11

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

std :: function而不是谓词的模板

许多标准库算法都采用谓词函数.但是,这些谓词的类型是用户提供的任意模板参数.为什么C++ 11没有指定这些类型采用特定类型std::function?例如:

template< class InputIt >
InputIt find_if( InputIt first, InputIt last,
             std::function<bool()> p );
Run Code Online (Sandbox Code Playgroud)

是不是使用这个而不是模板作为参数类型不是更干净?

c++ templates stl c++11 std-function

10
推荐指数
2
解决办法
1925
查看次数

标签 统计

c++ ×2

c++11 ×2

function-pointers ×1

lambda ×1

std-function ×1

stl ×1

templates ×1