c++ - 断言中的 dynamic_cast 导致错误

标签 c++ visual-studio gcc assert dynamic-cast

我正在使用过时的 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/

相关文章:

c - 切换编译器和 IDE 后在 C 中位打包结构的语法错误

c++ - 如何将地址转换为 GDB 中的特定类型变量?

c++ - qt 读取就绪信号

c++ - 在 C++ 中读取格式化数据的最简单/最清晰的方法

C++17 不能使用 std::bind 生成 std​​::function

visual-studio - Eclipse:改进调试并在mouseOver上显示变量值

c++ - 在 apache qpid 中如何列出经纪人状态?

c# - 在 Visual Studio 2010 中启用 C# 项目

c++ - 如何查找与包含相关的问题 - 可视化包含树

c - c程序中的段错误