Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to mark a function parameter as constexpr?

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?

like image 421
Redim Avatar asked Oct 25 '25 06:10

Redim


2 Answers

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.

like image 87
Yakk - Adam Nevraumont Avatar answered Oct 26 '25 19:10

Yakk - Adam Nevraumont


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.

like image 39
Yakk - Adam Nevraumont Avatar answered Oct 26 '25 18:10

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!