写点C++ user defined literals的奇怪(正常)用途

 

之前写的围棋程序的测试中,我们常常需要vector< { Player, Point } > pieceToPlace。问题在于,如果我们硬编码这个vector,可读性很差:

pieceToPlace.emplace_back(Player::B, make_pair(2, 3));
pieceToPlace.emplace_back(Player::B, make_pair(2, 1));
pieceToPlace.emplace_back(Player::W, make_pair(1, 0));

通过User defined literal,我们可以做到这样:

 auto placeVec = getInput({
    {O,   1_B,   2_W,   4_W},
    {6_W, 3_B,   5_B,   7_W},
    {O,   O,     O,     8_B},
    {9_W, O,     O,     O}
});
for (auto &ele : placeVec) 
{
    cout << (ele.player == Player::B ? "B" : "W") << " " << ele.point.first << "," << ele.point.second << endl; 
}
/*
B 0,1
W 0,2
B 1,1
W 0,3
B 1,2
W 1,0
W 1,3
B 2,3
W 3,0
*/

代码:

 

 

发表评论