Example code I wish to implement:
// Below code doesn't work
consteval bool func2(const char* str) {
return str[0] == 'a';
}
// Error: ‘str’ is not a constant expression
bool func1(const char* str, bool flag) {
return flag && func2(str);
}
int main() {
bool flag = false;
std::cout << func1("abc", flag) << std::endl;
}
I can guarantee that func1's str parameter is always a string literal, so I want to handle it at compile-time.
For an int type, I know I can use a template parameter to realize that goal. But sadly, I can't handle string literals in the same way.
// Below code works
consteval bool func2(int num) {
return num == 1;
}
template <int N>
bool func1(bool flag) {
return flag && func2(N);
}
int main() {
bool flag = false;
std::cout << func1<1>(flag) << std::endl;
}
Is there a workaround for strings?
You can pass string literals to non-type template parameters in modern C++.
The syntax "hello"_ct can create such a "consteval" string objects, which internally has an array of 5 characters in it, and can be passed as a non-type template parameter.
That will let you use the same techniques you use for integers.
You can pass string literals to non-type template parameters in modern C++.
The syntax "hello"_ct can create such a "consteval" string objects, which internally has an array of 5 characters in it, and can be passed as a non-type template parameter.
That will let you use the same techniques you use for integers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With