Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic_cast in assert Causing Error

I'm using the antiquated Visual Studio 2008 (let me save you the trouble "there's your problem".) This seems to be a problem with Visual Studio: http://rextester.com/XKFR77690 This seems to be a problem with the assert macro: http://ideone.com/bhxMi0

Given these structs:

struct base { virtual ~base() {} };

template <typename T>
struct Foo : base { T foo; };

I can do this:

base* test = new Foo<pair<int, int>>;

if(dynamic_cast<Foo<pair<int, int>>*>(test) != NULL) cout << "hello world\n";

But when I use the exact same code as is in the if-statement in an assert: assert(dynamic_cast<Foo<pair<int, int>>*>(test) != NULL) I get an error:

warning C4002: too many actual parameters for macro assert
error C2143: syntax error : missing ',' before ')'

Incidentally I can fix this by using a C-style cast: assert((Foo<pair<int, int>>*)(test) != NULL) But I think that the C-Style cast will do a static_cast not a dynamic_cast which I don't want.

like image 406
Jonathan Mee Avatar asked Nov 02 '16 15:11

Jonathan Mee


1 Answers

Yup: macros treat top-level commas as argument separators. The simplest fix is to put parentheses around the offending code:

assert((dynamic_cast<Foo<pair<int, int>>*>(test)) != NULL)

or, if you prefer, parentheses around the entire content:

assert((dynamic_cast<Foo<pair<int, int>>*>(test) != NULL))

The reason the C-style cast in the question compiles is not that it's a C-style cast, but that it puts the template code in parentheses, so the comma is no longer at the outermost level.

like image 177
Pete Becker Avatar answered Oct 07 '22 14:10

Pete Becker