Created
September 23, 2018 23:41
-
-
Save yshui/c6f21e37397e56e0e957b8dc9f75156b to your computer and use it in GitHub Desktop.
C++ template parameter deduction based on return type
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
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