cassert and templates

In Visual Studio, code that compiles outside an assert, does not compile inside an assert.

static_cast<_TupleVal<1, int>>(tup2).get() == 2

I am not sure why.

Could you show a complete minimal reproducible example?

And at the very least, what's the error message?

PS: Names with two underscores or underscore + capital letter are reserved for internal use everywhere, and should not be created by the end programmer.

Edit: Apologies Michael, I didn't realize that basically that line alone was enough to trigger the error.
Last edited on
assert is a function-like macro. Macros are expanded during the preprocessor stage and are not aware of all the C++ language rules with templates and stuff. It just treats the arguments as text and the comma as an argument separator.

1
2
assert(static_cast<_TupleVal<1, int>>(tup2).get() == 2);
// error: macro "assert" passed 2 arguments, but takes just 1 

It tries to pass static_cast<_TupleVal<1 as the first argument and int>>(tup2).get() == 2 as the second argument but that will obviously not work for several reasons.

To work around this you can put an extra pair of parentheses around the expression.

 
assert((static_cast<_TupleVal<1, int>>(tup2).get() == 2)); // OK 
Last edited on
Topic archived. No new replies allowed.