调用一个以std :: function作为参数的函数

时间:2014-03-18 14:43:40

标签: c++ c++11 operator-overloading std-function

我有以下代码实现回调。我希望回调能够采用​​一些参数,但只能在没有参数的情况下进行编译。

#include <iostream>
#include <string>
#include <functional>

template<typename TDeserialisable>
class Images;
class Analyze;

class X
{
    void operator()(...) {}
};

/** Interface for serialising/deserialising types defined by TDeserialisable */
template<typename TDeserialisable>
class IDeserialisable
{
public:
    virtual void deserialise(std::function<void()> callback) = 0;
    virtual void deserialise(std::function<void(IDeserialisable<TDeserialisable>&)> callback) = 0;
};

class Analyze
{
public:
    void operator()()
    {
        // deserialise
    }

    void operator()(Images<Analyze>& images)
    {
        // deserialise
    }
};

template<typename TDeserialisable>
class Images : public IDeserialisable<TDeserialisable>
{
private:
    virtual void deserialise(std::function<void()> callback)
    {
        callback();
    }

    virtual void deserialise(std::function<void(IDeserialisable<TDeserialisable>&)> callback)
    {
        callback(*this);
    }
};

int main()
{
    Analyze a;
    Images<Analyze> images;

    // calls the first overload
    static_cast<IDeserialisable<Analyze>&>(images).deserialise(a);

    // how do I call the second overload of deserialise?

    return 0;
}

如何调用deserialise的第二个重载?

1 个答案:

答案 0 :(得分:0)

您需要将输入参数类型指定为std::function template类型的函数参数。类似的东西:

std::function<void(Analyze&, Images<Analyze>&)> mf_p = Analyze::operator();