Last active
September 18, 2018 07:12
-
-
Save sebbekarlsson/e98b1a37d102b6b3dbb22f82a3bf51cb to your computer and use it in GitHub Desktop.
C++ function that returns multiple types and multiple types as argument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
template <typename T> | |
T perform_operation(const T& left, std::string op, const T& right) { | |
if (op == "+") | |
return left + right; | |
if (op == "-") | |
return left - right; | |
} | |
std::string perform_operation(std::string left, std::string op, std::string right) { | |
if (op == "+") | |
return left + right; | |
return ""; | |
} | |
int perform_operation(int left, std::string op, int right) { | |
if (op == "+") | |
return left + right; | |
if (op == "-") | |
return left - right; | |
return 0; | |
} | |
float perform_operation(float left, std::string op, float right) { | |
if (op == "+") | |
return left + right; | |
if (op == "-") | |
return left - right; | |
return 0; | |
} | |
int main(int argc, char** argv) { | |
// supports strings | |
std::cout << perform_operation("hello", "+", " world") << std::endl; | |
// supports integers | |
std::cout << perform_operation(1, "+", 1) << std::endl; | |
std::cout << perform_operation(1, "-", 1) << std::endl; | |
// supports floats | |
std::cout << perform_operation(10.56, "-", 32.5) << std::endl; | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment