Are all lambdas inside template lambdas also masked by lambdas?

Consider this code (which compiles on GCC and MSVC):

int main()
{
    auto foo = [](auto p){
        typedef decltype(p) p_t;
        auto bar = [](){
            return static_cast<p_t>(10);
        };
        return bar();
    };

    std::cout << foo(0ull) << std::endl;
}

foo()is a template lambda because it has a parameter auto. But for bar(), in order to find out the type p_t, it must somehow be an implicit template too, which then leads me to the question in the header:

Have all lambdas inside lambdas templates been also archived by lambdas?

If this is the case, then it seems that the number of template parameters will grow quite quickly if I have a lot of nested lambdas (not necessarily bad, but it comes as a surprise to me).

+4
source share
1 answer

, , . lambda auto template , :

#include <iostream>

auto foo = [](auto param){};

template <class T>
struct functor_template { 
    void operator()() const { }
};

template <template <class...> class Foo, class... Ts>
void bar(Foo<Ts...>) {
}

int main() {
    //bar(foo); //prog.cc:7:6: note:   template argument deduction/substitution failed
    bar(functor_template<int>{});
}

- , , operator().


, , , . - . :

#include <iostream>
#include <type_traits>

auto foo = [](auto p){
        static_cast<void>(p);
        typedef decltype(p) p_t;
        auto bar = [](){
            return static_cast<p_t>(10);
        };
        return bar;
    };

int main() {
    static_cast<void>(foo);
    std::cout << std::is_same<decltype(foo(int{})), decltype(foo(float{}))>::value << std::endl;
    std::cout << std::is_same<decltype(foo(int{})), decltype(foo(int{}))>::value << std::endl;
}

:

0
1
+1

Source: https://habr.com/ru/post/1677058/


All Articles