加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用别名的功能

发布时间:2020-12-16 09:52:52 所属栏目:百科 来源:网络整理
导读:以下代码究竟是什么声明的; using f1 = void(int); 我知道以下内容; using f2 = void(*)(int);using f3 = void()(int); f2是指向函数的指针,f3是参考. 解决方法 它是什么? 这是一种功能类型.声明函数时,例如: void func(int); 它的类型不是指针也不是引用.
以下代码究竟是什么声明的;

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';
}

Live demo

以上代码仅对第一行返回true.

它与指针或引用相同吗?

不,但函数左值可以隐式转换为函数指针,如下所示:

§4.3/1 Function-to-pointer conversion [conv.func]

An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function.

函数类型A(Args …)与其引用(即A(&)(Args …))之间的关系基本上与任何类型T与其引用(即T&)之间的关系相同.

它在哪里使用?

它通常用作模板参数.

例如,std :: function将函数类型存储在std :: function对象中,您可以使用以下命令声明这样的对象:

std::function<void(int)> fn;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读