0

I'm trying to implement boost::any like class:

struct any { private: struct holderBase { virtual ~holderBase(){} }; template<typename T> struct holder : public holderBase { T content; holder(const T& value) : content(value){} holder(const holder<T>& other) : content(other.content){} }; holderBase *hl; public: template<typename T> any(const T& data = T()) { hl = new holder<T>(data); } any(const any& other) { hl = other.hl; } template<typename T> T get() { if(holder<T>* p_hl = dynamic_cast<holder<T>*>(hl)) return p_hl->content; else throw std::runtime_error("std::runtime_error"); } }; 

I use a holder class (inherited by holderBase) to store the data. How can I modify the any::get() function (or even modify the whole code) so that it doesn't need a template parameter (the get() function)?

0

2 Answers 2

1

You could do it like this:

template<typename T> T get(T *ptr); 

Similar to the C time function, you would return the result, as well as store it in ptr.

Edit: You could also override the casting operator:

template<typename T> operator T() { return get<T>(); } 

Which will implicitly do what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the first option, I would avoid the second at all costs. Implicit conversions are a bad idea in general, and implicit conversions to any type are the worst of them.
0

Stating the obvious: If you don't want to return 1 particular type to the user then it needs to be templated. There's nothing you can do about it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.