I was trying some things and came to the following question: Is there a possibility to store references to a value in a std::any
?
I tried the following approaches:
#include <any>
#include <iostream>
#include <functional>
auto func_by_pointer(std::any obj)
{
*std::any_cast<int *>(obj) += 2;
}
auto modify_by_pointer(int &a)
{
func_by_pointer(std::make_any<int *>(&a));
}
auto func_by_reference_wrapper(std::any obj)
{
std::any_cast<std::reference_wrapper<int>>(obj).get() -= 2;
}
auto modify_by_reference_wrapper(int &a)
{
func_by_reference_wrapper(std::make_any<std::reference_wrapper<int>>(a));
}
auto func_by_reference(std::any obj)
{
std::any_cast<int &>(obj) *= 2;
}
auto modify_by_reference(int &a)
{
func_by_reference(std::make_any<int &>(a));
}
int main()
{
auto value = 3;
std::cout << value << '\n';
modify_by_pointer(value);
std::cout << value << '\n';
modify_by_reference_wrapper(value);
std::cout << value << '\n';
modify_by_reference(value);
std::cout << value << '\n';
}
The result is the following output:
3
5
3
3
Yet, I was expecting it to be:
3
5
3
6
Thus, passing a pointer to value
works fine. Passing a std::reference_wrapper
to value
works fine as well, but passing int&
somehow doesn't work. Did I do something wrong in my code, or is it generally not possible to store references inside a std::any
?
As such, when the original pointers are deleted and they are set to nullptr , in the vector we'd know exactly about it. The only problem is that in C++ one cannot store references to pointers.
std::reference_wrapper It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.
As you know, an address of an object in C++ can be stored either through a reference or through a pointer. Although it might appear that they represent similar concepts, one of the important differences is that you can reassign a pointer to point to a different address, but you cannot do this with a reference.
The class any describes a type-safe container for single values of any copy constructible type. 1) An object of class any stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the state of the class any object.
You cannot store references in std::any
because, for a given type T
, the constructor std::any(T)
stores a value of type std::decay_t<T>
, which removes reference qualifiers:
[any.cons]
template<class T> any(T&& value);
Let
VT
bedecay_t<T>
.Requires:
VT
shall satisfy theCpp17CopyConstructible
requirements.Effects: Constructs an object of type
any
that contains an object of typeVT
direct-initialized withstd::forward<T>(value)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With