2011-08-22 25 views
-1

此代码编译罚款:问题态类

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

点是函数对象应该能够访问的class A 成员变量的任何变通办法也将有所帮助。

回答

2

本地类不能有成员模板(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命名空间中。

0

你在问什么似乎对我来说是不必要的复杂。避免这样的代码。

  • 本地类不会自动“捕获”包含类A的成员。
  • 本地类lm的模板参数未使用且多余。
  • 此外,它不会编译,因为T隐藏T。封闭函数调用的保证:
  • 使用的 lm()(10,15)
  • 将根据类定义(类型推断仅支持功能类)
  • 当地lm类的泛型是假的,至少需要一个模板参数lm<int>()xy的静态类型为int s。

叹气。这是我会怎么做:

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