c++ - 函数作为 std::function 包装器的构造函数的参数

标签 c++ templates c++11

我正在编写 Monitor 类来解决同步问题,我想实现一个将包装 std::function 的“Entry”类。

我实现了一点,使用了函数特征,但现在我只能使用准备好的 std::function 对象构造 Entry 对象。尝试编写一个以普通函数作为参数的构造函数失败,并显示有关模板参数推导/替换和 参数的编译器消息。

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

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

最佳答案

有几件事:

template<F>

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

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

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

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

Live Demo


这是您的固定类(class)

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

关于c++ - 函数作为 std::function 包装器的构造函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35234023/

相关文章:

c++ - 从文件发出阅读空间

c++ - 根据 big O,一个清晰函数的时间复杂度是 std::map 是多少?

c++ - 强制转换尾随返回类型会导致 SFINAE 失败

c++ - 右值引用被视为左值?

c++ - "Undefined Reference"我已经声明和定义并#included 的函数错误

c++ - OpenGL - 加载多面的正确方法

c++ - 成员变量的通用声明

javascript - Django 中的 Django 压缩器和模板标签

c++11 - 为什么允许复制对象的单例设计模式甚至复制构造函数和赋值运算符都是私有(private)的?

c++ - 使复制的成员引用变量引用拷贝的成员而不是原始成员