In the code below, is there a way to implement const_foobar foobar_manager::get_foobar() const in terms of the non-const version without the visit or equivalent code?
#include <variant>
#include <string>
struct foo {
int val;
std::string str;
};
struct bar {
double val;
std::string str;
};
using foobar = std::variant<foo, bar>;
using const_foobar = std::variant<const foo, const bar>;
class foobar_manager {
public:
foobar get_foobar() {
// the primary implementation of whatever needs to
// happen to get the variant we want would go here.
return foo{ 42, "mumble" };
}
const_foobar get_foobar() const {
// we want to get the const variant in terms of the
// the getting logic for the non-const case. Can
// it be done without a visit?
return std::visit(
[](auto v)->const_foobar {
return v;
},
const_cast<foobar_manager*>(this)->get_foobar()
);
}
};
int main() {
foobar_manager fm;
const auto& const_fm = fm;
auto test1 = fm.get_foobar();
auto test2 = const_fm.get_foobar();
return 0;
}
constvariantsufficient in your case?constversion should be primary, and non-const version implemented in terms of it.const_cast<foobar_manager*>(this)exhibits undefined behavior when*thisobject is actually defined asconst.std::experimental/propagate_constmight help for theconst std::variant.