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

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

pack2.cpp
#include <iostream>

void print(std::ostream& out)
{
    out << std::endl;
}

template<typename T, typename... ArgsT>
void print(std::ostream& out, const T& value, ArgsT... args)
{
    out << value;
    print(out, args...);
}

int main()
{
    print(std::cout, "Hello world.", " Today is ", 12, '/', 8, ".");
    // = print(std::cout, "Hello world", args...) {
    //      out << "Hello world";
    //      print(out, args...); 
    //      // in place expands to print(out, " Today is ", 12, '/', 8, "."); 
    //      // resolves print(std::ostream&, const T&, ArgsT...)
    //   }
    // = {
    //      out << "Hello world";
    //      out << " Today is ";
    //      print(out, args...); 
    //      // in place expands to print(out, 12, '/', 8, ".");
    //      // resolves print(std::ostream&, const T&, ArgsT...)
    //   }
    // = {
    //      out << "Hello world";
    //      out << " Today is ";
    //      out << 12;
    //      print(out, args...); 
    //      // in place expands to print(out, '/', 8, ".");
    //      // resolves print(std::ostream&, const T&, ArgsT...)
    //   }
    // = {
    //      out << "Hello world";
    //      out << " Today is ";
    //      out << 12;
    //      out << '/';
    //      print(out, args...); 
    //      // in place expands to print(out, 8, ".");
    //      // resolves print(std::ostream&, const T&, ArgsT...)
    //   }
    // = {
    //      out << "Hello world";
    //      out << " Today is ";
    //      out << 12;
    //      out << '/';
    //      out << 8;
    //      print(out, args...); 
    //      // in place expands to print(out, ".");
    //      // resolves print(std::ostream&, const T&, ArgsT...)
    //   }
    // = {
    //      out << "Hello world";
    //      out << " Today is ";
    //      out << 12;
    //      out << '/';
    //      out << 8;
    //      out << ".";
    //      print(out, args...);  // args is zero-args
    //      // in place expands to print(out);
    //      // resolves print(std::ostream&)
    //   }
    // = {
    //      out << "Hello world";
    //      out << " Today is ";
    //      out << 12;
    //      out << '/';
    //      out << 8;
    //      out << ".";
    //      out << std::endl; // calls the print(std::ostream&);
    //   }
    return 0;
}
Output
> $ g++ -std=c++11 pack2.cpp
> $ ./a.out
Hello world. Today is 12/8.
comments powered by Disqus