0

In this reply https://stackoverflow.com/a/58737595 please, can you explan how it is possible to write :

return f( f, std::forward<Args>(args)... );

whereas f is only declared as : F f; and we don't know that f is a function accepting 2 parameters a priori. Thank you for your explanation.

I would be grateful for the deep explanations

4
  • 2
    Well this only compiles if F is a type that has a operator() with the given parameter types. This is checked by the compiler once the template is instantiated and if F does not fit the requirements, the compiler will exit with an error.
    – eike
    Nov 19, 2019 at 10:42
  • 2
    If it walks like a duck... Nov 19, 2019 at 10:44
  • 2
    @eike or F is a function (pointer) type
    – Caleth
    Nov 19, 2019 at 11:12
  • I have updated my first message and the line of code to make my question more clear
    – Dev
    Nov 19, 2019 at 11:12

1 Answer 1

2

It looks like you need some good C++ tutorial/book, specifically about templates.

The piece of code you're referring to is a templated struct.

template<class F>
struct y_combinator {
  F f;
 /* more code */
}

It means that whenever we want to use it we have to specify the template parameter.

y_combinator<int> y_int;

When we use our templated struct like that, the compiler will generate a new struct, let's call it y_combinator_int, and replace all occurences of F with int.

The important thing is that templates use duck typing, if you do something that's illegal/makes no sense, you will get a compile time error (currently such errors are really hard to read, but with C++20 we will probably get more human readable errors).

Overall templates are a very complicated subject, if you want to learn them you need to find a good tutorial/book.

3
  • I have updated the line of code of my first message
    – Dev
    Nov 19, 2019 at 11:13
  • The anserw remains the same, templates use duck typing. We don't know if F has such operator, but when we specify the type of F, like in my code example, the compiler will generate needed code and functions, which can result in a compilation error
    – Kaldrr
    Nov 19, 2019 at 11:18
  • This error message isn't that cryptic:
    – Caleth
    Nov 19, 2019 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.