Last weekend (4/4/2021) I was sitting down and working on my San Diego C++ agenda for the 25th upcoming session.
One of things I really like presenting is few riddles from cppquiz.org
I stumbled upon this one: https://cppquiz.org/quiz/question/227 . Simple and easy one.
Here is the code in question:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> using Func = int(); struct S { Func f; }; int S::f() { return 1; } int main() { S s; std::cout << s.f(); } |
And the question is what is the output.
So clearly the question is what does the following syntax mean?
1 |
Func f; |
Initially, the “using” part looked like an innocent typedef of a function pointer. But is it?
A quick check with cppinsights.io shows the following
1 2 3 4 5 6 |
using Func = int(); struct S { int f(); }; |
Clearly this is not a function pointer typedef, and we are not defining any “f” as a data member.
Instead, we are actually defining a function named as “f” that returns “int” and takes no params.
So when does it look like a function pointer and when it is not?
Here is a small playground cppinsights.io.
And the gist of it is described in the following snippet:
1 2 3 |
using Func = int(); // function typedef using Funcp_t = int(*)(); // function pointer typedef using bFuncp_t = std::add_pointer_t<int()>; // Modern C++ function pointer typedef |
Good stuff! Did not know 🙂 Welcome!
thank you!