c++ - 在编译时将字符串转换为大写

标签 c++ macros metaprogramming

是否可以在编译时将字符串转换为大写而不受任何大小限制?

例如:

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/

相关文章:

c++ - 模板元编程是否比等效的 C 代码更快?

Java动态方法创建

c++ - 如何将 std::vector 中的元素移动 1?

c++ - JAutodoc 类 C++ 插件

python - Python 中的纯静态类 - 使用元类、类装饰器还是其他东西?

c++ - 元编程 C/C++ : how can I avoid using macros here?

c - 用于抽象的预处理器宏 - 良好实践?

c++ - -Wlifetime 标志的目的是什么?

c++ - Makefile 编译内核模块以包含树源文件

c++ - 用于重复代码的 C/C++ 宏