1

Referring to my previous question, as the explanation is required in detail. How is the following code snippet working, fundamental and C++ 03 equivalent ?

 auto get_option_name = [](const std::pair<const std::string, std::string>& p) -> const std::string& {
    return p.first;
 };
Community
  • 1
  • 1
CMouse
  • 130
  • 3
  • 19
  • it's a functor, ie an object that work like a function. see [here](http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) – sp2danny Apr 21 '17 at 07:15

2 Answers2

3

It's equivalent to:

class Extractor {
    // Definition of "function call" operator, to use instance
    // of this class like a function
    const std::string& operator()(const std::pair<const std::string, std::string>& p) {
        return p.first;
    }
};

Extractor get_option_name;

More information on wikipedia or on stackoverflow

Community
  • 1
  • 1
Garf365
  • 3,619
  • 5
  • 29
  • 41
2

@Garf365's answer is the best. A lambda and a class like that one really are the most similar - you can use them just like callable functions, and pass around pointers and references to them.

However, you may also want to learn about using function templates to do this work during compile-time, especially when passing them as a parameter to another template, as in using the boost library.

I was curious if there was an improvement in the complexity of the code the compiler produced by using a function template, and there was!

Look for yourself:

Thank you for asking the question and leading me to look into it!

Shalom Craimer
  • 20,659
  • 8
  • 70
  • 106
  • 1
    This answer is **incorrect** - the reason your function object results in longer assembly is that you are converting `pair` to `pair` in `Extractor::operator()` which requires a copy. If you remove the `const` and make a temporary `Extractor` the resulting code is identical. – rlbond Sep 17 '20 at 00:15
  • @rlbond I'm always happy to have a better way shown to me. Please share your answer, so everyone can see the best way to do it. It's been 3.5 years (to the day!) since I wrote the answer, so I can't recall all the details (I remember I was writing code for GCC 4.4.7 at the time, so I'm not sure why I used a different version in answering this question. Oh well!) – Shalom Craimer Sep 17 '20 at 04:21