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