在函数上使用类型定义

Use of typedef on function

本文关键字:类型 定义 函数      更新时间:2023-10-16

在下面,我如何用typedef语法定义我的函数?

typedef void F();
//declare my function
F f;
//error
F f { }

函数定义将遵循通常的语法:

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

要测试定义确实是先前声明的函数的定义,在声明之后的定义之前的调用函数f()(阅读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


至于为什么F f{}不起作用,因为它是语言规范明确禁止的。§8.3.5 (c++ 03)说

函数类型的typedef可用于声明函数,但不能用于定义函数(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]

重要的几点:

    函数的类型定义可以用来声明一个函数
  • 函数的类型定义不能用于定义函数