Function overloading in C++
One name, three signatures: the compiler picks the right twice from the argument type alone.
#include <string>
// One name, three signatures: the compiler picks by argument type.
int twice(int n) { return n * 2; }
double twice(double x) { return x * 2.0; }
std::string twice(const std::string& s) { return s + s; }
int overload_demo() {
int a = twice(21);
double b = twice(1.5);
std::string c = twice(std::string("echo"));
return a + static_cast<int>(b) + static_cast<int>(c.size());
}
How it works
- Three
twicefunctions share a name but differ in parameter type:int,double, andstd::string. twice(21)binds to theintversion andtwice(1.5)to thedoubleone, with no casts or renames.- The
std::stringoverload concatenates instead of multiplying;static_castfolds the results into oneint.
Keywords and builtins used here
constdoubleintoverload_demoreturnstatic_casttwice
The run, in numbers
- Lines
- 13
- Characters to type
- 394
- Tokens
- 115
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 92 seconds.
Step 1 of 3 in Functions & lambdas, step 10 of 27 in Language basics.