I\'m looking for a way to simulate certain overloaded GCC built-ins in C++. The built-ins are similar to these:
__builtin_foo(char *a, signed int b);
__buil
Here is a portable C++11 solution so that your function (macro actually, sorry) accepts only integer literals and triggers a compile-time error instead:
constexpr int operator "" _literal(unsigned long long i)
{
return i;
}
#define m_builtin_foo(integer) builtin_foo(integer ## _literal)
User-defined literals accept only literals (hence their name). Therefore, if you make your macro paste a user-defined literal to what is passed to it, it should only accept the literals accepted by the corresponding user-defined literal.
However, that's rather ugly and I guess that could be error-prone. Not sure how though.
@MichaelAnderson pointed in the comments that m_builtin_foo(i+1) would still work. That's right. @Angew suggested wrapping the return type of _literal in a wrapper incompatible with integer arithmetic and adding explicit conversions. He was also right, here is the more complete solution:
struct wrapper
{
constexpr wrapper(int n):
value{n}
{}
explicit constexpr operator int() const
{
return value;
}
int value;
};
constexpr wrapper operator "" _literal(unsigned long long i)
{
return { int(i) };
}
#define m_builtin_foo(integer) builtin_foo(int(integer ## _literal))