Reputation: 241
I want to write a function in c++ that takes a variable of type int and what it does is that it will define the overloading operator () of a functor and will return that functor as output argument. For example:
template<class Functor>
Functor myFunc(double n)
{
Functor f;
double Functor::operator() (double q)
{ return n*q;}
return Functor;
}
class myClass
{
double operator() ( double q ) const ;
};
Is this proper the way of doing it ?
Upvotes: 3
Views: 285
Reputation: 19607
There's a syntactic sugar for what you're trying to do (wrongly). It's called lambda expressions and this is what it should look like:
auto myFunc(double n)
{
return [n](double q) { return n * q; }
}
If C++11 is not available, you can emulate it like this (which fixes your errors above):
class Functor
{
double m_n;
public:
Functor(double n) : m_n(n) {}
double operator()(double q) const { return m_n * q; }
};
Functor myFunc(double n)
{
return Functor(n);
}
If you wish, you can keep myFunc
as a template, but the point is, you can change the behaviour by the functor you pass in, so trying to hardcode operator()
inside myFunc
does not really make sense, and is not possible.
Making it more generic:
template <typename T>
class Functor
{
T m_n;
public:
Functor(T n) : m_n(n) {}
T operator()(T q) const { return m_n * q; }
};
template <template <typename> class Functor, typename T>
auto myFunc(T n)
{
// we can use perfect forwarding here, but it's far beyond the original question
return Functor<T>(n);
}
Usage:
myFunc<Functor>(2)(3)
Even more generic, for variable amount of parameters captured by a functor (variadic templates):
template <template <typename ...> class Functor, typename ... Ts>
auto myFunc(Ts ... ns)
{
return Functor<Ts...>(ns...);
}
Upvotes: 3