Try to implement a tiny-any:
#include <iostream> #include <type_traits> #include <memory> class TinyAny { public: template <typename Tp> TinyAny(Tp&& val) : data(std::make_shared<unsigned char[]>(sizeof(val))) { new(data.get()) Tp(std::forward<Tp>(val)); } template <typename Tp> TinyAny &operator =(Tp&& val) { data = std::make_shared<unsigned char[]>(sizeof(val)); new(data.get()) Tp(std::forward<Tp>(val)); return *this; } template <typename Tp> Tp get() { return *reinterpret_cast<Tp *>(data.get()); } private: std::shared_ptr<unsigned char[]> data; }; int main() { // var = "abc"; // std::cout << var.get<const char *>() << std::endl; } if uncomment var = "abc" will get the fellowing error:
<source>: In instantiation of 'TinyAny& TinyAny::operator=(Tp&&) [with Tp = const char (&)[4]]': <source>:40:11: required from here <source>:17:9: error: new cannot be applied to a reference type 17 | new(data.get()) Tp(std::forward<Tp>(val)); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <source>:17:44: error: invalid conversion from 'const char*' to 'char' [-fpermissive] 17 | new(data.get()) Tp(std::forward<Tp>(val)); | ~~~~~~~~~~~~~~~~^~~~~ | | | const char* The type of val is const char*, but I cannot understand which one is char? Or, how can I fix this error?
Source Code: https://gcc.godbolt.org/z/zW7fPc6G3
std::any. I just want to implement a 'tiny-any' by normal memory which can be not type-safed or not highly-efficient. In fact, what confused me is the aboved error message.std::any's interface is like. Copying theanywill copy its contents, not merely reference a shared_ptr. And a "not type-safed" any is just avoid*so... just use that.var = "abc"is supposed to causevarto store aconst char[4]array or whether it is supposed to store achar*. If the former, you need some special cases, since thenewexpression doesn't work like this with an array type. If the latter, then you shouldstd::decaythe type when storing or retrieving.