开发者

problem with polymorphic class

开发者 https://www.devze.com 2023-03-29 17:15 出处:网络
This code compiles fine: int main() { class lm { public: int operator()(int x,int y){ return x+y; } };

This code compiles fine:

 int main() 
 { 
   class lm { 
      public: 
       int operator()(int x,int y){ 
          return x+y; 
        }
   }; 

   int x = lm()(10,15);
   return 0;
 }

But this doesn't

 int main() 
 { 
   template<class T>
   class lm { 
      public:
       T operator()(T x,T y){ 
          return x+y; 
        }
   }; 

   int x = lm()(10,15);
   return 0;
 }

Why am I doing this? because I want to fake a polymorphic lambda function inside of another function. Other suggestions are also welcome.

Ultimately what i would like to do is:

class A{
int m_var;
public:
int f(int x,int y);
}
int A::f(int x, int y)
{
   template<class T>
   class lm { 
      public:
       T operator()(T x,T y){ 
          return x+y+ m_var; //accessing the member variable of class A
        }
   }; 

   int x = lm()(10,15);
   return 0;
}

The point 开发者_运维技巧is the function object should be able to access the member variable of class A Any workaround will also help.


A local class cannot have member templates (this is the case in both C++03 and C++11).

The obvious solution is to move the class so that it is at namespace scope:

namespace {
    struct lm {
        template <typename T> T operator()(T x, T y) { return x + y; }
    };
}

int main() {  
    int x = lm()(10,15); 
} 

If you want to "associate" the template with the function in which it is meant to be used, stick it in a main_stuff namespace.


What you are asking seems needlessly complex to me. Avoid such code.

  • A local class will not automatically 'capture' members of enclosing class A.
  • The template argument to the local class lm is unused and superfluous.
  • Also, it won't compile as such because T hides T.
  • usage of lm()(10,15) will at least require a template argument to lm<int>() according to the class definition (type inference is only supported for function class)
  • The genericity of the local lm class is fake: the enclosing function call guarantees the static types of x and y to be ints.

Sigh. Here's what I'd do:

template <typename T>
class A
{
    const T m_var;

public:
    A(T var) : m_var(var) {}

    T operator()(T x, T y) const
    {
        return x + y + m_var;
    }
};

template <typename T>
A<T> helper(T var)
{
    return A<T>(var);
}

int main()
{
    return helper(42)(10,15);
}

returning 67

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号