werico4026
werico4026

Reputation: 73

std::vector<std::any> returning the size

im trying to get the size of a std::vector<std::any>

My function works when the vector is a int but how would i get it to work with std::any

template<typename T>
size_t vectorsizeof(const typename std::vector<T>& vec)
{
    return sizeof(T) * vec.size();
}

std::vector<std::any> args = { (int)3, (bool)true };
auto size = vectorsizeof(args);

Upvotes: 1

Views: 247

Answers (2)

alfC
alfC

Reputation: 16270

The std::any instances do not know the underlying type of the objects they hold, so they do not know the size of the type either.

However you can make a wrapper to std::any that remembers the size.

class any_with_size : std::any{
    template<class T> any_with_size(T const& t) : std::any(t), s_{sizeof(T)}{}
    template<class T> any_with_size& operator=(T const& t){s_ = sizeof(T); std::any::operator==(t); return *this;}
    ...
    std::size_t dynamic_sizeof() const{return s_;}
private:
    std::size_t s_;
}

This gets closer to something called type erasure if you start adding functions that you know can be applied to some particular set of types.

Upvotes: 0

eerorika
eerorika

Reputation: 238411

My function works when the vector is a int but how would i get it to work with std::any

return sizeof(T) * vec.size();

This function already works with std::any as well as it works with int. Assuming the intention is to return the size of the dynamic array of the vector in bytes.

WriteProcessMemory(hProc, pMemory, args.data(), vectorsizeof(args), nullptr) this works with a int vector, but does not seem to work with a std::any

Indeed. That can only work with trivially copyable types. int is trivially copyable. std::any is not trivially copyable. The problem is not with vectorsizeof. Knowing the size of the object will not help you copy non-trivially-copyable objects byte-wise.

Communicating non-trivial data structures across processes necessitates translating it into a format that can represent the structure as raw bytes. Such translation is called serialisation. There is no way to serialise std::any, but it may be possible to serialise whatever type the std::any contains, if you know that type.

Upvotes: 1

Related Questions