打印任意C ++表达式的类型 [英] Print types of arbitrary C++ expressions

查看:104
本文介绍了打印任意C ++表达式的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣为教学目的编写一个工具,用于评估C ++表达式并打印它们的类型。基本上,我的想法是,我的学生可以输入任何表达式,程序将回显表达式的类型。有没有一个现有的工具已经这样做?如果没有,是否有一个很容易的方法做到这一点,通过与现有的编译器集成并调用其调试器或API?我已经告诉,例如,Clang有一个相当完整的编译器API,也许有一些方法,只需传递一个字符串到Clang以及相应的include指令,并且它吐出一个类型?



我意识到这是一个巨大的项目,如果没有什么接近这存在今天。

解决方案

我想出了一个答案灵感来自Ben Voigt的评论。只是做一个错误,让编译器告诉你导致它的类型:

  template< typename T& void foo(T); //没有定义

int main(){
foo(1 + 3.0);
}

结果:

 在函数`main'中:
prog.cpp :( .text + 0x13):未定义的引用`void foo< double>(double)'



<因为你只执行编译器,所以你很安全。没有沙盒需要,真的。如果你得到除了未定义的引用 void foo< T>(T)以外的任何东西,它不是一个表达式。



你会如何把这个工具?简单,与宏

  // TestHarness.cpp 
//稍微变化,使其成为编译错误
模板< typename T> void foo(T){typename T :: bar t = T :: bar; }

int main(){
foo(EXPR);现在编译使用 $(CC)/ D =














< (EXPR)TestHarness.cpp
。保存您每次​​重建输入文件。


I'm interested in writing a tool for teaching purposes that evaluates C++ expressions and prints their types. Essentially, my thinking is that my students could type in any expression, and the program would echo back the type of the expression. Is there an existing tool that already does this? If not, is there a pretty easy way to do it by integrating with an existing compiler and calling into its debugger or API? I've been told, for example, that Clang has a fairly complete compiler API, perhaps there's some way to just pass a string into Clang along with the appropriate include directives and have it spit out a type?

I realize that this is potentially a huge project if there's nothing close to this existing today. I just thought it would have significant educational value, so it seemed like it was worth checking.

解决方案

I came up with an answer inspired by Ben Voigt's comments. Just make a bug and let the compiler tell you the type which caused it:

template <typename T> void foo(T); // No definition

int main() {
  foo(1 + 3.0);
}

Result:

In function `main':
prog.cpp:(.text+0x13): undefined reference to `void foo<double>(double)'

Also, since you execute nothing but the compiler, you're pretty safe. No sandboxing needed, really. If you get anything other than "undefined reference to void foo<T>(T)", it wasn't an expression.

[edit] How would you put this into a tool? Simple, with macro's

// TestHarness.cpp
// Slight variation to make it a compile error
template <typename T> void foo(T) { typename T::bar t = T::bar ; }

int main() {
  foo(EXPR);
}

Now compile with $(CC) /D=(EXPR) TestHarness.cpp. Saves you from rebuilding the input file every time.

这篇关于打印任意C ++表达式的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆