|
Boost : |
Subject: [boost] TMP runtime access problem
From: Willy Liu (willy5562_at_[hidden])
Date: 2010-02-08 21:02:52
Hi, I wonder that how to access metadata in runtime.
If I pre-compute something and save them into a template ARRAY<int N>,
how can I random access the metadatas in runtime?
What I can only do is binary searching. Is it possible to do in
constant time, or there exist some functions in MPL doing this?
#include<cstdio>
using namespace std;
template<int N>
struct ARRAY
{
static const int a = ARRAY<N - 1>::a * 2;
};
template<>
struct ARRAY<0>
{
static const int a = 1;
};
template<int LOWER, int UPPER>
struct BS
{
static const int MID = UPPER + LOWER >> 1;
typedef BS<MID + 1, UPPER> GREATER;
typedef BS<LOWER, MID> LESS;
static inline int binary_search(int n)
{
if(n > MID)
return GREATER::binary_search(n);
else return LESS::binary_search(n);
}
};
template<int N>
struct BS<N, N>
{
static const int MID = N;
typedef ARRAY<MID> result;
static inline int binary_search(int n)
{
return result::a;
}
};
int main()
{
int n;
printf("2^n n:");
scanf("%d", &n);
printf("ARRAY<%d>::a = %d\n", n, BS<0, 30>::binary_search(n));
main();
return 0;
}
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk