Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 多态类的问题_C++_C++11 - Fatal编程技术网

C++ 多态类的问题

C++ 多态类的问题,c++,c++11,C++,C++11,这段代码编译得很好: int main() { class lm { public: int operator()(int x,int y){ return x+y; } }; int x = lm()(10,15); return 0; } 但事实并非如此 int main() { template<class T> class lm {

这段代码编译得很好:

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

   int x = lm()(10,15);
   return 0;
 }
但事实并非如此

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

   int x = lm()(10,15);
   return 0;
 }
我为什么要这样做? 因为我想在另一个函数中伪造一个多态lambda函数。 也欢迎提出其他建议

最后,我想做的是:

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;
}
关键是函数对象应该能够访问类A的成员变量
任何变通方法都会有所帮助。

本地类不能有成员模板这在C++03和C++11中都是如此

显而易见的解决方案是移动类,使其位于命名空间范围内:

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

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

如果您想将模板与要使用它的函数相关联,请将其粘贴在一个main_stuff名称空间中。

您所问的问题对我来说似乎不必要的复杂。避免这种代码

本地类不会自动“捕获”封闭类A的成员。 本地类lm的模板参数未使用且多余。 而且,它不会编译成这样,因为t隐藏了t。 根据类定义,lm10,15的使用将至少需要一个lm模板参数。类型推断仅支持函数类 局部lm类的泛型是假的:封闭函数调用保证x和y的静态类型为int。 唉。下面是我要做的:

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);
}
返回67