Skip to content

Instantly share code, notes, and snippets.

@Nekotekina
Last active September 8, 2019 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nekotekina/4bc7fde16fea8e461f4e10313da1b9b6 to your computer and use it in GitHub Desktop.
Save Nekotekina/4bc7fde16fea8e461f4e10313da1b9b6 to your computer and use it in GitHub Desktop.
Operator consteval(), constexpr function argument, and constexpr NSDM

Proposal

void foo(constexpr int x)
{
  // foo() is a function template with a hidden invented template parameter naming a unique type
  if constexpr ( consteval(x) )
  {
    // Should be legal in this scope
    std::bitset<x> z;
  }
  else
  {
    static_assert(!consteval(x));
    // x = 0; // Error: constexpr also implies that the argument is const in function scope
    
    // Runtime argument
    printf("%d", x);
  }
}

template <>
struct tup
{
  // Having constexpr non-static data member also adds an invented template parameter to the class template
  constexpr int x;
  constexpr int y;
  
  // By using CTAD, it must be possible to capture "constexpr" constructor args as empty members. Should also work with aggregates.
  tup(constexpr int x, constexpr int y)
    : x(x)
    , y(y)
  {
  }
};

void bar(int argc)
{
  foo(1); // Prints nothing
  foo(argc); // Prints argc value
  
  tup x(0, 0);
  tup y(0, argc);
  tup z(argc, argc);
  
  // Constexpr members behave like static members if initialized from a constant expression (not occupying space).
  static_assert(sizeof(y) == sizeof(int));
  static_assert(sizeof(z) == sizeof(int) * 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment