了解这个可变模板函数的工作原理 [英] Find out how this variadic templated function works

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

问题描述

这个回答,我看到一些C ++ 11代码,我不真正理解(但我

In this answer I have seen some C++11 code, that I don't really understand (but I would like to).

在这里,定义了一个可变参数模板函数,(或许?)接受所有传递的参数并将它们插入 std :: ostringstream

There, a variadic template function is defined, that (maybe?) takes all arguments passed and inserts them into a std::ostringstream.

这是函数(参见链接答案中的完整工作示例):

This is the function (see the complete working example at the linked answer):

template<typename T, typename... Ts>
std::string CreateString(T const& t, Ts const&... ts)
{
    using expand = char[];

    std::ostringstream oss;
    oss << std::boolalpha << t;
    (void)expand{'\0', (oss << ts, '\0')...};
    return oss.str();
}



当我不得不猜时,我会说,并用 \0 -bytes进行初始化,函数的参数插入到流中是作为初始化(逗号表达式的一部分)的副作用发生的。最后,该数组包含尽可能多的空值,因为项目已插入到流中。它被转换为void,以避免编译器警告(未使用的变量)。类似于此:

When I had to guess, I'd say, a character array is created and initialized with \0-bytes, and the insertion of the function's arguments into the stream happens as a side effect of the initialization (part of that comma expression). In the end, the array contains as many nulls as items were inserted into the stream. It's casted to void in order to avoid a compiler warning (unused variable). Similar to this:

char arr[] = {'\0', (oss << t1, '\0'), (oss << t2, '\0'), ..., (oss << tn, '\0')};

我试图描述这个函数的工作方式是否准确?有人可以解释什么设计决定在这里可能是相关的,为什么这有利于实现它(替代方法将是编译时递归,我猜)?

Is my attempt to describe this function's workings accurate? Can someone explain what design decision might be relevant here, and why is it beneficial to implement it this way (the alternative would be compile-time recursion, I guess)?

推荐答案

在问题评论部分收到一些有用的提示后,我可以找出一些要点:

After receiving some helpful hints in the question's comment section I could figure out some of the points:


  • 正在使用的功能称为包扩展。它的工作原理与OP中描述的一样:临时数组被初始化带有流插入的副作用。可以在此处找到该功能的详细描述:

    • The feature being used is called pack expansion. It works exactly as described in the OP: a temporary array is initialized with the side effect of stream insertion. A detailed description of the feature can be found here:
      • http://en.cppreference.com/w/cpp/language/parameter_pack
      • http://en.cppreference.com/w/cpp/language/fold
      • See also this question's answers: Variadic template pack expansion
      • http://en.cppreference.com/w/cpp/language/array

      这篇关于了解这个可变模板函数的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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