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 gurantee func1
's str
parameter is always a string literals, so i want to handle it in compile time.
For int
type, I know I can use template paramter to realize that goal. But sadly, I can't handle string literals in the same way. Is there a workaround?
// 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;
}