Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Template hàm variadic (tham số biến đổi) trong C++


Variadic function template cho phép hàm nhận số lượng tham số tùy ý. Cú pháp dùng typename... Args (parameter pack).

Cú pháp

template<typename T, typename... Args>
return_type ten_ham(T first, Args... rest)

Ví dụ minh họa

#include <iostream>
using namespace std;

void show() { cout << "Het tham so\n"; } // trường hợp cơ sở

template<typename T, typename... Args>
void show(T first, Args... rest) {
    cout << first << endl;
    show(rest...); // đệ quy giải nén parameter pack
}

int main() {
    show(7, 6, 0.04, "hi", "I am variadic", "function\n");
    return 0;
}

Kết quả

7
6
0.04
hi
I am variadic
function
Het tham so