Skip to content

Instantly share code, notes, and snippets.

@yshui
Created September 23, 2018 23:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yshui/c6f21e37397e56e0e957b8dc9f75156b to your computer and use it in GitHub Desktop.
Save yshui/c6f21e37397e56e0e957b8dc9f75156b to your computer and use it in GitHub Desktop.
C++ template parameter deduction based on return type
struct Fun {
// Gadget used for return type based deduction
// operator T() is probably the only place in C++
// where the template parameter can be deduced from
// what the function should return
template<typename T>
operator T() {
return T(sizeof(T));
}
};
struct Z {
int a,b,c,d;
Z(unsigned long x) : a(x) {
}
};
auto fun() {
return Fun();
}
int main() {
Z x = fun(); // 16
unsigned long y = fun(); // 8 (sizeof(unsigned long))
int z = fun(); // 4 (sizeof(int))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment