代码之家  ›  专栏  ›  技术社区  ›  outlaw

C++函子作为函数的输出变量

  •  3
  • outlaw  · 技术社区  · 6 年前

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

    这样做合适吗?

    1 回复  |  直到 6 年前
        1
  •  3
  •   LogicStuff    6 年前

    对于你试图做的事情(错误的)有一种语法上的甜头。它叫 lambda expressions 它应该是这样的:

    auto myFunc(double n)
    {
        return [n](double q) { return n * q; }
    }
    

    如果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);
    }
    

    如果你愿意,你可以 myFunc 作为模板,但重点是,可以通过传入的函子更改行为,因此尝试硬编码 operator() 里面 myFunc公司 没有真正意义,也不可能。


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

    用法:

    myFunc<Functor>(2)(3)
    

    更通用的是,对于由函子捕获的可变数量的参数(可变模板):

    template <template <typename ...> class Functor, typename ... Ts>
    auto myFunc(Ts ... ns)
    {
        return Functor<Ts...>(ns...);
    }