jeudi 11 juillet 2019

Define a factory function that returns a pointer to a function created in this factory function

My question is: how to define a factory function that takes a parameter and returns a function pointer pointing to a function that is created according to that parameter? (or any other nice way to achieve the same result)


Explanation

In essence, I want to define a factory function set, which takes a std::string parameter str, and returns a pointer to function pf. The function pointer pf points to a function, just created in set, that takes std::ostream & and returns std::ostream &.

In this way, I want to call with std::cout << set(str) << "text" << std::endl;. I hope that the result of set(str) lives at least as long as this statement.

For your reference, it is from cplusplus that

ostream & operator<< (ostream & (*pf)(ostream &));


More Explanation

This is for a real example, shown as below.

First I have manipulators

std::ostream & black(std::ostream & os)
{
    return os << "\033[30m";            // make terminal text black
}

std::ostream & red(std::ostream & os)
{
    return os << "\033[31m";            // make terminal text red
}

std::ostream & green(std::ostream & os)
{
    return os << "\033[32m";            // make terminal text green
}

so that when I call

std::cout << red << "this text is in red" << std::endl;

I will have the desired effect. So far so good.

Now with a map

std::map<std::string, std::string> code =
{
    {"black", "30"},
    {"red", "31"},
    {"green", "32"}
    // ...
    // could extend much longer as there are many colors
};

I hope to achieve a similar, customized effect with foo("red") with

void foo(std::string str)
{
    std::cout << set(str) << ("this text is in " + str) << std::endl;
}

where set takes "red" and looks up the map code for the corresponding code "31".

But I have problems in implementing the set function. I would appreciate it much if anyone could help me with this!

Two notes:

  1. If possible, I want good performance for the set function, as it will be called again and again.

  2. Forgive me please if I think the wrong way --- So long as you can implement the functionality for set, I don't mind you do it in a different way.

Thank you for reading this long post. Thank you very much!

Aucun commentaire:

Enregistrer un commentaire