ここでの’厨’の定義
- それをつかえる隙があればどこでもつかってしまう
- 釘を打つためのハンマーなのに、ハンマーもったらすべて釘にみえてしまう
- やらないほうがいいとわかっていても、やってしまう
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");
おぼえるのは時間のラ無駄ァ!