Variadic template pack expansion

2019-01-01 03:25发布

I am trying to learn variadic templates and functions. I can't understand why this code doesn't compile:

template<typename T>
static void bar(T t) {}

template<typename... Args>
static void foo2(Args... args)
{
    (bar(args)...);
}

int main()
{
    foo2(1, 2, 3, "3");
    return 0;    
}

When I compile it fails with the error:

Error C3520: 'args': parameter pack must be expanded in this context

(in function foo2).

6条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 03:47

You can use make_tuple for pack expansion as it introduces a context where the , sequence produced by an expansion is valid

make_tuple( (bar(std::forward<Args>(args)), 0)... );

Now, I suspect the unused/unnamed/temporary tuple of zeroes that's produced is detactable by the compiler and optimized away

Demo

查看更多
后来的你喜欢了谁
3楼-- · 2019-01-01 03:52

This is a full example, based on the answers here.

Example to reproduce console.log as seen in JavaScript:

Console console;
console.log("bunch", "of", "arguments");
console.warn("or some numbers:", 1, 2, 3);
console.error("just a prank", "bro");

Filename e.g. js_console.h:

#include <iostream>
#include <utility>

class Console {
protected:
    template <typename T>
    void log_argument(T t) {
        std::cout << t << " ";
    }
public:
    template <typename... Args>
    void log(Args&&... args) {
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void warn(Args&&... args) {
        cout << "WARNING: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }

    template <typename... Args>
    void error(Args&&... args) {
        cout << "ERROR: ";
        int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
        cout << endl;
    }
};
查看更多
泪湿衣
4楼-- · 2019-01-01 04:01

SHAMELESS COPY [approved by its source]

Parameter packs can only be expanded in a strictly-defined list of contexts, and operator , is not one of them. In other words, it's not possible to use pack expansion to generate an expression consisting of a series of subexpressions delimited by operator ,.

The rule of thumb is "Expansion can generate a list of ,-separated patterns where , is a list delimiter." Operator , does not construct a list in the grammar sense.

To call a function for each argument, you can use recursion (which is the primary tool in the variadic template programmer's box):

#include <utility>

template<typename T>
void foo(T &&t){}

template<typename Arg0, typename Arg1, typename ... Args>
void foo(Arg0 &&arg0, Arg1 &&arg1, Args &&... args){
    foo(std::forward<Arg0>(arg0));
    foo(std::forward<Arg1>(arg1), std::forward<Args>(args)...);
}

auto main() -> int{
    foo(1, 2, 3, "3");
}

USEFUL NON-COPIED INFO

Another thing you probably haven't seen in this answer is use of the && specifier and std::forward. In C++, the && specifier can mean one of 2 things: rvalue-references, or universal references.

I won't go into rvalue-references, but to somebody working with variadic templates; universal references are a god-send.

Perfect Forwarding

One of the uses of std::forward and universal references are perfect forwarding of types to other functions.

In your example, if we pass an int& to foo2 it will be automatically demoted to int because of the signature of the generated foo2 function after template deduction and if you wanted to then forward this arg to another function that would modify it ny reference, you will get undesired results (the variable won't be changed) because foo2 will be passing a reference to the temporary created by passing an int to it. To get around this, we specify a forwarding function to take any type of reference to a variable (rvalue or lvalue). Then, to be sure that we pass the exact type passed in the forwarding function we use std::forward, then and only then do we allow the demoting of types; because we are now at the point where it matters most.

If you need to, read more on universal references and perfect forwarding; scott meyers is pretty great as a resource.

查看更多
余欢
5楼-- · 2019-01-01 04:06

One of the places where a pack expansion can occur is inside a braced-init-list. You can take advantage of this by putting the expansion inside the initializer list of a dummy array:

template<typename... Args>
static void foo2(Args &&... args)
{
    int dummy[] = { 0, ( (void) bar(std::forward<Args>(args)), 0) ... };
}

To explain the content of the initializer in more detail:

{ 0, ( (void) bar(std::forward<Args>(args)), 0) ... };
  |       |       |                        |     |
  |       |       |                        |     --- pack expand the whole thing 
  |       |       |                        |   
  |       |       --perfect forwarding     --- comma operator
  |       |
  |       -- cast to void to ensure that regardless of bar()'s return type
  |          the built-in comma operator is used rather than an overloaded one
  |
  ---ensure that the array has at least one element so that we don't try to make an
     illegal 0-length array when args is empty

Demo.

An important advantage of expanding in {} is that it guarantees left-to-right evaluation.


With C++1z fold expressions, you can just write

((void) bar(std::forward<Args>(args)), ...);
查看更多
浅入江南
6楼-- · 2019-01-01 04:12

The execution order is not guaranteed for this!

make_tuple( (bar(std::forward<Args>(args)), 0)... );

In this example parameters will be printed in reverse order at least with GCC.

foo2(1, 2, 3, "3");

calling bar for 3
calling bar for 3
calling bar for 2
calling bar for 1
查看更多
路过你的时光
7楼-- · 2019-01-01 04:13

Parameter packs can only be expanded in a strictly-defined list of contexts, and operator , is not one of them. In other words, it's not possible to use pack expansion to generate an expression consisting of a series of subexpressions delimited by operator ,.

The rule of thumb is "Expansion can generate a list of ,-separated patterns where , is a list delimiter." Operator , does not construct a list in the grammar sense.

To call a function for each argument, you can use recursion (which is the primary tool in the variadic template programmer's box):

template <typename T>
void bar(T t) {}

void foo2() {}

template <typename Car, typename... Cdr>
void foo2(Car car, Cdr... cdr)
{
  bar(car);
  foo2(cdr...);
}

int main()
{
  foo2 (1, 2, 3, "3");
}

Live example

查看更多
登录 后发表回答