什么是C ++中的可调用对象? [英] What is a callable object in C++?

查看:224
本文介绍了什么是C ++中的可调用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究增强线程.我发现线程类有一个接受可调用对象的构造函数.什么是可调用对象?

I'm currently studying boost threads. And I came across that the thread class has a constructor that accepts callable objects. What are callable objects?

class CallableClass
{
private:
    // Number of iterations
    int m_iterations;

public:

    // Default constructor
    CallableClass()
    {
        m_iterations=10;
    }

    // Constructor with number of iterations
    CallableClass(int iterations)
    {
        m_iterations=iterations;
    }

    // Copy constructor
    CallableClass(const CallableClass& source)
    {
        m_iterations=source.m_iterations;
    }

    // Destructor
    ~CallableClass()
    {
    }

    // Assignment operator
    CallableClass& operator = (const CallableClass& source)
    {
        m_iterations=source.m_iterations;
        return *this;
    }

    // Static function called by thread
    static void StaticFunction()
    {
        for (int i=0; i < 10; i++)  // Hard-coded upper limit
        {
            cout<<i<<"Do something in parallel (Static function)."<<endl;
            boost::this_thread::yield(); // 'yield' discussed in section 18.6
        }
    }

    // Operator() called by the thread
    void operator () ()
    {
        for (int i=0; i<m_iterations; i++)
        {
            cout<<i<<" - Do something in parallel (operator() )."<<endl;
            boost::this_thread::yield(); // 'yield' discussed in section 18.6
        }
    }

};

这如何成为可调用对象?是因为运算符重载还是构造函数或其他原因造成的?

How does this become a callable object? Is it because of the operator overloaded or the constructor or something else?

推荐答案

可调用对象是可以像函数一样调用的,其语法为object()object(args);也就是说,函数指针或类类型的对象会重载operator().

A callable object is something that can be called like a function, with the syntax object() or object(args); that is, a function pointer, or an object of a class type that overloads operator().

您的课程中operator()的重载使其可以调用.

The overload of operator() in your class makes it callable.

这篇关于什么是C ++中的可调用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆