你知道,我们可以将 lambda 函数包装或存储到std::function
:
#include <iostream>
#include <functional>
int main()
{
std::function<float (float, float)> add = [](float a, float b)
// ^^^^^^^^^^^^^^^^^^^^
{
return a + b;
};
std::cout << add(1, 2) << std::endl;
}
我的问题是围绕std::function
,正如你所看到的,它是一个模板类,但它可以接受任何类型的函数签名.
例如float (float, float)
以这种形式return_value (first_arg, second_arg)
.
其结构是怎样的std::function
它如何接受像这样的函数签名x(y,z)
以及它是如何运作的?是float (float, float)
C++ 中新的有效表达式?
它使用一些类型擦除技术.
一种可能性是将混合子类型多态性与模板结合使用。这是一个简化版本,只是为了让大家了解整体结构:
template <typename T>
struct function;
template <typename Result, typename... Args>
struct function<Result(Args...)> {
private:
// this is the bit that will erase the actual type
struct concept {
virtual Result operator()(Args...) const = 0;
};
// this template provides us derived classes from `concept`
// that can store and invoke op() for any type
template <typename T>
struct model : concept {
template <typename U>
model(U&& u) : t(std::forward<U>(u)) {}
Result operator()(Args... a) const override {
t(std::forward<Args>(a)...);
}
T t;
};
// this is the actual storage
// note how the `model<?>` type is not used here
std::unique_ptr<concept> fn;
public:
// construct a `model<T>`, but store it as a pointer to `concept`
// this is where the erasure "happens"
template <typename T,
typename=typename std::enable_if<
std::is_convertible<
decltype( t(std::declval<Args>()...) ),
Result
>::value
>::type>
function(T&& t)
: fn(new model<typename std::decay<T>::type>(std::forward<T>(t))) {}
// do the virtual call
Result operator()(Args... args) const {
return (*fn)(std::forward<Args>(args)...);
}
};
(请注意,为了简单起见,我忽略了几件事:它无法复制,也许还有其他问题;不要在实际代码中使用此代码)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)