I can't get std::any running properly in the following peace of code. What I'd like to achieve is to return a reference/ pointer to the object hold by std::any. The version below using a void pointer is just running fine.
How can I translate that using std::any.
Why is std::any_cast designed to return a copy of the internal object anyway?
Thank you!
struct ReadOperation
{
public:
template <LeafnodeConcept L>
static bool visitLeafnode(L *l)
{
value = &(l->data);
return false;
}
template <NodeLike N> static bool previsit(N* n)
{
return false;
}
template <class T>
static const T GetValue()
{
// return std::any_cast<T>(value);
return *static_cast<T*>(value);
}
template<class T>
static const T* GetValueRef()
{
return static_cast<T*>(value);
}
private:
// inline static std::any value = nullptr;
inline static void* value = nullptr;
};
Thank you for pointing out the right way to use std::any_cast in the comments. I created a sample which seems to work as expected.
But this is just half the truth. The original question was about how to imitate the use of a void pointer. And the solution is: Just use std::any exactly the way you'd use a void pointer.
It's straight forward: just wrap the pointer to your object to std::any, not the object itself. This will prevent it from creating a forwarded instance on the heap.
Result: All memory locations should be the same as opposed to the previous example where you'll get a reference/pointer to the instance hold by the std::any value.
And finally, revisiting to the original questions on how to subsitute the void pointer by std::any we end up with: