Skip to content

Instantly share code, notes, and snippets.

@sighingnow
Created October 4, 2016 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sighingnow/dee20f965881605095cf8baa02edbd2e to your computer and use it in GitHub Desktop.
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++ ?
#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