Tuesday, October 17, 2017

C++17: Constant evaluation for all non-type template arguments

C++17 provides constant evaluation for all non-type template arguments. Here is an example:

#include <iostream>

template<int * p>
struct ST1
{
  int *mP = p; // C++98: Error; C++14: Good
};

template<int * i> 
struct ST2
{
  int mI = *i; // C++98: Error; C++14: Good
};

template<int (*pf)()>
struct ST3
{
  int mI = pf(); // C++98: Error; C++14: Good
};

struct S
{
  static int m;
};

int S::m = 42;
int gI   = 55;

///////////////////////////////////////////////////////////////////////////////
int myFunc()
{
  return 211;
}

///////////////////////////////////////////////////////////////////////////////
int main()
{
  S           s   ;
  ST1<&s.m  > st11; // C++14: Error, c++17: Good
  ST1<&S::m > st12;
  ST2<&gI   > st21;
  ST3<myFunc> st31;

  std::cout <<  s.m     << " ";
  std::cout << *st11.mP << " ";
  std::cout << *st12.mP << " ";
  std::cout <<  st21.mI << " ";
  std::cout <<  st31.mI << " ";

  std::cout << std::endl;
  return 0;
}
// Output: 42 42 42 55 211
References:
https://en.wikipedia.org/wiki/C%2B%2B17
https://stackoverflow.com/questions/33301552/non-type-reference-parameter-argument
https://isocpp.org/files/papers/n4268.html

No comments:

Post a Comment