C++ 11 可變模板參數的兩種展開方式


#include <iostream>
#include <string>
#include <stdint.h>

template<typename T>
T Sum(T t)
{
    std::cout << t << " = ";
    return t;
}
template<typename T, typename... Args>
T Sum(T head, Args...args)
{
    std::cout << head << " + ";
    return head + Sum(args...);
}


template<typename T>
void PrintArg(T t)
{
    std::cout << t << " ";
}
template<typename... Args>
void Expand(Args... args)
{
    std::initializer_list<int32_t> {(PrintArg(args), 0)...};
    std::cout << std::endl;
}

int32_t main()
{
    std::cout << Sum(1, 2, 3, 4) << std::endl;
    Expand(1, 2, 3, 4);
    std::cin.get();
    return 0;
}

效果:

1 + 2 + 3 + 4 = 10
1 2 3 4

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM