4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

lambda厨。または暴走lambda。

Last updated at Posted at 2015-08-14

ここでの’厨’の定義

  • それをつかえる隙があればどこでもつかってしまう
  • 釘を打つためのハンマーなのに、ハンマーもったらすべて釘にみえてしまう
  • やらないほうがいいとわかっていても、やってしまう

lambdaさえつかえればなんでもよかった

一時変数をどんな場合でもconst化するためにやった

before
int score = 0;
// Rank が100なら10
if ( Rank == 100 ) {
  score = 10;
}
// 50~99なら5
else if( Rank < 100 && Rank >= 50 ) {
  score = 5;
}
else {
  score = 1;
}
return score;
lambdar
const int score = [Rank]() {
  if ( Rank == 100 ) {
    return 10;
  }
  else if( Rank < 100 && Rank >= 50 ) {
    return 5;
  }
  return 1;
}();
return score;


// または、、、

return [Rank]() {
  if ( Rank == 100 ) {
    return 10;
  }
  else if( Rank < 100 && Rank >= 50 ) {
    return 5;
  }
  return 1;
}();

外部から振るまいを変えたくてやった

before
class JibaNyan
{
public:
  void Say() { cout << "ジバニャンだニャイーン!" << endl; }
  YokaiType Type() { return YokaiType::Purichie; }
}

class RoboNyan
{
public:
  void Say() { cout << "ロボニャンだ!" << endl; }
  YokaiType Type() { return YokaiType::Goketsu; }
};
lambdar
# include <functional>
typedef std::function<void()> SayFunction;
typedef std::function<YokaiType()> TypeFunction;

class Yokai
{
public:
  Yokai( SayFunction say, TypeFunction type)
  : _say(say), _type(type) {}
  void Say() { _say(); }
  YokaiType Type() { return _type(); }

private:
  SayFunction _say;
  TypeFunction _type;
}

void usecase
{
  Yokai J([](){ cout << "にゃいーん!"; }, [](){ return YokaiType::Prichie; });
  J.Say();  // にゃいーん!

  Yokai R([](){ cout << "I'll be back!"; }, [](){ return YokaiType::Goketsu; });
  R.Type();  // YokaiType::Goketsu
}

CString::FormatがMutableすぎたからやった

before
CString hello;
hello.Format("わたしの名前は%sです", name);

// ...helloに関係ないなにか

hello = "";  // 消える!
lambdar
const CString hello = [name]() {
  CString fmt;
  fmt.Format("わたしの名前は%sです", name);
  return fmt;
}();

// ...helloに関係ないなにか

hello = "";  // error!!
lambdar_case2
const auto MyNameIs = [](LPCTSTR name) {
  CString fmt;
  fmt.Format("わたしの名前は%sです", name);
  return fmt;
};

const CString hiroshi_say = MyNameIs("Hiroshi");
const CString masa_say = MyNameIs("Masa");

おぼえるのは時間のラ無駄ァ!

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?