通过Lambdas打开包装变量参数 [英] Unpacking Variadic Parameters via Lambdas
问题描述
我试图避免外部函数或递归调用,所以我决定测试lambdas的力量,但我被卡住了。如果可能,我如何解开 Args ...
使用lambdas?
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?
我试图做 std :: tie
以获得参数到tuple然后我试图使用 std :: get< I>
其中 I
是一个非const整数,但它失败,因为get需要一个 constexpr
。
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++;
}
}
推荐答案
我理解你正在尝试实现,你可以使用这个简单的技巧:
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)...};
};
调用 Unpack
的参数插入 std :: cout
(因此,打印到标准输出)。
Invoking the Unpack
function object will cause all of the arguments to be inserted into std::cout
(and, therefore, printed to the standard output).
这篇关于通过Lambdas打开包装变量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!