关于C++入参的可变参数

昨天看C++11里的thread构造函数可以写成带入口和参数的形式, 主要看黑体部分。

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
 
void f1(int n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread " << n << " executing\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
void f2(int& n)
{
    for (int i = 0; i < 5; ++i) {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
int main()
{
    int n = 0;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n + 1); // pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';
}

以上来自cppreference。

我就对参数个数不同,它是怎么知道的产生疑问?好吧,有人立刻想到了printf("%s %d %X", a, b,c)这样的东西。于是就上网查了一下怎么使用可变参数的方法。下面的代码是参照百度上的内容:

大体的意思是针对采用入栈方式调用函数,不需要知道几个入参,利用va_list, va_start, va_end这样的宏来告诉编译器哪个是第一个参数,然后自己一个个把参数取出来,听起来还是挺麻烦的,最关键的是自己要去解析各个参数。

PS:如果是类的成员,由于函数的调用方式和普通函数不一样,我还不知道这两者是不是一样。

要包含头文件

#include <iostream>
#include <thread>
#include <stdarg.h>

void HelloWorld(const char * fisrt, ...)
{
    va_list argp;
    int argno = 0;
    char * para;
    va_start(argp, fisrt);

    while (true)
    {
        para = va_arg(argp, char*);
        if (strcmp(para, "\0") == 0)
        {
            break;
        }

        printf("参数 #%d是: %s\n", argno, para);
        ++argno;
    }
    va_end(argp);
    return;
    
}

int main()
{
    std::thread t(HelloWorld, "This", "is", "a", "DEMO", "\0");
    t.join();
    t.detach();
    system("pause");
    return 0;
}

再在CPPReference上看std::thread的其中一个构造函数(其实第一步就应该看这玩意。。。)

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
答案就是这个了。不过thread的这个构造式的入参不能超过7个,没啥影响,一般函数的入参最好不要超过5个,不然那么多,用起来就烦啊。



转载于:https://my.oschina.net/yangcol/blog/123682

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值