加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将函数应用于变量函数的参数包的所有元素

发布时间:2020-12-16 09:22:13 所属栏目:百科 来源:网络整理
导读:参见英文答案 variadic template parameter pack expanding for function calls????????????????????????????????????2个 考虑以下(不工作!)示例: #include iostreamtemplate typename type void print(const type item){ std :: cout item std :: endl;}t
参见英文答案 > variadic template parameter pack expanding for function calls????????????????????????????????????2个
考虑以下(不工作!)示例:

#include <iostream>

template <typename type> void print(const type & item)
{
    std :: cout << item << std :: endl;
}

template <typename... types> void printall(const types & ... items)
{
    print(items)...;
}

int main()
{
    printall(1,2,"hello");
}

这里我有一个函数print,它只是打印出它的参数,以及一个可变函数printall,它接受一组参数.现在,我想做的是简单地将printall应用于包装物品的每个元素.我该怎么做呢?

注意:我不是在问如何打印一组值.我知道fold表达式的存在,我知道我可以使用它们将整个项目抛出到std :: cout中.这里打印只是一个例子,可以是任何功能.

我该怎么做呢?这听起来像是非常简单的事情,但我找不到任何(合理的)语法来做到这一点.

解决方法

What I would like to do is to simply have printall apply print to
each element of the pack items. How can I get that done?

选项1

正如用户@liliscent和用户@max66在评论中建议的那样,
在C 11 / C 14中,您可以使用以下hacky-way,其行为类似于C 17中的折叠表达式.

SEE HERE

#include <iostream>

template <typename type> void print(const type& item)
{
    std::cout << item << 'n';
}

template <typename... types> 
void printall (const types&... items)
{
    using dummy = int[];
    (void)dummy { 0,(print(items),0)... };
}

选项 – 2

如果上面看起来不够好,请提供经典的可变参数模板重载作为printall()和print()函数之间的包装器/帮助器,以便可以在print()中访问每个模板函数参数.

SEE HERE

#include <iostream>

template <typename Type> void print(const Type& item)
{
    std::cout << item << 'n';  // print each argument
}

namespace helper 
{
    void printall() {}          // nontemplate overload for last call(i.e,no arguments call)

    template<typename FirstArg,typename... Types>
    void printall(const FirstArg& firstItem,Types&&... items)  
    {
        ::print(firstItem);                             // call print() for each argument
        helper::printall(std::forward<Types>(items)...);// calls the same wrapper::printalll()
    }
}

template <typename... Types> void printall(const Types& ... items)
{
    helper::printall(items...); // calls the wrapper::printall()
}

选项 – 3

但是,如果您可以访问C 17,只需使用fold expressions.这样可以提供干净(非hacky)和少量代码.

SEE HERE

template <typename type> void print(const type& item)
{
    std::cout << item << 'n';
}

template <typename... types> void printall(const types&... items)
{
    (print(items),...);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读