Function array initialization at compile time with metaprograming - c++

In video-games is common that resources are loaded in a step fashion way, so within a single thread a loading bar can update at each loading step. By example:
1 -> Load texture A
2 -> Update Loading Bar to 2%
3 -> Load texture B
4 -> Update Loading Bar to 4%
5 ...
This can be done in many ways. One of these is define a function for each loading step.
void LoadTextureA()
{
//Loading routine
...
}
This has the advantage of readability, not need too much nested code and even possible in some cases to share loading routines between two game states.
Now what I was thinking was to generalize this "function-for-step" model with templates. Lets say.
template <int S>
struct Foo{
void LoadingStep()
{
}
};
template <>
struct Foo<0>
{
void LoadingStep()
{
//First loading step
...
}
};
Please correct me if I'm wrong. But it appears possible that I can compile-time iterate through 0 .. to N steps using metaprogramming and assign this specialized functions to an array or vector of function pointers.
N steps are known at compile time along with it respective functions.
Function pointer vector would be iterated like this:
template <int Steps>
class Loader {
public:
bool Load()
{
functionArray[m_step]();
if (++m_step == Steps)
return false; //End loading
else
return true;
}
private:
int m_step;
}
Is this possible? I know that that are easier ways to do it. But besides project requirments it's an interesting programming challenge

I achieved it based on Kal answer of a similar problem
Create N-element constexpr array in C++11
template <int S>
struct Foo{
static void LoadingStep()
{
}
};
template <>
struct Foo<0>
{
static void LoadingStep()
{
//First loading step
}
};
template<template<int S> class T,int N, int... Rest>
struct Array_impl {
static constexpr auto& value = Array_impl<T,N - 1, N, Rest...>::value;
};
template<template<int S> class T,int... Rest>
struct Array_impl<T,0, Rest...> {
static constexpr std::array<void*,sizeof...(Rest)+1> value = {reinterpret_cast<void*>(T<0>::LoadingStep),reinterpret_cast<void*>(T<Rest>::LoadingStep)...};
};
template<template<int S> class T,int... Rest>
constexpr std::array<void*,sizeof...(Rest)+1> Array_impl<T,0, Rest...>::value;
template<template<int S> class T,int N>
struct F_Array {
static_assert(N >= 0, "N must be at least 0");
static constexpr auto& value = Array_impl<T,N>::value;
F_Array() = delete;
F_Array(const F_Array&) = delete;
F_Array(F_Array&&) = delete;
};
Using example:
int main()
{
auto& value = F_Array< Foo ,4>::value;
std::cout << value[0] << std::endl;
}
This yields of void* array of pointers to template functions:
Foo<0>::LoadinStep()
Foo<1>::LoadinStep()
Foo<2>::LoadinStep()
Foo<3>::LoadinStep()
Foo<4>::LoadinStep()
Since Foo<1..3> are not specialized they will fall to Default LoadingStep function

Yes. It's possible. And if you use the template metaprogramming, you don't need to use a run time loop, but a recursive call to a template method:
#include <iostream>
// The template numerated methods
template <int S> struct Foo{static void LoadingStep(){}};
template <> struct Foo<0> {static void LoadingStep(){std::cout<<0;}};
template <> struct Foo<1> {static void LoadingStep(){std::cout<<1;}};
template <> struct Foo<2> {static void LoadingStep(){std::cout<<2;}};
// The loader template method
template <int Step>
void Loader()
{
Foo<Step>::LoadingStep();
Loader<Step-1>();
}
// Stopping rule
template <> void Loader<-1>(){}
int main()
{
Loader<2>();
}

If you want an array:
LoadingFunction functionArray[] = {Function0, Function1, Function2};
.....
for (int i = 0; i < nSteps; ++i)
RunStep(i, nSteps, Function[i]);
Or initialize an std container with it.
If you want templates, you could write
for (int i = 0; i < nSteps; ++i)
RunStep(i, nSteps, Function<i>);
except i in Function<i> must be a constant. So you have to do it with a templated recursive something:
template <int i, int NSteps> struct RunSteps
{
void Run()
{
RunStep(i, NSteps, Function<i>);
RunSteps<i+1, NSteps>::Run();
}
};
template <int NSteps> struct RunSteps<NSteps, NSteps>
{
void Run() {}
};
RunSteps<0, NSteps>::Run();
Compile-time iteration doesn't really exist. The for loop and the templated recursive something do exactly the same thing. The compiler is as capable of unrolling a loop, as of inlining a call.
It looks like there's very little to be gained from templatizing this stuff, and lots to lose.
It is not clear why you would want to put templated functions to an array at compile time, but here you go:
LoadingFunction functionArray[] = {Function<0>, Function<1>, Function<2>};
Now if you don't want to enumerate functions manually like that, it could be a bit of a challenge. It doesn't seem possible with either legacy C arrays or any of the std containers. Assuming you really need it, it's possible to write a custom container capable of such initialization.
template <template <int> class FunctionWrappper, int NFunctions>
class MyOptimizedFunctionArray {
// filling this space is left as an exercise
};

Related

Managing a collection of vectors of templated derived types

The X: What I want to do:
I have the types: BaseType and DerivedType<int k> (see code below), and I need to handle a collection of K vectors of the derived types std::vector<DerivedType<k>>, k = 1...K. I'd like to access the objects in these vectors, and perform an operation on them that depends on k. K is a compile time constant. The problem is illustrated in the implementation:
The types are defined as:
#include <iostream>
#include <algorithm>
struct BaseType { // Interface of the DerivedTypes
virtual void print(){std::cout << "BaseType!" << std::endl; }
};
template< int k >
struct DerivedType : public BaseType {
static const int k_ = k;
// ... function calls templated on k ...
void print(){std::cout << "DerivedType: " << k_ << std::endl;}
};
template< int k >
void doSomething ( DerivedType<k>& object ) { object.print(); }
And what I want to do is:
int main() {
// My collection of vectors of the derived types:
std::vector<DerivedType<0>> derType0(2);
std::vector<DerivedType<1>> derType1(1);
std::vector<DerivedType<2>> derType2(3);
// ... should go to K: std::vector<DerivedType<K>> derTypeK;
// Iterate over the derived objects applying a k-dependent templated function:
std::for_each(begin(derType0),end(derType0),[](DerivedType<0>& object){
doSomething<0>(object);
});
std::for_each(begin(derType1),end(derType1),[](DerivedType<1>& object){
doSomething<1>(object);
});
std::for_each(begin(derType2),end(derType2),[](DerivedType<2>& object){
doSomething<2>(object);
});
return 0;
}
I want to avoid repeating code, such that I only have to change K, which is a compile time constant of O(10). Ideally, I would have something "more like" this:
// Pseudocode: do not try to compile this
create_derived_objects(DerivedType,K)
= std::vector< std::vector<DerivedType<k>>* > my_K_derived_types;
for each vector<DerivedType<k>>* derivedTypes in my my_K_derived_types
for each object in (*derivedTypes)
doSomething<k> on object of type derivedType<k>
// I could also restrict doSomething<k> to the base interface
Each vector of derived types contains O(10^6) to O(10^9) objects. The inner-most loops are the most time consuming part of my application making dynamic_cast only an option for the outer-most loop.
The Y: what I have tryed without succes.
I am at the moment studying the Abrahams C++ Template Metaprogramming book to see if I could use boost::mpl. I am also doing the tutorials on boost::fusion to see if I could use it too. However, the learning curve of these libraries is rather large, so I wanted to ask first before I invest a week in something when a better and simpler solution is available.
My first try was to wrapp my vectors std::vector<DerivedType<k>> such that I can create a vector<WrappedDerivedTypes*>, and access each of the single vectors separately within a for_each loop. However, in the loop I have a series of if(dynamic_cast<std::vector<DerivedType<0>>>(WrappedVector) != 0 ){ do for_each loop for the derived objects } else if( dynamic_cast...) { do...} ... that I wasn't able to eliminate.
What about a recursive solution based on a generic linked list of vectors, a strategy pattern and a thing that applies strategies recursively through the linked list? (note: see the improved version at the end):
#include <iostream>
#include <vector>
template <int j>
class holder {
public:
const static int k = j;
};
template <int j>
class strategy {
public:
void operator()(holder<j> t)
{
std::cout << "Strategy " << t.k << std::endl;
}
};
template <int k>
class lin_vector {
private:
std::vector<holder<k>> vec;
lin_vector<k-1> pred;
public:
lin_vector(const lin_vector<k-1> &pred, std::vector<holder<k>> vec)
: vec(vec), pred(pred) { }
std::vector<holder<k>> get_vec() { return vec; }
lin_vector<k-1> &get_pred() { return pred; }
};
template <>
class lin_vector<0> {
public:
lin_vector() { }
};
template <int k, template <int> class strategy>
class apply_strategy {
public:
void operator()(lin_vector<k> lin);
};
template <int k, template <int> class strategy>
void apply_strategy<k, strategy>::operator()(lin_vector<k> lin)
{
apply_strategy<k-1, strategy>()(lin.get_pred());
for (auto i : lin.get_vec())
strategy<k>()(i);
}
template <template <int> class strategy>
class apply_strategy<0, strategy>
{
public:
void operator()(lin_vector<0> lin) { /* does nothing */ }
};
template <int k>
lin_vector<k> build_lin()
{
return lin_vector<k>(build_lin<k-1>(), {holder<k>()});
}
template <>
lin_vector<0> build_lin()
{
return lin_vector<0>();
}
int main(void)
{
apply_strategy<5, strategy>()(build_lin<5>());
}
Compile it with a C++11 compiler.
Most probably you'll find unsatisfactory the fact that building a lin_vector requires a lot of copying, but you can specialize the structure to suit your needs (perhaps substituting the pred with a pointer or embedding the creation strategy straight into the linked list).
EDIT: here there is an improved version which avoids a lot of copying and handles list building and processing in a more coherent and uniform way:
#include <iostream>
#include <vector>
template <int j>
class holder {
public:
const static int k = j;
};
template <int k>
class lin_vector {
private:
std::vector<holder<k>> vec;
lin_vector<k-1> pred;
public:
std::vector<holder<k>> &get_vec() { return vec; }
lin_vector<k-1> &get_pred() { return pred; }
};
template <>
class lin_vector<0> {
public:
lin_vector() { }
};
template <int k, template <int> class strategy>
class apply_strategy {
public:
void operator()(lin_vector<k> &lin);
};
template <int k, template <int> class strategy>
void apply_strategy<k, strategy>::operator()(lin_vector<k> &lin)
{
apply_strategy<k-1, strategy>()(lin.get_pred());
strategy<k>()(lin.get_vec());
}
template <template <int> class strategy>
class apply_strategy<0, strategy>
{
public:
void operator()(lin_vector<0> &lin) { /* does nothing */ }
};
template <int j>
class strategy {
public:
void operator()(std::vector<holder<j>> &t)
{
std::cout << "Strategy " << j << ", elements: ";
for (auto v : t)
std::cout << v.k << " ";
std::cout << std::endl;
}
};
template <int j>
class build_strategy {
public:
void operator()(std::vector<holder<j>> &t)
{
for (unsigned int i = 0; i < j; i++)
t.push_back(holder<j>());
}
};
int main(void)
{
const int K = 5;
lin_vector<K> list;
apply_strategy<K, build_strategy>()(list);
apply_strategy<K, strategy>()(list);
}
A solution free of virtual dispatch is possible, though it's probably overkill.
The first thing you need is a function template doSomething<K>() that you specialise on each derived type:
template <int K>
void doSomething(vector<DerivedType<K> >& x);
template <>
void doSomething<1>(vector<DerivedType<1> >& x) { ... }
template <>
void doSomething<2>(vector<DerivedType<2> >& x) { ... } // etc.
You could then build a strongly-typed collection of vectors using a recursively defined struct template:
template <int K>
struct vov {
vov<K - 1> prev;
vector<DerivedType<K> > v;
};
template <>
struct vov<1> {
vector<DerivedType<1> > v;
};
Finally, you can write a recursive function template to process this structure:
template <int K>
void process(vov<K>& x) {
doSomething(x.v); // Type inference will find the right doSomething()
process(x.prev); // Here too
}
template <>
void process<1>(vov<1>& x) {
doSomething(x.v);
}
Now the main code will look like:
vov<42> foo;
process(foo);
Because the process() function call performs iteration through the use of recursion, it will probably use K stack frames unnecessarily; however it is tail recursion, which modern optimising C++ compilers can usually convert into plain iteration with no stack wastage. Using tail recursion forces us to process the vectors in "reverse" order, so that the DerivedType<1> vector is processed last, but if necessary this could be fixed with a slightly more elaborate template using 2 int template parameters (one will "count up" towards the other, instead of a single int parameter that "counts down" towards 1).
Observe that there is no benefit gained by deriving each DerivedType<k> from BaseType in this solution -- you may as well forget about BaseType altogether, unless you need it for a different reason.
There may well be MPL primitives that simplify some of these processes -- if anyone knows them, please feel free to edit.

compile time loops

I would like to know if it is possible to have sort of compile time loops.
For example, I have the following templated class:
template<class C, int T=10, int B=10>
class CountSketch
{
public:
CountSketch()
{
hashfuncs[0] = &CountSketch<C>::hash<0>;
hashfuncs[1] = &CountSketch<C>::hash<1>;
// ... for all i until i==T which is known at compile time
};
private:
template<int offset>
size_t hash(C &c)
{
return (reinterpret_cast<int>(&c)+offset)%B;
}
size_t (CountSketch::*hashfuncs[T])(C &c);
};
I would thus like to know if I can do a loop to initialize the T hash functions using a loop. The bounds of the loops are known at compile time, so, in principle, I don't see any reason why it couldn't be done (especially since it works if I unroll the loop manually).
Of course, in this specific example, I could just have made a single hash function with 2 parameters (although it would be less efficient I guess). I am thus not interested in solving this specific problem, but rather knowing if "compile time loops" existed for similar cases.
Thanks!
Nope, it's not directly possible. Template metaprogramming is a pure functional language. Every value or type defined through it are immutable. A loop inherently requires mutable variables (Repeatedly test some condition until X happens, then exit the loop).
Instead, you would typically rely on recursion. (Instantiate this template with a different template parameter each time, until you reach some terminating condition).
However, that can solve all the same problems as a loop could.
Edit: Here's a quick example, computing the factorial of N using recursion at compile-time:
template <int N>
struct fac {
enum { value = N * fac<N-1>::value };
};
template <>
struct fac<0> {
enum { value = 1 };
};
int main() {
assert(fac<4>::value == 24);
}
Template metaprogramming in C++ is a Turing-complete language, so as long as you don't run into various internal compiler limits, you can solve basically any problem with it.
However, for practical purposes, it may be worth investigating libraries like Boost.MPL, which contains a large number of data structures and algorithms which simplify a lot of metaprogramming tasks.
Yes. Possible using compile time recursion.
I was trying with your code but since it was not compilable here is a modified and compiling exmaple:
template<class C, int T=10>
class CountSketch
{
template<int N>
void Init ()
{
Init<N-1>();
hashfuncs[N] = &CountSketch<C>::template hash<N>;
cout<<"Initializing "<<N<<"th element\n";
}
public:
CountSketch()
{
Init<T>();
}
private:
template<int offset>
size_t hash(C &c)
{
return 0;
}
size_t (CountSketch::*hashfuncs[T])(C &c);
};
template<>
template<>
void CountSketch<int,10>::Init<0> ()
{
hashfuncs[0] = &CountSketch<int,10>::hash<0>;
cout<<"Initializing "<<0<<"th element\n";
}
Demo. The only constraint of this solution is that you have to provide the final specialized version as, CountSketch<int,10>::Init<0> for whatever type and size.
You need a combination of boost::mpl::for_each and boost::mpl::range_c.
Note: This will result in run-time code and this is what you actually need. Because there is no way to know the result of operator& at compile time. At least none that I'm aware of.
The actual difficulty with this is to build a struct that is templated on an int parameter (mpl::int_ in our case) and that does the assignment when operator() is called and we also need a functor to actually capture the this pointer.
This is somewhat more complicated than I anticipated but it's fun.
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/copy.hpp>
// aforementioned struct
template<class C, class I>
struct assign_hash;
// this actually evaluates the functor and captures the this pointer
// T is the argument for the functor U
template<typename T>
struct my_apply {
T* t;
template<typename U>
void operator()(U u) {
u(t);
}
};
template<class C, int T=10, int B=10>
class CountSketch
{
public:
CountSketch()
{
using namespace boost::mpl;
// we need to do this because range_c is not an ExtensibleSequence
typedef typename copy< range_c<int, 0, T>,
back_inserter< vector<> > >::type r;
// fiddle together a vector of the correct types
typedef typename transform<r, typename lambda< assign_hash<C, _1 > >::type >
::type assignees;
// now we need to unfold the type list into a run-time construct
// capture this
my_apply< CountSketch<C, T, B> > apply = { this };
// this is a compile-time loop which actually does something at run-time
for_each<assignees>(apply);
};
// no way around
template<typename TT, typename I>
friend struct assign_hash;
private:
template<int offset>
size_t hash(C& c)
{
return c;
// return (reinterpret_cast<int>(&c)+offset)%B;
}
size_t (CountSketch::*hashfuncs[T])(C &c);
};
// mpl uses int_ so we don't use a non-type template parameter
// but get a compile time value through the value member
template<class C, class I>
struct assign_hash {
template<typename T>
void operator()(T* t) {
t->hashfuncs[I::value] = &CountSketch<C>::template hash<I::value>;
}
};
int main()
{
CountSketch<int> a;
}
with C++20 and consteval compile time loops became possible without doing template hell unless the value can have multiple types:
consteval int func() {
int out = 0;
for(int i = 10; i--;) out += i;
return out;
}
int main() {
std::cout << func(); // outputs 45
}
There are compilers that will see the loop and unroll it. But it's not part of the language specification that it must be done (and, in fact, the language specification throws all sorts of barriers in the way of doing it), and there's no guarantee that it will be done, in a particular case, even on a compiler that "knows how".
There are a few languages that explicitly do this, but they are highly specialized.
(BTW, there's no guarantee that the "unrolled" version of your initializations would be done "at compile time" in a reasonably efficient fashion. But most compilers will, when not compiling to a debug target.)
Here is, I think, a better version of the solution given above.
You can see that we use the compile-time recursive on the function params.
This enables putting all the logic inside your class, and the base case of Init(int_<0>) is very clear - just do nothing :)
Just so you won't fear performance penalty, know that the optimizer will throw away these unused parameters.
As a matter of fact, all these function calls will be inlined anyway. that's the whole point here.
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
template <class C, int N = 10, int B = 10>
class CountSketch {
public:
CountSketch() {
memset(&_hashFunctions, sizeof(_hashFunctions), 0); // for safety
Init(int_<N>());
}
size_t HashAll(C& c)
{
size_t v = 0;
for(const auto& h : _hashFunctions)
{
v += (this->*h)(c); // call through member pointer
}
return v;
}
private:
template<int offset>
size_t hash(C &c)
{
return (reinterpret_cast<size_t>(&c)+offset)%B;
}
size_t (CountSketch::*_hashFunctions[N])(C &c);
private: // implementation detail
// Notice: better approach.
// use parameters for compile-time recursive call.
// you can just override for the base case, as seen for N-1 below
template <int M>
struct int_ {};
template <int M>
void Init(int_<M>) {
Init(int_<M - 1>());
_hashFunctions[M - 1] = &CountSketch<C, N, B>::template hash<M>;
printf("Initializing %dth element\n", M - 1);
}
void Init(int_<0>) {}
};
int main() {
int c;
CountSketch<int, 10> cs;
int i;
cin >> i;
printf("HashAll: %d", cs.HashAll(c));
return 0;
}
Compiler Explorer

compile-time counter for template classes

Imagine that you have a lot of classes with a lot of different template parameters. Every class has a method static void f(). You want to collect all these function pointers in a list L.
A run-time solution would be easy:
typedef void (*p)();
std::vector<p> L;
int reg (p x) { static int i = 0; L.push_back(x); return i++; } // also returns an unique id
template <typename T> struct regt { static int id; };
template <typename T> int regt<T>::id = reg (T::f);
template < typename ... T > struct class1 : regt< class1<T...> > { static void f(); };
template < typename ... T > struct class2 : regt< class2<T...> > { static void f(); };
// etc.
The compiler knows all f()s of all instantiated classes at compile-time. So, theoretically it should be possible to generate such a list (a const std::array<p, S> L with some S) as a compile-time constant list. But how? (C++0x solutions are welcome, too).
Why do I need this?
On an architecture with only 256 kB (for code and data), I need to generate objects for incoming ids of classes. Existing serialization frameworks or the run-time solution above are unnecessarily big. Without templates a compile-time solution would be easy, but I want to keep all the advantages templates offer.
Manually
The simplest thing that you can do is just roll the code manually, I don't think that there is much that can be used to your advantage from the templates, so I will use plain classes, where A, B... stand for particular instantiations of your types. That allows for compile time initialization of the types, at the cost of having to remember to update the lookup table whenever a new type is added to the system:
typedef void (*function_t)();
function_t func[] = {
&A::f,
&B::f,
&C::f
};
I would recommend this, from a maintenance point of view. Automating the system will make the code much harder to understand and maintain in the future.
Macros
The simple most automated one, which will probably generate less code is a macro generation system is just using macros. Since this first approach will use extensive use of macros, I will generate the functions automatically, as you did in the previous question. You can remove that part of code if you have (hopefully) given up the path of full code generation through macros.
To avoid having to retype the names of the types in different contexts you can define a macro with all the data you need for any context, and then use other macros to filter what is to be used (and how) in each particular context:
// This is the actual list of all types, the id and the code that you were
// generating in the other question for the static function:
#define FOREACH_TYPE( macro ) \
macro( A, 0, { std::cout << "A"; } ) \
macro( B, 1, { std::cout << "B"; } ) \
macro( C, 2, { std::cout << "C"; } )
// Now we use that recursive macro to:
// Create an enum and calculate the number of types used
#define ENUM_ITEM( type, id, code ) \
e_##type,
enum AllTypes {
FOREACH_TYPE( ENUM_ITEM )
AllTypes_count
};
#undef ENUM_ITEM
// Now we can create an array of function pointers
typedef void (*function_t)();
function_t func[ AllTypes_count ];
// We can create all classes:
#define CREATE_TYPE( type, the_id, code ) \
struct type {\
static const int id = the_id; \
static void func() code\
};
FOREACH_TYPE( CREATE_TYPE )
#undef CREATE_TYPE
// And create a function that will
#define REGISTER_TYPE( type, id, code ) \
func[ i++ ] = &type::func;
void perform_registration() {
int i = 0;
FOREACH_TYPE( REGISTER_TYPE );
};
#undef REGISTER_TYPE
// And now we can test it
int main() {
perform_registration();
for ( int i = 0; i < AllTypes_count; ++i ) {
func[ i ]();
}
}
This is, on the other hand a maintenance nightmare, quite fragile and hard to debug. Adding new types is trivial, just add a new line to the FOREACH_TYPE macro and you are done... and the best of lucks once something fails...
Templates and metaprogramming
On the other hand, using templates you can get close but you cannot get to the single point of definition for the types. You can automate some of the operations in different ways, but at the very least you will need to define the types themselves and add them to a typelist to get the rest of the functionality.
Simplifying the definition of the actual type_list with C++0x code you can start by defining the types and then creating the type_list. If you want to avoid using C++0x, then take a look at the Loki library, but with C++0x a type list is simple enough:
template <typename ... Args> type_list {}; // generic type list
typedef type_list< A, B, C, D > types; // our concrete list of types A, B, C and D
// this is the only source of duplication:
// types must be defined and added to the
// type_list manually [*]
Now we need to use some metaprogramming to operate on the type list, we can for example count the number of elements in the list:
template <typename List> struct size; // declare
template <typename T, typename ... Args> // general case (recursion)
struct size< type_list<T,Args...> > {
static const int value = 1 + size< type_list<Args...>::value;
};
template <> // stop condition for the recursion
struct size< type_list<> > {
static const int value = 0;
};
Having the size of the type list is a first step in our problem, as it allows us to define an array of functions:
typedef void (*function_t)(); // signature of each function pointer
struct registry {
static const int size = ::size< types >::value;
static const function_t table[ size ];
};
function_t registry::table[ registry::size ]; // define the array of pointers
Now we want to register the static functions from each particular type in that array, and for that we create an auxiliar function (encapsulated as a static function in a type to allow for partial specializations). Note that this concrete part is designed to be run during initialization: it will NOT be compile time, but the cost should be trivial (I would be more worried on the binary size with all the templates):
template <typename T, int N> // declaration
struct register_types_impl;
template <typename T, typename ... Args, int N> // general recursion case
struct register_types_impl< type_list<T,Args...>, N> {
static int apply() {
registry::table[ N ] = &T::f; // register function pointer
return register_types_impl< type_list<Args...>, N+1 >;
}
};
template <int N> // stop condition
struct register_types_impl< type_list<>, int N> {
static int apply() { return N; }
};
// and a nicer interface:
int register_types() {
register_types_impl< types, 0 >();
}
Now we need an id function that maps our types to the function pointer, which in our case is the position of the type in the type list
template <typename T, typename List, int N> // same old, same old... declaration
struct id_impl;
template <typename T, typename U, typename ... Args, int N>
struct id_impl< T, type_list<U, Args...>, N > { // general recursion
static const int value = id_impl< T, type_list<Args...>, N+1 >;
};
template <typename T, typename ... Args, int N> // stop condition 1: type found
struct id_impl< T, type_list<T, Args...>, N> {
static const int value = N;
};
template <typename T, int N> // stop condition 2: type not found
struct id_impl< T, type_list<>, N> {
static const int value = -1;
}
// and a cleaner interface
template <typename T, typename List>
struct id {
static const int value = id_impl<T, List, 0>::value;
};
Now you just need to trigger the registration at runtime, before any other code:
int main() {
register_types(); // this will build the lookup table
}
[*] Well... sort of, you can use a macro trick to reuse the types, as the use of macros is limited, it will not be that hard to maintain/debug.
The compiler knows all f()s of all instantiated classes at compile-time.
There's your mistake. The compiler knows nothing about template instantiations in other compilation units. It should now be pretty obvious why the number of instantiations isn't a constant integral expression that could be used as a template argument (and what if std::array was specialized? Halting Problem ahead!)

Metaprogramming template recursion doesn't recurse (edited important)

I try to invoke function void set (...) recursively using metaprogramming.
The problem is that it seems to invokes only once.
template <int N>
struct GEN
{
enum {value = GEN<N-1>::value};
template <typename T>
static inline void set(T& tup, int l_item)
{
cout<<"item value: "<<l_item<<", N-1: "<< N-1 << ", value: "<<value <<endl;
typedef typename boost::tuples::element<N-1, T>::type _el_type;
get<N-1>(tup) = atomic_item<N-1, _el_type>(l_item);
};
};
template<>
struct GEN<0>
{
enum {value = 0};
template <typename T>
static inline void set(T& tup, int l_item)
{
typedef typename boost::tuples::element<0, T>::type _el_type;
get<0>(tup) = atomic_item<0, _el_type>(l_item);
};
};
main(){
....
/** this is how i try to invoke it */
GEN<3>::set(w,1);
}
Output:
item value: 1, N-1: 2, value: 0
function has been invoked only once...
EDIT
is there a way to do kind of loop with for_each or anything else to get something simmilar:
for_each<range_c<int,0,3> f{operator()(T i)GEN<typename T::value>::set(w,1)}>
or something similar to achieve invoke for all of those elements?
Particularly I'd like to have this:
GEN<3>::set(w,1);
GEN<2>::set(w,1);
GEN<1>::set(w,1);
In loop.
There is no recursion. Recursion means calling yourself. The set function in your code does not do this.
Your value declaration does recurse (i.e. GEN<N>::value is defined in terms of GEN<N -1>::value) – but in a pretty uninteresting way, it just propagates the base case value, 0 – and furthermore you don’t seem to be using this value anyway.
/EDIT: Here’s a very simple example to address the point raised by you in the comments, i.e. to achieve the effect of
GEN<3>::set(w,1);
GEN<2>::set(w,1);
GEN<1>::set(w,1);
That’s actually pretty easy:
template <unsigned N>
struct GEN {
template <typename T>
static void set(T& w, int value) {
// Do something, e.g.:
get<N - 1>(w) = value;
// Recurse:
GEN<N - 1>::set(w, value);
}
};
template <>
struct GEN<0> {
template <typename T>
static void set(T&, int) { /* empty */ }
};
Now you can call this code via GEN<3>::set(w, 1) and it will have the desired semantics.
The metaprogramming template obviously did recurse since your code compiled and ran.
Were you expecting a recursive call of the set function? The function you called, GEN<3>::set doesn't call the set function of any other class, so there is no run-time recursion. There is only compile-time recursion to instantiate the templates. But compile-time recursion doesn't generate output at run time.

C++ metaprogramming

I have the following problem:
Suppose I have some basic counter class Counter. And suppose we also have some sets of classes, that can be counted. Let's name some of them class CountedA and class CountedB.
Now, every class, which can be counted (such as CountedA and CountedB) has the following statically declared parts: one enum and one int part, that acts like a part of counted data.
For example, it's declaration could look the following way:
enum CountedType { A, B };
template <CountedType Type, int N>
class Counted { };
// Now we can declare 'CountedA' and 'CountedB'
typedef Counted<A, 25> CountedA;
typedef Counted<B, 7> CountedB;
Now, the declaration of the counter:
// C++0x variadic or simply bunch of 'typename XX' definitions for C++03
template <typename T0, typename T1, typename ...>
class Counter
{
// I don't know how to implement this
// for now!
int GetTotalN() { ... }
// Retrieve the corresponding type
// so that GetTypeAt<0> returns
// enum from 'T0'
template <int Pos>
CountedType GetTypeAt() { ... }
};
I want to be able to write something like:
class RealCounter : public Counter<CountedA, CountedB> { };
And use it the following way:
RealCounter counter;
int n = counter.GetTotalN();
CountedType type = counter.GetTypeAt<0>();
Now, I'm pretty sure that this can be done. But what's the best way of implementing it? (don't ask me why would I need such crazy kind of things :)
Does boost::mpl offer something for this case?
Thank you.
Small update:
In this particular example, GetTotalN() should return 25 + 7.
If we add, for example, typedef Counted<C, 2> CountedC, then the result for
RealCounter : public Counter<CountedA, CountedB, CountedC>
should become 25 + 7 + 2.
Here's C++03 code which works (for up to 10 template arguments). The main trick is giving class Counter a multiple inheritance, and passing objects of type Counter to function templates which must select a base class. The actual summation is done recursively.
Counter.hpp
enum CountedType { A, B };
template <CountedType Type, int N>
struct Counted {};
struct DummyCounted {};
template <int Pos, typename T>
struct IndexedType {};
template <unsigned int Terms>
struct PartialSum
{
template <typename CounterT>
static int getSum(const CounterT& ctr)
{ return PartialSum<Terms-1>::getSum(ctr) + ctr.template GetNAt<Terms>(); }
};
template <> struct PartialSum<0U>
{
template <typename CounterT>
static int getSum(const CounterT& ctr)
{ return ctr.template GetNAt<0>(); }
};
template <typename T0, typename T1=DummyCounted,
typename T2=DummyCounted, typename T3=DummyCounted,
typename T4=DummyCounted, typename T5=DummyCounted,
typename T6=DummyCounted, typename T7=DummyCounted,
typename T8=DummyCounted, typename T9=DummyCounted>
class Counter :
public IndexedType<0, T0>, public IndexedType<1, T1>,
public IndexedType<2, T2>, public IndexedType<3, T3>,
public IndexedType<4, T4>, public IndexedType<5, T5>,
public IndexedType<6, T6>, public IndexedType<7, T7>,
public IndexedType<8, T8>, public IndexedType<9, T9>
{
public:
static int GetTotalN() {
return PartialSum<9>().getSum( Counter() );
}
template <int Pos>
static CountedType GetTypeAt() { return _getTypeAt<Pos>( Counter() ); }
template <int Pos>
static int GetNAt() { return _getNAt<Pos>( Counter() ); }
private:
template <int Pos, CountedType Type, int N>
static CountedType _getTypeAt(const IndexedType<Pos, Counted<Type,N> >&)
{ return Type; }
template <int Pos, CountedType Type, int N>
static int _getNAt(const IndexedType<Pos, Counted<Type,N> >&)
{ return N; }
template <int Pos>
static int _getNAt(const IndexedType<Pos, DummyCounted>&)
{ return 0; }
};
Counter.cpp
#include "Counter.hpp"
#include <iostream>
typedef Counted<A, 25> CountedA;
typedef Counted<B, 7> CountedB;
class RealCounter : public Counter<CountedA, CountedB> {};
int main()
{
RealCounter counter;
int n = counter.GetTotalN();
CountedType type = counter.GetTypeAt<0>();
std::cout << "n is " << n
<< "\ntype check is " << (type == A) << std::endl;
return 0;
}
Output:
n is 32
type check is 1
That C++0x variadic template stuff looks interesting, but I haven't taken a good look at it yet. But I do think in C++0x, all this example's functions (except main of course) could be constexpr.
I'm not sure why you need to embed those parameters in the templates arguments and not simply in a constructor since they are all the same types for each "derived" CountedA/B types.
Anyways you can embed the resulting types into a std::tuple as shown in the link below (see Message class for an example). Then create a variadic template function similar to the applyTuple version in the link below that will add all your integer arguments and return the final result once all arguments have been unrolled. As for the returning of the enum value for the item in "Pos" simply call the get( tuple ).getEnum() or .value to get it.
How do I expand a tuple into variadic template function's arguments?