为了代表国际象棋棋盘,我有一些便利constexpr
功能。为了记录易读的结果,我创建了一个函数,将两个表示形式的幂转换为const char*
我不确定使用constexpr const char*
函数返回字符串文字是否安全,下面是否有任何问题?据我所知,编译器会替换say:
::std::cout << "Before: " << typePrint(bounds())
使用:
::std::cout << "Before: " << "Bounds"
代码:
constexpr unsigned int bounds() { return 1; }
constexpr unsigned int nothing() { return 1 << 1; }
constexpr unsigned int bPawn() { return 1 << 2; }
constexpr unsigned int bRook() { return 1 << 3; }
constexpr unsigned int bKnight() { return 1 << 4; }
constexpr unsigned int bBishop() { return 1 << 5; }
constexpr unsigned int bQueen() { return 1 << 6; }
constexpr unsigned int bKing() { return 1 << 7; }
constexpr unsigned int wPawn() { return 1 << 8; }
constexpr unsigned int wRook() { return 1 << 9; }
constexpr unsigned int wKnight() { return 1 << 10; }
constexpr unsigned int wBishop() { return 1 << 11; }
constexpr unsigned int wQueen() { return 1 << 12; }
constexpr unsigned int wKing() { return 1 << 13; }
constexpr const char* typePrint(const unsigned int ac_type) {
return ac_type == bounds() ? "Bounds" :
ac_type == nothing() ? "Nothing" :
ac_type == bPawn() ? "Black Pawn" :
ac_type == bRook() ? "Black Rook" :
ac_type == bKnight() ? "Black Knight" :
ac_type == bBishop() ? "Black Bishop" :
ac_type == bQueen() ? "Black Queen" :
ac_type == bKing() ? "Black King" :
ac_type == wPawn() ? "White Pawn" :
ac_type == wRook() ? "White Rook" :
ac_type == wKnight() ? "White Knight" :
ac_type == wBishop() ? "White Bishop" :
ac_type == wQueen() ? "White Queen" :
ac_type == wKing() ? "White King" :
"Unknown";
}
编辑:引起我注意的是,执行以下操作是有效的C ++:
::std::cout << "Before: " "Bounds";
但是,返回constexpr
的{{1}}不是有效替代品,因此我认为编译器不会将const char*
替换为typePrint(bounds())
,以下是错误:< / p>
"Bounds"