可变参数模板initilizer_list技巧 [英] Variadic template initilizer_list trick

查看:87
本文介绍了可变参数模板initilizer_list技巧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Visual Studio 2017 RC上使用C ++ 17编写了for_each_tuple,但对此实现感到震惊。

I've wrote for_each_tuple with C++17 on visual studio 2017 RC and I am horrified about that implementation.

签出:

template<class fun_t, class tuple_t>
constexpr auto for_each_tuple(fun_t& fun, tuple_t&& tuple) {

    std::apply([&](auto&&... args) {
        auto l = { (fun(std::forward<decltype(args)>(args)), 0)... };
    }, std::forward<tuple_t>(tuple));
}

int main() {
    auto tup = std::make_tuple(
        1, 2, 3, 4
    );
    for_each_tuple([](auto& arg) { ++arg; }, tup);
    for_each_tuple([](auto& arg) {std::cout << arg; }, tup);

}

输出:
2345

output: 2345

我对此部分有严重疑问:

I have serious questions about this part:

auto l = { (fun(std::forward<decltype(args)>(args)), 0)... };

仅仅是编译器trick俩还是完全标准的正确方法?

Is that just compiler trick or fully standard correct way?

以及如何准确地将函数调用解析为std :: initilizer_list?

And how exactly function call parsed into std::initilizer_list ?

如何根据您的意见使该函数更好?

How make that function better on your opinion?

推荐答案

在C ++ 17中,

auto l = { (fun(std::forward<decltype(args)>(args)), 0)... }; 

可以重写为:

(fun(std::forward<decltype(args)>(args)), ...);

列表技巧是完全合法的(从标准的角度来看)C ++ 11 / C ++ 14等待折叠表达式时的解决方法。

基本思想是创建一个列表(或数组),此列表在此之后立即被丢弃。由于逗号运算符的工作原理,该容器中填充了零。最后,参数包的展开只会强制每个参数调用给定函数。

换句话说,您可以想象如下:

The list trick is a perfectly legal (from the point of view of the standard) C++11/C++14 workaround while waiting for fold expressions.
The basic idea is to create a list (or an array) to be discarded immediately after. That container is filled with zeros, because of how the comma operator works. Finally, the unfolding of the parameter pack simply forces the invokation of the given function for each parameter.
In other terms, you can imagine it as it follows:

auto l = { (fun(std::forward<decltype(arg0)>(arg0)), 0), (fun(std::forward<decltype(arg1)>(arg1)), 0), (fun(std::forward<decltype(arg2)>(arg2)), 0), and so on... }; 

这篇关于可变参数模板initilizer_list技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆