3 ms·
> you can't just pass functions to F1 or F2, they have to be objects. Why? https://godbolt.org/z/2kJsT9 https://godbolt.org/z/2kJsT9
by steerablesafe 6y ago
> you can't just pass functions to F1 or F2, they have to be objects.
Why?
https://godbolt.org/z/2kJsT9 https://godbolt.org/z/2kJsT9
- jkcxn 6y agoI'm new to C++, what are lines 11-12 for? I see that it doesn't compile without it. It doesn't seem to be the new 'arrow return type' syntax because there's no auto keyword. Edit: I found it - it's a 'template deduction guide' https://stackoverflow.com/questions/40951697/what-are-template-deduction-guides-and-when-should-we-use-them https://stackoverflow.com/questions/40951697/what-are-templa...
- gpderetta 6y agoYes, the functionality was added in C++17, it is quite convenient, before you had to write boilerplate make_X 'constructor' functions. In C++20 this specific deduction guide is no longer required as it is implicitly generated for template aggregates, so even less boilerplate.
- jcelerier 6y agothat only works if you are in a context where you can deduce the type from ctor arguments, which is definitely not all cases (for instance, storing as a member and initializing in a ctor, etc...)
- gpderetta 6y agoYou can then specify the function pointer type, although mildly inconvenient. If you want to use lambdas though, then yes, you are out of luck as their type is unnameable.
- jcelerier 6y agobut that fails as soon as you have a case where you want to pass an algorithm implementation that does have state. That was my point - whenever I assumed that I would not have state... well I ended up needing to refactor everything because I ended up needing to add a new strategy that did require some state later. In the context of C++, struct / class types are more generic that function pointers and there's no real shortcut around this - that's how the language is specified.
- steerablesafe 6y agoThere is nothing wrong with writing generic code that works both with functions and function objects. Note that stateless (empty) function objects can often be more efficient than function pointers.