Hello World
This commit is contained in:
parent
929ae9001d
commit
441d7c50d9
3 changed files with 133 additions and 36 deletions
61
cpp/C++.md
Normal file
61
cpp/C++.md
Normal file
|
@ -0,0 +1,61 @@
|
|||
## Template
|
||||
|
||||
Templates are a way to dynamically "generate" functions from a template that accept user-defined arguments. They can be used instead of overloading a function. Example:
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
// One function works for all data types. This would work
|
||||
// even for user defined types if operator '>' is overloaded
|
||||
// Type (i/d) Func Arg Arg
|
||||
template <typename T> T myMax(T x, T y)
|
||||
{
|
||||
return (x > y) ? x : y;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// Call myMax for int
|
||||
cout << myMax<int>(3, 7) << endl;
|
||||
// call myMax for double
|
||||
cout << myMax<double>(3.0, 7.0) << endl;
|
||||
// call myMax for char
|
||||
cout << myMax<char>('g', 'e') << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Source: https://www.geeksforgeeks.org/templates-cpp/
|
||||
|
||||
## Overloading functions
|
||||
|
||||
Overloading a function is a way to make a function execute different instructions when different types of arguments are passed using the same function name.
|
||||
|
||||
```cpp
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
void add(int a, int b)
|
||||
{
|
||||
cout << "sum = " << (a + b);
|
||||
}
|
||||
|
||||
void add(double a, double b)
|
||||
{
|
||||
cout << endl << "sum = " << (a + b);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
int main()
|
||||
{
|
||||
add(10, 2);
|
||||
add(5.3, 6.2);
|
||||
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Source: https://www.geeksforgeeks.org/function-overloading-c/
|
Loading…
Add table
Add a link
Reference in a new issue