29 Eylül 2020 Salı

std::declval

Tanımı
Şuna benzer
template<class T>
typename std::add_rvalue_reference<T>::type declval() noexcept;
Açıklaması şöyle
In some contexts, we don’t have the objects available that we need to pass to an expression to evaluate it in decltype and similar functionalities. We might even not be able to create those objects at all, e.g. because their classes have only private or protected constructors.
...
For those cases, std::declval comes in handy. It is just a declared function template that returns an rvalue reference to whatever you pass to it. That way we don’t need to artificially declare a poorly named function to have something that we can use in our decltype argument: decltype(f(std::declval<int>()))

It comes especially handy if you are in a templated context and the value you want to obtain depends on a template parameter.
Örnek
Şöyle yaparız. Sanki C tipinden bir nesne varmış gibi davranır. Aslında C nesnesini normalde ilklendiremeyiz. Burada C nesnesini foo() metodunun döndürdüğü tip türünden (yani int) n değişkeni tanımlanır
struct C {
    C() = delete;
    int foo() { return 0; }
};


int main() {
    decltype(declval<C>().foo()) n = 1;
    cout << n << endl;
}

Hiç yorum yok:

Yorum Gönder