以下代码声明了什么:
我知道以下内容:
using f1 = void(int);
我知道以下内容:
我知道以下内容:
using f2 = void(*)(int);
using f3 = void(&)(int);
f2
是一个指向函数的指针,而f3
将是引用。
这是一个函数类型。当你声明一个函数时,例如:
void func(int);
它的类型既不是指针也不是引用。上述函数的类型为void(int)
。
我们可以使用类型特征来“证明”:
void func(int) {}
int main() {
std::cout << std::is_same<decltype(func), void(int)>::value << '\n';
std::cout << std::is_same<decltype(func), void(*)(int)>::value << '\n';
std::cout << std::is_same<decltype(func), void(&)(int)>::value << '\n';
}
以上代码仅针对第一行返回true
。
不是,但函数lvalue可以隐式转换为函数指针,如下所示:
§4.3/1 函数到指针的转换 [conv.func]
函数类型T的lvalue可以转换为类型“指向T的指针”的prvalue。结果是函数的指针。
函数类型A(Args...)
及其引用(即A(&)(Args...)
)之间的关系与任何类型T
及其引用(即T&
)之间的关系基本相同。
通常作为模板参数使用。
例如,std::function
需要一个函数类型来存储在std::function
对象中,您可以使用以下方式声明这样的对象:
std::function<void(int)> fn;
decltype
相关的代码片段特别有用。 - Niall它声明了f1
为一个函数类型,带有一个int
参数和没有返回类型。
它等同于老式的声明方式。
typedef void f(int);