I would very much like to be able to provide a functor as a template argument. The functors must be able to provide “themself” as that argument.
I imagine something like this:
template<typename T, template<typename> class SumFunctor> class foo;
template<typename T>
struct sum_default
{
foo<T, sum_default> operator()(foo<T, sum_default> a, foo<T, sum_default> b) const
{
T a_data = a.data();
T b_data = b.data();
return foo<T, sum_default>(a_data + b_data);
}
};
template<typename T>
struct sum_awesome
{
foo<T, sum_awesome> operator()(foo<T, sum_awesome> a, foo<T, sum_awesome> b) const
{
T a_data = a.data();
T b_data = b.data();
return foo<T, sum_awesome>(a_data - b_data);
}
};
template<typename T=int, template<typename> class SumFunctor=sum_default>
class foo
{
private:
T _data;
SumFunctor<T> _functor;
public:
foo<T, SumFunctor>(T data) : _data(data) {}
T data() { return _data; }
friend const foo operator +(const foo& lhs, const foo& rhs)
{
return lhs._functor(lhs,rhs);
}
};
int main(){
foo<> a(42);
foo<double> b(1.0);
foo<double,sum_default> c(4.0);
foo<double,sum_awesome> d(4.0);
a+a;
d+d;
}
Is this possible, and if so, how?
An alternative solution is to provide the functor to the constructor, but this is very ugly i think, as the user must dynamically allocate the functor himself (As we cannot determine the type of the functor in the constructor. Using RTTI to do so also seems a bit ugly):
foo<double> a(42, new sum_default<double>() );
This also forces all functors to be derived from some pre-defined base functor.
UPDATE
Attempting to add template arguments to the sum_default template argument does not appear to solve the problem:
template<typename T>
struct sum_default
{
// Error 1 error C3200: 'sum_default<T>' : invalid template argument for template parameter 'SumFunctor', expected a class template
foo<T, sum_default<T> > operator()(foo<T, sum_default<T> > a, foo<T, sum_default<T> > b) const
{
T a_data = a.data();
T b_data = b.data();
return foo<T, sum_default<T> >(a_data + b_data);
}
};
What’s biting you here is known as “class name injection” – inside of a class template, e.g.
Foo<T>, unqualified use ofFoois actually treated asFoo<T>. Citing C++11 §14.6.1/1:Consequently, inside of
sum_default<T>, when you havefoo<T, sum_default>, it’s treated as though you typedfoo<T, sum_default<T> >(which obviously won’t work asfoowants a template template parameter).In order to avoid this behavior, you need to qualify uses of the class template names inside of those class templates. Because your class templates are in the global scope,
::is sufficient:Note that this also allows you to define
foo‘s constructor thusly, reducing a bit of noise: