2011-06-01 58 views
2

我试图建立一个小例子:仿函数调用(其他字符)

struct Functor 
{ 
    void operator()(int& a) 
    { 
     a += 1; 
    } 
    void other(int& a) 
    { 
     a += 2; 
    } 
}; 

template <typename foo> 
class Class 
{ 
    public: 
     void function() 
     { 
      int a = 10; 
      foo()(a); 
      std::cout << a << std::endl; 
     } 
}; 

int main() 
{ 
    Class<Functor> c; 
    c.function(); 
} 

我这个问题:为什么是它甚至可能呼吁纯粹型操作者没有对象?我如何以与我所称的operator()相同的方式调用函数other

+0

在哪里 “纯型”? – 2011-06-01 09:12:06

回答

8

你不是在纯粹的类型上调用它。 foo()调用构造函数,并计算临时对象foo,然后调用operator()

要与“正常”的成员函数做相当的,只是做:

foo().other(a); 
+0

这意味着每个调用都会有一个对象在堆栈上分配? – DyingSoul 2011-06-01 09:09:14

+0

@DyingSoul:如果你这样做,那么是的!虽然编译器可以自由优化,但它喜欢。 – 2011-06-01 09:10:03

+4

@DyingSoul:是和否,因为你的结构是空的,而且由于这些方法是内联的,所以编译器可能会简单地在“in place”方法中执行代码(相当于替换'foo()(a)如果你的方法不是内联的(无论什么原因),那么它将不得不在栈上保留一个字节(至少),因为有效地址需要传递给方法( 'this'),并且它不知道你不需要它,实际上。 – 2011-06-01 09:33:03

3

你是不是“调用[和]上的纯型运营商无一物”。语法foo()(a)正在创建类型foo(这是foo()部分)的临时文件,然后以a作为参数(该部分为(a)部分),在该对象上调用operator()

2

纯类型例如:

struct Functor 
{ 
    void operator()(int& a) 
    { 
     a += 1; 
    } 
    void other(int& a) 
    { 
     a += 2; 
    } 
    static void one_more(int& a) 
    { 
     a += 3; 
    } 
}; 

template <typename foo> 
class Class 
{ 
    public: 
     void function() 
     { 
      int a = 10; 
      foo()(a); 
      foo().other(a); 
      foo::one_more(a); 
      std::cout << a << std::endl; 
     } 
}; 

int main() 
{ 
    Class<Functor> c; 
    c.function(); 
} 
+0

调用静态函数更有效率,因为我们不需要在堆栈上创建一个实例,对吗? – DyingSoul 2011-06-01 09:21:05

+0

而编译器可以内联静态函数,因为编译时会解决这个问题吗? – DyingSoul 2011-06-01 09:21:43

+3

@DyingSoul:在这种情况下,所有这三个可能会变成相同的机器代码,构造函数没有可观察的副作用,所以编译器可以完全优化它。 – 2011-06-01 09:27:05