函数作为std :: function wrapper

时间:2016-02-05 21:40:29

标签: c++ templates c++11

我正在为同步问题编写Monitor类,我想实现一个' Entry'将包装std :: function的类。

我实现了一点,使用了函数特性,但是现在我只能使用准备好的std :: function对象构造Entry对象。尝试编写具有普通函数作为参数的构造函数失败,编译器消息有关模板参数推断/替换和< anonymous>参数。

该程序正在运行,但我只是好奇如何实现给定的构造函数,这是我的代码:

template <class F>
struct FunctionType;
template <class R, class Object, class... Args>
struct FunctionType<R (Object::*)(Args...)> {
  typedef R return_type;
};
template <class R, class Object, class... Args>
struct FunctionType<R (Object::*)(Args...) const> {
  typedef R return_type;
};


template <class F> class Entry {
    std::function<F> internalFunction;

    ...

public:
    template <F> Entry(const F& function){
        // It doesn't work.
    }

    template <F> Entry(const std::function<F> function) :
        internalFunction(function) {

    }

    template<F, class... Arguments>
    typename FunctionType<F>::return_type operator()(Arguments... arguments){
        return internalFunction(arguments...);
    }
};

1 个答案:

答案 0 :(得分:2)

有几件事:

template<F>

根本没有任何意义。您从类的模板参数中获取F的类型,使用它并完全删除它。

接下来,您可能更容易在operator()函数上使用尾随返回类型:

template<class... Arguments>
auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...))
{
  return internalFunction(arguments...);
}

(如果你有C ++ 14,你可以使用auto)。

Live Demo

这是您的固定班级

template <class F> class Entry {
    std::function<F> internalFunction;

public:
    Entry(const F& function){
        // It doesn't work.
    }

    Entry(const std::function<F> function) :
        internalFunction(function) {

    }

    template<class... Arguments>
    auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...)){
        return internalFunction(arguments...);
    }
};
相关问题