Sanyin
Sanyin

Reputation: 101

C++ function wrappers

I have function add, that returns concatenated strings:

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

I need to write generic function f1 which accepts two strings, returns function wrapper, something like this:

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

so that this call outputs string "OneTwo":

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

How to capture a and b, inside wrapper object returned from f1?

Upvotes: 1

Views: 135

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

What you're looking for is lambda captures.

#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;
}

Result:

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

Upvotes: 1

Related Questions