Unpacking Variadic Parameters via Lambdas

2019-05-24 07:30发布

I'm trying to avoid external functions or recursive calls so I decided to test the power of lambdas but I got stuck. How would I go about unpacking Args... using lambdas if possible?

I attempted to do std::tie to get the arguments into tuple then I tried to use std::get<I> where I is a non-const integer but it fails because get requires a constexpr.

I also tried initialization lists which I knew would fail but was worth a shot. I don't want to do it the Wikipedia way. I want to do it this way:

Any ideas or am I doomed?

template<typename... Args>
void fcout(const char* s, Args... args)
{
    std::function<void(Args... A)> Unpack = [&](Args... A) {
        //Unpack(A...);
    };

    while (*s)
    {
        if (*s == '%')
        {
            if (*(s + 1) == '%')
            {
                ++s;
            }
            else
            {
                Unpack(args...);
                fcout(s + 1, args...);
                return;
            }
        }
        std::cout << *s++;
    }
}

标签: c++ c++11 lambda
1条回答
叛逆
2楼-- · 2019-05-24 08:27

If I understand correctly what you are trying to achieve, you can use this simple trick:

std::function<void(Args... A)> Unpack = [&](Args... A) {
    auto l = {((std::cout << A), 0)...};
};

Invoking the Unpack function object will cause all of the arguments to be inserted into std::cout (and, therefore, printed to the standard output).

查看更多
登录 后发表回答