Is there a way in c++ to get a different overload called based on the runtime/compile time constness of an input? My version(12) of MSVC can't do this using constexpr. Reading c++ documentation, I am not sure if this is the way constexpr works.
inline int Flip4(constexpr int n) {
return ((n & 0xFF) << 24) | ((n & 0xFF00) << 8) | ((n & 0xFF0000) >> 8) | ((n & 0xFF000000) >> 24);
}
inline int Flip4(int n) {
return _byteswap_ulong(n);
}
int main(int argc, char* argv[]) {
int a = Flip4('abcd'); // calc at compile time
int b = Flip4(argc); // calc at runtime
}
So if this can be done, how? I think there might be a way to use template deduction to do it, but I can't figure out how.
EDIT
I came up with this, but am not sure why it works, && is still fuzy for me, and not sure if this works for everything.
template<class T> typename std::enable_if<std::is_arithmetic<T>::value, int>::type
inline Flip4(T&& n) {
//cout << "compile time" << endl;
return ((n & 0xFF) << 24) | ((n & 0xFF00) << 8) | ((n & 0xFF0000) >> 8) | ((n & 0xFF000000) >> 24);
}
template<class T> typename std::enable_if<!std::is_arithmetic<T>::value, int>::type
inline Flip4(T&& n) {
//cout << "run time" << endl;
return _byteswap_ulong(n);
}
int main(int argc, char* argv[]) {
int n = Flip4(argc);
n += Flip4(1);
return n;
}
If you compile without commenting out the output, it produces this output.
run time
compile time
and it produces this assembly, which is what I want:
int n = Flip4(argc);
000000013FA11270 bswap ecx
n += Flip4(1);
000000013FA11272 lea eax,[rcx+1000000h]
Are there cases of integer T where this won't work?