Literals don't seem to interplay well with preprocessor macros. For example, I have this preprocessor definition CONFIG_FADE_DELAY_MS that I want to translate to std::chrono::milliseconds. But the ms literal needs to be written close up to it, the the compiler doesn't understand ms when there is a space in between them.
#include <cstdio>
#include <chrono>
#define CONFIG_FADE_DELAY_MS 5000
using namespace std::chrono_literals;
int main()
{
// Works
// const auto tp_now = std::chrono::system_clock::now() + 5000ms;
// Doesn't work
const auto tp_now = std::chrono::system_clock::now() + CONFIG_FADE_DELAY_MS ms;
}
I also tried to put parentheses around the preprocessor macro, and put the literal right behind it, but no luck.
Can this be done, or do I need to convert the macro manually?
std::chrono::milliseconds{CONFIG_FADE_DELAY_MS};
You can use the preprocessor's
##token concatenation operator to join the5000andmstokens, eg:Demo
The indirection of
CONCAT()callingCONCAT2()is required in order for the preprocessor to first translateCONFIG_FADE_DELAY_MSto5000before then concatenatingmsonto it. If you tried to use simply#define CONCAT(a, b) a ## bthen the result would not be5000msas expected but rather would beCONFIG_FADE_DELAY_MSmsinstead, which will obviously fail to compile sinceCONFIG_FADE_DELAY_MSmsis not defined anywhere.