C++ 函数包装器

标签 c++

我有函数 add,它返回连接的字符串:

std::string add(std::string a, std::string b){
  return a+b;
}

我需要编写通用函数 f1,它接受两个字符串,返回函数包装器,如下所示:

template<typename T>
std::function<T(T(T,T))> f1(T a, T b);

以便此调用输出字符串“OneTwo”:

std::string a("One");
std::string b("Two");
cout << f1(a,b)(add);

如何在 f1 返回的包装器对象中捕获 a 和 b?

最佳答案

您正在寻找的是 lambda 捕获。

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

template<typename arg_type>
std::function<arg_type ( arg_type(arg_type, arg_type))> make_wrapper(arg_type a, arg_type b)
{
    return [a, b](arg_type (*f)(arg_type, arg_type))
    {
        return (*f)(a, b);
    };
}

std::string add(std::string a, std::string b)
{
    return a+b;
}

int main()
{
    std::string a="One";
    std::string b="Two";

    // This should be "auto wrapper=", of course, just explicitly
    // declared for demonstrative purposes:

    std::function<std::string (std::string (std::string, std::string))>
           wrapper = make_wrapper(a, b);

    std::cout << wrapper(add) << std::endl;
    return 0;
}

结果:

$ g++ -std=c++1z -g -o t t.C
$ ./t
OneTwo

关于C++ 函数包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36956381/

相关文章:

c++ - shmget 大小限制问题

c# - 启动 CLR 后如何设置程序集查找路径?

c++ - 如何知道 CThreadPool 的工作何时完成?

c++ - 模板化类内部函数的模板特化

c++ - 在 C++ 中对字符串使用 OR 运算符

python - 有什么方法可以将用C++创建的变量加载到python解释器中吗?

c++ - 向 std::vector 添加结构时的 std::bad_alloc

c++ - 为什么 "using namespace"声明会混淆 C++ 中的编译器?

c++ - "Conditional jump or move depends on uninitialised value",但堆栈跟踪中未列出分配函数。如何?

c++ - 如何在 SFML 中使用顶点数组?