Reputation: 1794
I want to implement a function some similar to verify
in Unreal 4, where if some expression is not true, print the tag and some variable used in the expression.
Here is a case:
int x = ...;
long y = ...;
Verify( x > y, "check-range", x, y);
Verify( y < INT_MAX, "check-range:y", x, y, INT_MAX);
The solution I supposed was bellowing function Verify
, and I want to join all the paramters to one string in macro GET_STRING_FROM_PARAMETERS
. But I didn't figure out the way how to pass varadic paramters to macro from a templated function.
Here is the code:
#define GET_STRING_FROM_PARAMETERS(...) \
do { \
if (...) { \
something to be done \
} \
} while (false)
template <typename... Ts>
constexpr void Verify(bool expression, const std::string &tag, Ts &&... rest) noexcept {
if (!expression) {
std::cout << tag << " " << GET_STRING_FROM_PARAMETERS(rest...);
}
}
Upvotes: 0
Views: 185
Reputation: 14589
Your code will not compile for multiple reasons. You are using macro a a function while it's containing a while statement, you're passing parameter pack directly to it, parameter pack can't be used like that in loop.
You can't pass parameter pack to macro because preprocessing happens before compiling code. Macro definitions are not aware of templates. You have to use a trick to maintain proper syntax:
#define PARAMETER_PACK(x) x...
#define SOME_OTHER_MACRO(x) auto lm = \
[&, PARAMETER_PACK(x)] { return foo(PARAMETER_PACK(x)); }
SOME_OTHER_MACRO(Args);
The ellipsis cannot be part of argument list for functional macro. It can be a part of expression within that list, so you also can do this in some cases:
#define SOME_OTHER_MACRO(x) g x;
SOME_OTHER_MACRO((Args ...));
It's a limited and weird way in both cases, preferably do not use macrodefinitions in such templates at all. Use smaller auxiliary templates if you must.
Upvotes: 2