宏何时可以使代码比函数更美观? [英] When could macro make code more beautiful than function does?

查看:78
本文介绍了宏何时可以使代码比函数更美观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确实,对于编程语言而言,宏不是必需的.例如,Java在没有宏的情况下工作得很好.通常,宏会使代码更清晰,更短,同时也更危险.

Exactly, macro is not necessary for programming languages. For example, Java works quite fine without macro. Usually macro makes code more clear and shorter, at the same time, more dangerous.

那么,使用宏的最佳方法是什么? 让我们谈谈代码.

So, what's the best way to use macro? Let's talk in code.

推荐答案

我仅在其他无效的地方使用宏.

I use macros only in places where nothing else works.

一个例子是从错误值到字符串的简单映射,例如代替

One example is having an easy mapping from error values to strings, for example instead of

switch(code) {
    case ERR_OK: return "ERR_OK";
    case ERR_FOO: return "ERR_FOO";
    :

我使用一个简单的宏,例如

I use a simple macro like

#define CASE_STR(x) case x: return #x

所以我可以简化为

switch(code) {
    CASE_STR(ERR_OK);
    CASE_STR(ERR_FOO);
    :

但是,这些情况通常更多用于调试.

However, those cases are usually more for debugging.

此外,我使用boost预处理器套件编写了GLSL(OpenGL着色语言)循环展开一次,然后可以使用类似的

Also, I've written a GLSL (OpenGL Shading Language) loop unrolling once using the boost preprocessor suite, which then could be used something like

const char *shader = "#version 120\n"
"..."
GLSL_UNROLL_FOR("int i",0,10,\
    "foo += i\n" \
)
"...";

这篇关于宏何时可以使代码比函数更美观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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