This implementation is close to correct, but it looks like it has a few bugs. For example, this code:
if (typeid(T).name() != mClassName)
is not guaranteed to work correctly because the .name()
function in type_info
is not guaranteed to return a unique value for each type. If you want to check if the types match, you should probably use something like this:
if (typeid(*mImpl) == typeid(VariantImpl<T>))
Which more accurately checks if the type matches. Of course, you need to watch out for const
issues, since storing a const T
and storing a T
will yield different types.
As for your question about dynamic_cast
, in the case you've described you don't need to use the dynamic_cast
because you already have a check to confirm that the type will match. Instead, you can just use a static_cast
, since you've already caught the case where you have the wrong type.
More importantly, though, what you've defined here is an "unrestricted variant" that can hold absolutely anything, not just a small set of restricted types (which is what you'd normally find in a variant). While I really like this code, I'd suggest instead using something like Boost.Any or Boost.Variant, which has been extensively debugged and tested. That said, congrats on figuring out the key trick that makes this work!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…