栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

函数模板可变参

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

函数模板可变参

英文:Variadic Templates ,C++11
一:函数模板可变参
1.1:基本范例

template //T是一包类型,...是固定语法
void fun(T ...args)//args是一包参数,注意...的位置
{
    cout << sizeof...(args) << endl; //输出参数的个数
    cout << sizeof...(T) << endl;//输出参数的个数
}

允许模板定义中包含 0 ,到多个(任意个)模板参数。
1.2:参数包的展开
a)递归

//再实现一个同名的递归终止函数(这是个真正的函数),位置放在  参数包展开函数 的前面
void func()
{
    std::cout << "递归终止" <
void func(T first, U...args)
{
    std::cout << first << std::endl;
    func(args...);
}

b)c++17 if constexpr语句,编译期间做的判断

template 
void func(T first, U...args)
{
    std::cout << first << std::endl;
    if constexpr (sizeof...(args) > 0)
    {
        func(args...);
    }
    else
    {
    }

二:函数模板可变参重载

#include 
using namespace std;
template
void myfunc(T... arg)
{
	cout << "myfunc(T... arg)执行了!" << endl;
}

template
void myfunc(T*... arg)
{
	cout << "myfunc(T*... arg)执行了!" << endl;
}

void myfunc(int arg)
{
	cout << "myfunc(int arg)执行了!" << endl;
}
int main()
{
   //一般来说,调用普通函数和调用函数模板都合适的时候,编译器优先选择普通函数
    myfunc(NULL);
    myfunc(nullptr); //nullptr是空指针
    myfunc((int*)nullptr);
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/458119.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号