是否可以在编译时将字符串转换为大写而不受任何大小限制?
例如:
char* myString = TO_UPPERCASE("a big string here!");
会产生:
char* myString = "A BIG STRING HERE!";
最佳答案
有可能,使用Boost.Hana和 C++14。
#include <iostream>
#include <boost/hana/unpack.hpp>
#include <boost/hana/string.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/value.hpp>
#include <boost/hana/core/to.hpp>
constexpr char to_upper(char c) noexcept
{
switch(c) {
default: return c;
case 'b': return 'B';
case 'i': return 'I';
case 'g': return 'G';
case 's': return 'S';
case 't': return 'T';
case 'r': return 'R';
case 'n': return 'N';
// The other characters in the alphabet.
}
}
auto to_upper_str = [](auto hana_str) noexcept {
return boost::hana::unpack(hana_str, [](auto... chars) noexcept {
return boost::hana::string_c<
boost::hana::char_c<to_upper(boost::hana::value(chars))>...>;
});
};
int main()
{
auto str = to_upper_str(BOOST_HANA_STRING("Big string."));
std::cout << boost::hana::to<const char*>(str) << '\n';
}
这会输出 BIG STRING。
请参阅 Coliru .
关于c++ - 在编译时将字符串转换为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40945727/