函数模板可变参

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

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

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

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

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

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

二:函数模板可变参重载

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

template<typename... T>
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;
}

猜你喜欢

转载自blog.csdn.net/qq_38158479/article/details/121252165