Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a slide on visitor pattern with lambdas #87

Closed
sponce opened this issue Jan 19, 2022 · 2 comments · Fixed by #239
Closed

Add a slide on visitor pattern with lambdas #87

sponce opened this issue Jan 19, 2022 · 2 comments · Fixed by #239
Assignees
Labels
Advanced Content for the "advanced" course stale
Milestone

Comments

@sponce
Copy link
Contributor

sponce commented Jan 19, 2022

Originally posted by @sponce in #79 (comment)

@bernhardmgruber
Copy link
Contributor

So this is essentially the overload pattern:

template<typename... Ts>
struct Overload : Ts ... { 
    using Ts::operator()...;
};
template<typename... Ts>
Overload(Ts...) -> Overload<Ts...>;

int main(){
    std::variant<char, long, float, int, double, long long> v;
    auto overloadSet = Overload{
        [](char) { return "char"; },
        [](int) { return "int"; },
        [](unsigned int) { return "unsigned int"; },
        [](long int) { return "long int"; },
        [](long long int) { return "long long int"; },
        [](auto) { return "unknown type"; },
    };
    std::visit(overloadSet, v);
}

(excerpted from here)

There is a lot of stuff going on here like variadic templates, variadic using declarations of member functions, deduction guides and aggregate initialization into base classes. I would still show it to beginners, because the code is short and the usage is easy. But understanding why this works requires more knowledge on the language rules.

@chavid chavid added the Advanced Content for the "advanced" course label Feb 23, 2022
@roiser roiser added this to the Sept22 milestone Jun 15, 2022
@stale
Copy link

stale bot commented Aug 14, 2022

This issue or pull request has been automatically marked as stale because it has not had recent activity. Please manually close it, if it is no longer relevant, or ask for help or support to help getting it unstuck. Let me bring this to the attention of @klieret @wdconinc @michmx for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Advanced Content for the "advanced" course stale
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants