lang/ifconsteval2.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

#include <iostream>
#include <string_view>

constexpr const char* foo()
{
  if consteval {
    return "compile-time";  // compile-time behavior
  }
  else {
    return "runtime";       // runtime behavior
  }
}

int main()
{
  std::string_view x = foo();            // runtime context
  constexpr std::string_view c = foo();  // compile-time context

  std::cout << "string_view:           " << x << '\n';
  std::cout << "constexpr string_view: " << c << '\n';

  static std::string_view sx = foo();    // compile-time context
  const std::string_view cx = foo();     // runtime context

  std::cout << "static string_view:    " << sx << '\n';
  std::cout << "const string_view:     " << cx << '\n';
}