搜尋此網誌

2025年11月23日星期日

Template in C++

instantiate: represent as or by an instance

Compile-time polymorphism in C++ (also called static polymorphism or early binding) is achieved mainly through function overloading and operator overloading. The compiler decides which function or operator to invoke at compile time, based on the arguments provided.

Function Overloading: Multiple functions with the same name but different parameter lists.

Operator Overloading: Redefining operators (like +, ==, etc.) to work with user-defined types.

Difference from Runtime Polymorphism: Runtime polymorphism uses virtual functions and dynamic binding, where the decision is made at execution time. Compile-time polymorphism is faster because it avoids the overhead of dynamic dispatch.

#include <iostream>
using namespace std;

void greet(string name) {   // parameter
    cout << "Hello, " << name << "!" << endl;
}

int main() {
    greet("Alice");  // argument
    greet("Bob");
    return 0;
}

In C++, a template is a feature that allows you to write generic code that works with any data type. Instead of duplicating functions or classes for different types (like int, double, or string), you can define a template once and let the compiler generate the appropriate version when needed.

In C++ templates, the angle brackets (< >) are used to specify the template arguments when instantiating a template. They tell the compiler which data type (or constant value, in case of non-type parameters) should be substituted into the generic template definition.

Microsoft Copilot

沒有留言:

發佈留言