我正在使用过时的 Visual Studio 2008(让我为您省去“这是您的问题”的麻烦。)这似乎是 Visual Studio 的问题:http://rextester.com/XKFR77690 这似乎是 assert
的问题宏:http://ideone.com/bhxMi0
给定这些结构:
struct base { virtual ~base() {} };
template <typename T>
struct Foo : base { T foo; };
我能做到:
base* test = new Foo<pair<int, int>>;
if(dynamic_cast<Foo<pair<int, int>>*>(test) != NULL) cout << "hello world\n";
但是当我使用与 if
中完全相同的代码时-assert
中的声明: assert(dynamic_cast<Foo<pair<int, int>>*>(test) != NULL)
我得到一个错误:
warning C4002: too many actual parameters for macro
assert
error C2143: syntax error : missing ',' before ')'
顺便说一句,我可以使用 C 风格的转换来解决这个问题:assert((Foo<pair<int, int>>*)(test) != NULL)
但我认为 C-Style Actor 会做一个 static_cast
不是dynamic_cast
我不想要。
最佳答案
assert
是一个宏。它由对 C++ 构造一无所知的预处理器处理。所以如下:
assert(dynamic_cast<Foo<pair<int, int>>*>(test) != NULL)
扩展为一个带有两个参数的类似函数的宏,在本例中为:
dynamic_cast<Foo<pair<int
和
int>>*>(test) != NULL
请记住,类似函数的宏参数由逗号分隔。这就是预处理器看到的所有内容。所以在这种情况下,它看到 2 个参数,而不是 assert
所需的 1 个参数。
由于括号的优先级高于逗号,您的 C 风格强制转换版本可以正常工作。将它们放在 dynamic_cast
周围也可以完成这项工作。
关于c++ - 断言中的 dynamic_cast 导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384192/