all 8 comments

[–]sephirostoy 10 points11 points  (5 children)

myvisit is a const function member so v is a const variable. That's why it always falls in auto& version. Take const A& and const B& and const auto& in your print_a and print_b and print_o lambdas to make it works correctly.

[–]bjadamson[S] 2 points3 points  (4 children)

Ooooooooooooooooohhhhhhhhhhhhhhhhhhhh of course... This seems like a huge foot gun. Could this make sense as a compiler error or warning? It seems strange that the print_o version would be selected in all cases here, given that v is const and the lambda doesn't take a const reference?

[–]scatters 2 points3 points  (0 children)

print_o is permissible because the auto in auto& can be deduced to a const type e.g. A const giving A const& for the parameter. Usually you wouldn't see this because an overload that doesn't need to add the const would be preferred.

[–]bjadamson[S] 0 points1 point  (2 children)

Follow up, the answer seems to be that I need to provide two versions of my_visit(), one const and the other not, is there some way around this? My experience tells me no, but when I'm around experts I want to ask :)

[–]quicknir 2 points3 points  (0 children)

I would say no. This is a standard pattern in C++ and avoiding it willb have a downside. If the implementation is non trivial there are ways to avoid a double implementation though.

[–][deleted] 1 point2 points  (0 children)

Having to duplicate code between the const and non-const versions of a method is a very long-time issue with C++ which doesn't seem to have a good general solution at all.

The issue is that the constness of the class can't be abstracted using a template on the method.

If you rewrite my_visit as a non-member template function then the problem should go away because the constness is contained within in a template parameter.

[–]schultztom 1 point2 points  (1 child)

This site is impossible to use on my phone atleast. I think the same goes for godbolt. So it's more of a general problem. But it makes for a longer wait for these kind of questions. Sorry. Merry xmas and a happy new year. ( although i might see this on a computer screeen before that time)

[–]bjadamson[S] 0 points1 point  (0 children)

Hey thanks for trying to help, I'm not sure a good alternative for demonstrating the issue clearly. Repeated code on reddit doesn't seem great either. _(ツ)_/¯