C++ 函子调用(附加字符)

C++ 函子调用(附加字符),c++,call,functor,C++,Call,Functor,我试图构建一个最小的示例: struct Functor { void operator()(int& a) { a += 1; } void other(int& a) { a += 2; } }; template <typename foo> class Class { public: void function() {

我试图构建一个最小的示例:

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();
}
结构函子 { void运算符()(int&a) { a+=1; } 无效其他(内部和外部) { a+=2; } }; 模板 班级 { 公众: 空函数() { INTA=10; foo()(a);
std::cout您不是在纯类型上调用它。
foo()
调用构造函数,并计算为一个临时的
foo
对象,然后在该对象上调用
operator()

要对“正常”成员函数执行等效操作,只需执行以下操作:

foo().other(a);
您不是在没有对象的纯类型上“调用”操作符。语法
foo()(a)
正在创建类型
foo
的临时变量(这是
foo()
部分),然后在该对象上调用
operator()
,并将
a
作为参数:(the
(a)
部分)。

纯类型示例:

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();
}
结构函子 { void运算符()(int&a) { a+=1; } 无效其他(内部和外部) { a+=2; } 静态无效一个或多个(int&a) { a+=3; } }; 模板 班级 { 公众: 空函数() { INTA=10; foo()(a); foo().其他(a); foo::再加一(a);
std::难道这意味着每次调用都会在堆栈上分配一个对象吗?@DyingSoul:如果你这样做,那么是的!尽管编译器可以随意优化它。@DyingSoul:是和否,因为你的结构是空的,而且方法是内联的,编译器很可能只是在其中执行代码方法“in-place”(相当于将
foo()(a)
替换为
a+=1
。如果您的方法不是内联的(无论出于何种原因),那么它必须在堆栈上保留一个字节(至少),因为需要将有效地址传递给该方法(该
this
),而实际上它无法知道您不需要它。地址在哪里“纯型"?调用静态函数更有效,因为我们不需要在堆栈上创建实例,对吗?编译器可以内联静态函数,因为它将在编译时解析?@DyingSoul:在这种情况下,所有三个函数可能都会转换为相同的机码。构造函数没有明显的副作用,因此编译器可以完全优化它。