The solution is, quite simply, not to do this.
A macro cannot work with values presented minutes, hours, days, years, potentially decades later. A macro is resolved before compilation, and before compilation there is no way of knowing what value id
holds. During compilation sort of but even then it gets complicated unless the initialiser is trivial and the variable's value can never change.
Instead, use a function:
#include
#include
int channel(const int id)
{
// Your own rules here; we don't know enough about them to know.
// Perhaps instead of a switch, a map. It depends.
switch (id)
{
case 1: return 10;
default: throw std::out_of_range("Dammit");
}
}
int main()
{
int id = 1;
std::cout << channel(id) << '\n';
}
Again, you can make it work at compile-time if id
is known at compile-time, and indicated as such using the keyword constexpr
:
#include
#include
template
int channel()
{
// Perhaps instead of a switch, a sequence of 'if constexpr' and
// a static_assert(false) at the end.
switch (id)
{
case 1: return 10;
default: throw std::out_of_range("Rats");
}
}
int main()
{
constexpr int id = 1;
std::cout << channel() << '\n';
}
If neither approach is acceptable, then you must rework your requirements.
But, without knowing what those requirements actually are, we cannot help you to do that.