Boost logo

Boost :

From: Daniel Wallin (dalwan01_at_[hidden])
Date: 2004-08-24 15:10:22


Goran Mitrovic wrote:
> I've got a question.
>
> Is a compile-time variables concept known?

Yes, but AFAIK it can't be done in standard C++. I guess you mean
something along the lines of this hack, which takes advantage of a
common compiler bug which will incorrectly find the check() and value()
overloads.. Works on gcc and maybe something else, but it's not
portable.

   template<int N> struct counter : counter<N - 1> {};
   template<> struct counter<0> {};

   template<int N>
   struct size_type
   {
       typedef char(&type)[N + 1];
   };

   size_type<0>::type check(...);

   template<class T, int N>
   struct set_variable
   {
       typedef counter<10> start_type;

       enum
       {
           current = sizeof(check((T*)0, (start_type*)0)) - 1,
           next = current + 1
       };

       friend typename size_type<next>::type check(T*, counter<next>*) {}
       friend typename size_type<N>::type value(T*, counter<current>*) {}
   };

   #define CURRENT(T) (sizeof(check((T*)0, (counter<10>*)0)) - 1)
   #define VALUE(T) (sizeof(value((T*)0, (counter<10>*)0)) - 1)
   #define SET(T, N) set_variable<T, N>()

   #include <iostream>

   struct X {};

   int main()
   {
       SET(X, 10);
       std::cout << CURRENT(X) << "\n";
       std::cout << VALUE(X) << "\n";

       SET(X, 15);
       std::cout << CURRENT(X) << "\n";
       std::cout << VALUE(X) << "\n";

       SET(X, 20);
       std::cout << CURRENT(X) << "\n";
       std::cout << VALUE(X) << "\n";
   }

-- 
Daniel Wallin

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk