前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >是黑魔法吗?揭秘std::is_function!

是黑魔法吗?揭秘std::is_function!

作者头像
公众号guangcity
发布2024-03-22 12:54:22
790
发布2024-03-22 12:54:22
举报
文章被收录于专栏:光城(guangcity)光城(guangcity)

最近在写C++代码时用到了is_function,然后顺便看了一下源码实现,发现了一些问题,以前咱们学习的是三个点...,那六个点......你知道是啥吗?

同样,如果有一段这样的代码:

代码语言:javascript
复制
template<typename... Args>
struct foo(Args......);

你知道是啥意思?

下面我们一起来深入细节!

1.六个点

六个点我们通常叫做two ellipsis operators,我们可以将六个点进行拆分,于是得到下面三种情况

代码语言:javascript
复制
template <typename... Args> void foo1(Args......)
template <typename... Args> void foo2(Args... ...)
template <typename... Args> void foo3(Args..., ...)

这下就好看了,我们来看std::is_function的代码。

2.is_function实现细节

std::is_function的实现涉及到主模板和两个偏特化:

代码语言:javascript
复制
// 主模板,假设提供的类型不是函数类型
template<typename T>
struct is_function : std::false_type {};

// 偏特化,用于正常的函数类型
template<typename Ret, typename... Args>
struct is_function<Ret(Args...)> : std::true_type {};

// 偏特化,用于变参函数类型
template<typename Ret, typename... Args>
struct is_function<Ret(Args......)> : std::true_type {};
  • 主模板假设提供的类型不是函数类型,并将std::false_type作为结果。
  • 第一个偏特化用于正常的函数类型,其中Ret表示返回类型,Args...表示参数类型。如果提供的类型匹配这种函数签名,则std::true_type作为结果。
  • 第二个偏特化用于变参函数类型,其中的省略号表示函数具有可变数量的参数。同样,如果提供的类型匹配这种函数签名,则std::true_type作为结果。

3.使用示例

最后给出一个std::is_function的使用示例:

代码语言:javascript
复制
#include <iostream>
#include <type_traits>

int func(int x, int y) { return x + y; }
int vararg_func(int x, ...) { return x; }

int main() {
    std::cout << std::boolalpha;
    std::cout << "Is func a function? " << std::is_function<decltype(func)>::value << std::endl;
    std::cout << "Is vararg_func a function? " << std::is_function<decltype(vararg_func)>::value << std::endl;
    return 0;
}

这将输出:

代码语言:javascript
复制
Is func a function? true
Is vararg_func a function? true

你学会了吗,本节完~

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-03-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 光城 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.六个点
  • 2.is_function实现细节
  • 3.使用示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档