Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print static variable for template metaprogramming

I have the following template metaprogramming implementation of factorial:

#include <iostream>

template <int n> struct factorial{
  static const int res = n*factorial<n-1>::res;
};

template <> struct factorial<0>{
  static const int res = 1;
};

int main(){
  std::cout << factorial<5>::res << '\n';
  return 0;
}

This code compiles successfully and outputs 120, as expected. However, for purely self-enjoying reasons, I would like to instead make it not compile, and instead display 120 in the error message of the compiler.

Is there a simple syntax mistake I can deliberately enter into my code to get it to fail to compile and yet still print the value of 5!, i.e. 120, in the compiler error message?

I anticipate that the answer will probably be compiler dependent; I am currently using g++ that came with Xcode Mac OSX, which iirc is a frontend for clang.

like image 753
xdavidliu Avatar asked Dec 14 '22 06:12

xdavidliu


1 Answers

You could use a declared, but undefined template to print out the value as a compile time error.

template<int n>
class display;

template<int n> struct factorial{
    static const int res = n*factorial<n-1>::res;
};

template<> struct factorial<0>{
    static const int res = 1;
};

int main()
{
    display<factorial<5>::res> value;
}

g++ outputs:

g++ -std=c++11 fact.cxx
fact.cxx: In function ‘int main()’:
fact.cxx:14:29: error: aggregate ‘display<120> value’ has incomplete type and cannot be defined
  display<factorial<5>::res> value;
                             ^
like image 165
Andrew Duncan Avatar answered Dec 28 '22 06:12

Andrew Duncan