c ++将模板化函数应用于元组的每个元素

Vin*_*nce 1 c++ templates apply variadic-templates stdtuple

template<typename T>
void print(T& t)
{
    std::cout << t << std::endl;
}

template<typename ... Args>
class Container 
{

    public:

    Container(Args&& ... args)
    : values_(std::forward<Args>(args)...)
    {}

    template<int INDEX>
    typename std::tuple_element<INDEX, std::tuple<Args...> >::type& get()
    {
        return std::get<INDEX>(values_);
    }

    void display()
    {
        // (obviously) does not compile !
        std::apply(print,values_);
    }

    private:
    std::tuple<Args ...> values_;

};
Run Code Online (Sandbox Code Playgroud)

上面的代码显示了意图但不正确(注释的地方),因为函数“print”需要一个模板。

有没有办法将(适当模板化的)打印函数调用到元组 values_ 的每个元素?

运行代码:https : //onlinegdb.com/SJ78rEibD

cig*_*ien 5

您需要apply像这样将元组解包:

void display()
{
    std::apply([](auto ...ts) { (..., print(ts)); },values_);
}
Run Code Online (Sandbox Code Playgroud)

这是一个演示

请注意,此解决方案使用折叠表达式来简化语法。

  • 可能值得一提的是,这种奇特的语法称为[折叠表达式](https://en.cppreference.com/w/cpp/language/fold)。 (3认同)