开发者

functor call (additional characters)

开发者 https://www.devze.com 2023-03-09 13:20 出处:网络
I tried to build a minimal example: struct Functor { void operator()(int& a) { a += 1; } void other(int& a)

I tried to build a minimal example:

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

My question about this: Why is it even possible to cal开发者_运维知识库l the operator on the pure type without an object? How can I call the function other the same way as I call operator()?


You're not calling it on a pure type. foo() invokes the constructor, and evaluates to a temporary foo object, on which you then invoke operator().

To do the equivalent with a "normal" member function, just do:

foo().other(a);


You are not "call[ing] the operator on the pure type without an object". The syntax foo()(a) is creating a temporary of type foo (this is the foo() part) and then calling operator() on that object with a as argument: (the (a) part).


Pure type example:

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

精彩评论

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