Nasıl std::fonksiyon çalışır
Size veya std::function
bir lambda fonksiyonu wrap mağaza başlayabilirim.:
#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;
}
Benim sorum bir şablon sınıf gördüğünüz gibi std::function
, civarında ama her türlü kabul edebilirimza fonksiyonu.
Bu örneğin float (float, float)
return_value (first_arg, second_arg)
form.
std::function
yapısı nedir ve nasıl çalışır nasıl x(y,z)
gibi bir işlev imza ve kabul ediyor mu? float (float, float)
C yeni geçerli bir ifadedir ?
CEVAP
type erasure technique bazı kullanır.
Bir olasılık şablonları ile karıştırın alt polimorfizmi kullanmaktır. İşte basitleştirilmiş bir versiyonu, sadece genel yapısı hakkında bir fikir vermek için:
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)...);
}
};
(Kolaylık olması için bazı şeyleri Gözden kaçırmışım not: kopyalanan olamaz, ve belki de diğer sorunlar; gerçek kod bu kodu kullanmak) yok
JavaScript kilitler nasıl çalışır?...
CSS üçgenler nasıl çalışır?...
Veri bağlama Nasıl çalışır?AngularJS :...
Nasıl veritabanı indeksleme çalışır?...
Bit shift (bit-shift) operatörleri ned...