在C ++ 11中的懒惰 [英] Laziness in C++11

查看:231
本文介绍了在C ++ 11中的懒惰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道如何执行字符串的延迟评估,如下面的D代码片段:

  void log(lazy string msg){
static if(fooBarCondition)
writefln(...)/ * something with msg * /
}

其实,问题可能不需要懒惰,因为 static if。也许可以在不使用时舍弃 char const * 字符串?像C ++中一样:

  void log(char const * msg){
#ifdef DEBUG
cout << ...< endl; / * something with msg * /
#else / *根本没有* /
#endif
}

有什么想法吗?谢谢。

解决方案

  #ifdef DEBUG 
#define log(msg) do {cout< ...< endl; } while(0)
#else
#define log(msg)do {} while(0)
#endif

在C ++ 11中有两种实现延迟的方法:宏和lambda表达式。两者在技术上都不是懒惰,而是所谓的正常评价(相对于热切评价),这意味着表达式可以被评估任何次数。因此,如果您要将程序从D(或haskell)转换为C ++,则必须小心不要在这些表达式中使用具有副作用的表达式(包括计算时间)。



对于简单的日志记录,宏是很好的。

$ b

要实现真正的懒惰,你必须实现记忆,这不是那么简单。 $ b

Do you know how to perform a lazy evaluation of string, like in this D snippet:

void log(lazy string msg) {
  static if (fooBarCondition)
    writefln(…) /* something with msg */
}

Actually, the problem might not need laziness at all since the static if. Maybe it’s possible to discard char const* strings when not used? Like, in C++:

void log(char const *msg) {
  #ifdef DEBUG
  cout << … << endl; /* something with msg */
  #else /* nothing at all */
  #endif
}

Any idea? Thank you.

解决方案

#ifdef DEBUG
#define log(msg) do { cout << … << endl; } while(0)
#else
#define log(msg) do { } while(0)
#endif

There are two ways to achieve laziness in C++11: macros and lambda expressions. Both are not "lazy" technically, but what is called "normal evaluation" (as opposed to "eager evaluation"), which mean that an expression might be evaluated any number of times. So if you are translating a program from D (or haskell) to C++ you will have to be careful not to use expressions with side effects (including computation time) in these expressions.

To achieve true laziness, you will have to implement memoizing, which is not that simple.

For simple logging, macros are just fine.

这篇关于在C ++ 11中的懒惰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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