C++核心準則F.50:不願意使用函數時使用lambda表達式

C++核心準則F.50:不願意使用函數時使用lambda表達式

F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)

F.50:在不願意使用函數時使用lambda表達式(例如讀取局部變量,訪問局部函數)

Reason(原因)

Functions can't capture local variables or be defined at local scope; if you need those things, prefer a lambda where possible, and a handwritten function object where not. On the other hand, lambdas and function objects don't overload; if you need to overload, prefer a function (the workarounds to make lambdas overload are ornate). If either will work, prefer writing a function; use the simplest tool necessary.

函數無法使用函數體外部的局部變量,也不能定義在局部作用域;如果你需要這方面功能,如果可能的話使用lambda表達式是較好的選擇,否則需要自己實現函數對象。另一方面,lambda表達式和函數對象無法實現重載;如果你需要重載,函數更合適(通過折騰讓lambda表達式重載的方法太高級)。如果兩種方式都可用,用函數更好;使用滿足需要的,最簡單的工具。

Example(示例)

// writing a function that should only take an int or a string
// -- overloading is natural
void f(int);
void f(const string&);
// writing a function object that needs to capture local state and appear
// at statement or expression scope -- a lambda is natural
vector<work> v = lots_of_work();
for (int tasknum = 0; tasknum < max; ++tasknum) {
pool.run([=, &v]{

/*
...
... process 1 / max - th of v, the tasknum - th chunk
...
*/
});
}
pool.join();/<work>

Exception(例外)

Generic lambdas offer a concise way to write function templates and so can be useful even when a normal function template would do equally well with a little more syntax. This advantage will probably disappear in the future once all functions gain the ability to have Concept parameters.

通常的lambda表達式提供一種實現函數模板的簡明方式,因此很有用;一個普通的函數模板想要做相同的事情甚至需要稍微複雜的語法。但是將來一旦所有的函數都可以擁有概念參數,這個優勢將來很可能會消失。

譯者注:Concept是C++20將會導入的新特性。

Enforcement(實施建議)

  • Warn on use of a named non-generic lambda (e.g., auto x = [](int i){ /*...*/; };) that captures nothing and appears at global scope. Write an ordinary function instead.在使用了一個沒有獲取任何變量而且存在於全局作用域的、命名的非普通lambda表達式(例如auto x=[](int){/*...*/};)時報警。

覺得本文有幫助?請分享給更多人。

面向對象設計,面向對象編程,面向對象思考!


分享到:


相關文章: