7

Function alias vs Function pointer alias

 3 years ago
source link: https://vorbrodt.blog/2021/04/08/function-alias-vs-function-pointer-alias/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Function alias vs Function pointer alias

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:

#include <iostream>
using Func = int();
struct S {
    Func f;
int S::f() { return 1; }
int main() {
    std::cout << s.f();

And the question is what is the output.

So clearly the question is what does the following syntax mean?

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

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:

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

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK