我正在编写 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
)。
这是您的固定类(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/