Created
October 4, 2016 08:37
-
-
Save sighingnow/dee20f965881605095cf8baa02edbd2e to your computer and use it in GitHub Desktop.
When two type parameters are different, how to choose a proper return type in C++ ?
This file contains hidden or 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> | |
#include <typeinfo> | |
template<typename T, typename S> | |
auto max(T a, S b) -> decltype(a+b) { // note that T and S may be different. | |
// for numeric type, automatic type convension will be performed when compare two values. | |
if (a > b) { | |
return a; | |
} | |
else { | |
return b; | |
} | |
} | |
int main() { | |
short a = 1; | |
int b = 2; | |
double c = 3; | |
std::cout << typeid(max(a, b)).name() << std::endl; // print "i", return type: int | |
std::cout << typeid(max(b, c)).name() << std::endl; // print "d", return type: double | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment