ybw
V2EX  ›  C++

c++有能力实现编译时的 int 对字符串翻译表吗?

  •  
  •   ybw · Mar 20, 2020 via Android · 1723 views
    This topic created in 2288 days ago, the information mentioned may be changed or developed.

    关键词: 编译时,非运行时

    9 replies    2020-03-21 20:49:51 +08:00
    Caturra
        1
    Caturra  
       Mar 20, 2020
    constexpr ?
    ipwx
        2
    ipwx  
       Mar 21, 2020
    std::string 永远要在对上分配内存,而对上分配永远是运行时的。所以,你的需求不可能实现 。
    ipwx
        3
    ipwx  
       Mar 21, 2020
    对 => 堆
    ysc3839
        4
    ysc3839  
       Mar 21, 2020 via Android
    “int 对字符串翻译表”指的是什么呢?
    ybw
        5
    ybw  
    OP
       Mar 21, 2020 via Android
    @ipwx 谁说 std::string 了,字符串字面值,就是分配在静态存储区的。
    ybw
        6
    ybw  
    OP
       Mar 21, 2020 via Android
    @ysc3839 类似于 std::map<int, string>。不过是编译时而不是运行时。
    ipwx
        7
    ipwx  
       Mar 21, 2020
    @ybw 行吧,那就是 const char*。

    但是 int 值域那么大,你打算生成多少容量的翻译表?写一个运行时的 formatInt 也不耗时啊。经济一点,你可以把 0~255,-1,-2 这种常用值的翻译表静态化,剩下的运行时生成不就行了?

    如果是有限数量的静态翻译表,写个 python 程序生成一个 const char*[] 不就可以了?
    ybw
        8
    ybw  
    OP
       Mar 21, 2020 via Android
    @ipwx 这和我的问题无关。
    ysc3839
        9
    ysc3839  
       Mar 21, 2020
    @ybw 可以,随手搜了一下就搜到了 https://github.com/mapbox/eternal

    下面是测试代码和编译结果
    https://godbolt.org/z/z2orb6
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   899 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 20:39 · PVG 04:39 · LAX 13:39 · JFK 16:39
    ♥ Do have faith in what you're doing.