最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Is there any way to mark a function paramter as constexpr? - Stack Overflow

programmeradmin4浏览0评论

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;
}
发布评论

评论列表(0)

  1. 暂无评论