【问题标题】:how to pass a constexpr string literal to other function如何将 constexpr 字符串文字传递给其他函数
【发布时间】:2020-10-21 08:35:39
【问题描述】:

使用以下两个函数,它们往往会在编译时获取字符串文字的长度。第一个不会编译,虽然例子没有意义,但是我实际上需要使用getlen内的字符串长度作为编译时常量,我该怎么做? p>

// compile failed with "expression did not evaluate to a constant" in vs2019 std=latest
// failure was caused by a read of a variable outside its lifetime
// see usage of 's'
constexpr auto getlen(const char* s) {
    constexpr auto size = std::char_traits<char>::length(s);
    return size;
}

constexpr auto getlen2(const char* s){
    return std::char_traits<char>::length(s);
}

int main() {
    constexpr size = getlen2("suprise!") // size is 8
    return 0;
}

第二个函数显示getlen2的返回确实是一个constexpr,所以一定是s。这怎么解释?

【问题讨论】:

    标签: c++ constexpr


    【解决方案1】:

    这是因为constexpr 函数也可以在运行时调用,但getlen 的实现只有在编译时调用才有意义:

    constexpr auto getlen(const char* s) {
        constexpr auto size = std::char_traits<char>::length(s);
        return size;
    }
    

    在以下上下文中,很明显size 不能是constexpr

    int main(int argc, char** argv)
    {
        (void) getlen(argv[0]);
    }
    

    如果您需要您的函数只能在编译时调用,您可能对consteval 感兴趣。

    【讨论】:

    • 所以一般来说,这意味着我不能调用其他函数并在后面的其他表达式中使用不是 constexpr 的返回值?
    • @zoujyjs 不明白你的意思,介意举个例子吗?
    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多