Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

One of the worst design decisions in C++ (IMO, of course) is the template syntax. Templates are proper macros, abstractions over code in the sense of lisp. But C++ hides this fact by relying (mostly) on implicit template application and very, very, indirect syntax for template abstraction.

For instance: who came up with the idea of templated lambdas? Yes, manually managed closures are very C++, and yes, templated closures are also very much C++. But now we have templated closures that capture local variables IF THEY EVER HAPPEN TO BE INSTANTIATED. What the actual cluster eff?



Perhaps I'm just dense today, but I'm still not seeing the problem with templated lambdas... if you could spell it out, I'd be much obliged!

Also, I'd assume the closure is instantiated (and the vars captured) regardless of whether its ever called, but I could be wrong.


Can you imagine C++ templates without template parameter deduction?

What's the alternative: spelling out all the parameter values, wherever the template is used?

    mult<int, double>(x, add<double, double>(y, z));
C++ templates use type information to deduce parameters. Lisp macros may be expanded before any type analysis takes place.

The fact that you can just write:

    mult(x, add(y, z))
and the language figures out the parameters for the mult and add templates from the declared types of x, y and z doesn't really have any parallel in mainstream Lisp dialects.

The idiomatic solution would involve making the functions themselves generic so they dispatch on the actual types of the arguments.

Anything relying on declared or inferred type would be a second-class citizen in a dynamic language anyway, where declarations are optional, and inference may be imperfect or absent.


It doesn't capture the variables "if they ever happen to be instantiated." They get captured once; the lambda gets instantiated. It's the operator() method that is templated, not the lambda object's type itself. Basically a template lambda might be equivalent to this:

    struct foo {
        std::string capture;
        template <class T>
        std::string operator()(T x) {
            return capture + std::to_string(x);
        }
    };


Templated lambdas are extremely powerful. Think for example of (recursive) visitations of etherogeneous containers.


I tried; the house began shaking, there was a sudden eclipse and blood started trickling down the walls. Is that supposed to happen?


Have you tried compiling with -O0 -g -Wstrict-exorcism ?


Something like that yes.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: