C++ Parameter Pack 展開的簡單例子之一

pack.cpp
#include <iostream>

/* functions to be resolved */
void f(int a, int b, int c);
void f(int* pa, int* pb, int* pc);
void f(int** ppa, int* pb, int* pc);

/* two kind of paramter pack to expand */

/* expand args as normal */
template<typename... ArgsT>
void f_in_value(ArgsT... args)
{
    f(args...);
    // args expands f(a, b, c); in place
}

/* expand args with & as prefix */
template<typename... ArgsT>
void f_in_address(ArgsT... args)
{
    f(&args...);
    // args expands f(&a, &b, &c); in place
    // args expands f(&pa, &b, &c); in place
}

int main()
{
    int a = 1;
    int b = 2;
    int c = 3;
    int *pa = &a;

    f_in_value(a,b,c);
    // = f(args...);
    // = f(a, b, c);
    // resolve f as f(int, int, int);

    f_in_address(a,b,c);
    // = f(&args...);
    // = f(&a, &b, &c);
    // resolve f as f(int*, int*, int*);

    f_in_address(pa, b, c);
    // = f(&args...);
    // = f(&pa, &b, &c);
    // resolve f as f(int**, int*, int*);

    return 0;
}

void f(int a, int b, int c)
{
    std::cout << "int pass by value" << std::endl;
    std::cout << "a: " << a << std::endl;
    std::cout << "b: " << b << std::endl;
    std::cout << "c: " << c << std::endl;
}

void f(int* pa, int* pb, int* pc)
{
    std::cout << "int pass by address" << std::endl;
    std::cout << "a: " << *pa << std::endl;
    std::cout << "b: " << *pb << std::endl;
    std::cout << "c: " << *pc << std::endl;
}

void f(int** ppa, int* pb, int* pc)
{
    std::cout << "int pass by (double_address, address, address)" << std::endl;
    std::cout << "a: " << **ppa << std::endl;
    std::cout << "b: " << *pb << std::endl;
    std::cout << "c: " << *pc << std::endl;
}
Output
> $ g++ -std=c++11 pack.cpp
> $ ./a.out
int pass by value
a: 1
b: 2
c: 3
int pass by address
a: 1
b: 2
c: 3
int pass by (double_address, address, address)
a: 1
b: 2
c: 3

C++ Parameter Pack 展開的簡單例子之二

comments powered by Disqus