简体   繁体   中英

how to pass a constexpr string literal to other function

With the following two functions which is tend to get the length of a string literal at compile time. The first one won't compile, though the example is meaningless, but I actually need to use the string length inside the getlen as a compile-time constant, how can I do that?

// 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;
}

The second function shows that the returns of getlen2 is indeed a constexpr, so must be the s . How to explain this?

That's because a constexpr function can also be called at runtime, but the implementation of getlen makes only sense when called at compile-time:

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

In the following context, it is clear size cannot be a constexpr :

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

If you need your function to only be callable at compile-time, you might be interested in consteval .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM