简体   繁体   中英

what the difference between sizeof..(typename) and sizeof..(parameter) in variadic template c++

Whats the difference between sizeof..(typename) and sizeof..(parameter) in a variadic template in c++?

In cpp primer 5th, I can't understand the difference:

#include <iostream>
using namespace std;

template <typename T, typename... Args>
void foo(const T &t, const Args &... rest)
{
    std::cout << "sizeof...(Args)=" << sizeof...(Args) << "  sizeof...(rest)=" << sizeof...(rest) << std::endl;
}

int main(int argc, const char **argv)
{
    int i = 0;
    double d = 3.14;
    string s = "how";

    foo(i, s, 42, d); /// sizeof...(Args)=3  sizeof...(rest)=3
    foo(s, 42, "hi"); /// sizeof...(Args)=2  sizeof...(rest)=2
    foo(d, s);        /// sizeof...(Args)=1  sizeof...(rest)=1
    foo("hi");        /// sizeof...(Args)=0  sizeof...(rest)=0
    foo(i, s, s, d);  /// sizeof...(Args)=3  sizeof...(rest)=3

    while (1)
        ;
    return 0;
}

sizeof...(rest) counts the number of arguments (not including the first). sizeof...(Args) counts the number of their types. There is no difference on the result.

The sizeof... operator gives the number of arguments in a parameter pack, and works for both template parameter packs (like Args ) and function parameter packs (like rest ). A function parameter pack always has the same count as the template parameter pack(s) used in declaring its type, for each specialization of the function template.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM