samedi 28 février 2015

Use template to apply a function template

If the following example were C++ it would contain non-sensical gibberish so I'll define the example to be written in pseudocode (and hence correct). It strongly hints at what I want to do in C++.



#include <vector>

template<class T>
void increment(const T& x)
{
++x;
}

template<template<class> class F>
struct Apply
{
template<class T>
void operator()(std::vector<T>& v)
{
for (auto& x : v)
F<T>(x);
}
};

template<template<class> class F, class T>
void apply(F<T> f, std::vector<T>& v)
{
for (auto& x : v)
f(x);
}

int main()
{
std::vector<int> v{1,2,3};

// apply increment function to v

// maybe this?
Apply<increment> a;
a(v);

// hmm... or this?
apply(increment, v);
}


I don't know how to turn this into C++ such that:




  1. increment is a function and not a function object.




  2. The parameter of increment is either deduced or supplied by Apply/apply.




  3. Apply/apply does not know about the name increment.




I can satisfy two out of the three but I'm not sure how to satisfy all three at once. The problem I run into is the apparent need for using a function template as a template template parameter which my compiler doesn't like. Still, it certainly seems possible to get this to work even if that particular route is off limits.


How can it be done?


Aucun commentaire:

Enregistrer un commentaire