
On Tue, 24 Aug 2004 22:10:22 +0200, Daniel Wallin <dalwan01@student.umu.se> wrote:
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
Just a suggestion: Making set_variable a parameter to the check and value functions should make them available for standard compliant compilers as well, if I have interpreted the standards correctly. ... template<class T,int Current, int N> struct set_variable { typedef counter<10> start_type; set_variable(int); set_variable() {} enum { current = Current, next = current + 1 }; friend typename size_type<next>::type check(set_variable<T,Current,N> const&,T*, counter<next>*) {} friend typename size_type<N>::type value(set_variable<T,Current,N> const&,T*, counter<current>*) {} }; #define CURRENT(T) (sizeof(check(1,(T*)0, (counter<10>*)0)) - 1) #define VALUE(T) (sizeof(value(1,(T*)0, (counter<10>*)0)) - 1) #define SET(T, N) set_variable<T,CURRENT(T), N>() ... This compiles fine for VC 6.5 (so does the original example, so this is no proof of compliancy)
_______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost