Reputation: 14688
Is only the way to modify, not replace, an object stored as std::any
is to declare changeable data mutable? E.g. to avoid creation and copy of class S instances:
#include <iostream>
#include <vector>
#include <any>
#include <string>
struct S {
mutable std::string str;
S(S&& arg) : str(std::move(arg.str)) { std::cout << ">> S moved" << std::endl; }
S(const S& arg) : str(arg.str) { std::cout << ">> S copied" << std::endl; }
S(const char *s) : str(s) { std::cout << ">> S created" << std::endl; }
S& operator= (const S& arg) { str = arg.str; return *this; }
S& operator= (S&& arg) { str = std::move(arg.str); return *this; }
virtual ~S() { std::cout << "<< S destroyed" << std::endl; }
};
int main() {
std::vector<std::any> container;
container.emplace_back(S("Test 1"));
std::any_cast<const S&>(container[0]).str = "Test 2";
for (const auto& a : container) {
std::cout << a.type().name() << ", "
<< std::any_cast<const S&>(a).str << std::endl;
}
}
Upvotes: 1
Views: 101
Reputation: 218268
You can any_cast with non-const reference:
std::any_cast<S&>(container[0]).str = "Test 2";
or
std::any a = 40;
std::any_cast<int&>(a) += 2;
std::cout << std::any_cast<int>(a) <<std::endl;
Upvotes: 4
Reputation: 118
nope.
The issue is here.
std::any_cast<const S&>(container[0]).str = "Test 2";
you are trying to change constant data
Upvotes: 0