简体   繁体   English

C ++ Functor作为函数的输出参数

[英]C++ Functor as an output argument of a function

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. 我想在c ++中编写一个函数,它接受一个int类型的变量,它的作用是它将定义一个仿函数的重载operator(),并将该函数作为输出参数返回。 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 ? 这样做是否正确?

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: 它被称为lambda表达式 ,它应该是这样的:

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): 如果C ++ 11不可用,您可以像这样模拟它(它修复了上面的错误):

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. 如果你愿意,你可以保持myFunc作为模板,但关键是,你可以通过传入的仿函数改变行为,所以尝试在myFunc中硬编码operator()并不是真的有意义,而且是不可能的。


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...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM