什么是C++中的可调用对象?

Xeg*_*ara 17 c++ multithreading object callable

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

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

};
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*our 16

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

类中的重载operator()使其可调用.


mas*_*oud 5

至少具有重载的对象operator()可调用对象,并且该运算符及其对象可以函数调用一样被调用:

CallableClass obj;
obj();
Run Code Online (Sandbox Code Playgroud)


Pau*_*ans 5

可调用对象是来自具有重载的类的对象实例operator()

struct Functor {
    ret_t operator()();
    // ...
}

Functor func;  // func is a callable object
Run Code Online (Sandbox Code Playgroud)

或解引用函数指针:

ret_t func() {
   // ...
}

func;  // func converts to a callable object
Run Code Online (Sandbox Code Playgroud)


Pet*_*ker 5

这里有两个步骤。在C ++标准中,“函数对象”是可以出现在带括号的参数列表左侧的对象,即指向函数的指针或类型为一个或多个operator()s 的对象。术语“可调用对象”范围更广:它还包括指向成员的指针(不能使用常规函数调用语法来调用)。可调用对象是可以传递给std::bind等的对象。请参见20.8.1 [func.def]和20.8 [function.objects] / 1。