Using typedef for a function

In the following, how can I define my function with typedef syntax?

typedef void F(); //declare my function F f; //error F f { } 
+4
source share
1 answer

A function definition will follow the usual syntax:

 //declare my function F f; //it is exactly equivalent to : void f(); //definition void f() { cout << "hello world"; } 

To verify that the definition is indeed the definition of a previously declared functional, call the f() function only after the declaration and before (read the comments in main() ):

 //declaration F f; int main() { f(); //at compile-time, it compiles because of *declaration* } //definition void f() { std::cout << "hello world" << std::endl; } 

Demo: http://ideone.com/B4d95


As for why F f{} does not work, because it is specifically prohibited by the language specification. §8.3.5 (C ++ 03) states:

A typical function type can be used to declare a function , but should not be used to define a function (8.4) .

 [Example: 
  typedef void F(); F fv; // OK: equivalent to void fv(); F fv { } // ill-formed void fv() { } // OK: definition of fv —end example] 

Important points:

  • Functon typedef function can be used to declare a function
  • Functon typedef function cannot be used to define function
+6
source

Source: https://habr.com/ru/post/1383611/


All Articles