Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4070698
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T16:39:39+00:00 2026-05-20T16:39:39+00:00

Note: I’m aware of boost::variant , but I am curious about the design principles.

  • 0

Note: I’m aware of boost::variant, but I am curious about the design principles. This question mostly for self-education.

Original post

At my current job I found an old variant class implementation. It’s implemented with a union and can only support a handful of datatypes. I’ve been thinking about how one should go about designing an improved version. After some tinkering I ended up with something that seems to work. However I’d like to know your opinion about it. Here it is:

#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <boost/shared_ptr.hpp>

class Variant
{
public:
    Variant() { }

    template<class T>
    Variant(T inValue) :
        mImpl(new VariantImpl<T>(inValue)),
        mClassName(typeid(T).name())
    {
    }

    template<class T>
    T getValue() const
    {
        if (typeid(T).name() != mClassName)
        {
            throw std::logic_error("Non-matching types!");
        }

        return dynamic_cast<VariantImpl<T>*>(mImpl.get())->getValue();
    }

    template<class T>
    void setValue(T inValue)
    {
        mImpl.reset(new VariantImpl<T>(inValue));
        mClassName = typeid(T).name();
    }

private:
    struct AbstractVariantImpl
    {
        virtual ~AbstractVariantImpl() {}
    };

    template<class T>
    struct VariantImpl : public AbstractVariantImpl
    {
        VariantImpl(T inValue) : mValue(inValue) { }

        ~VariantImpl() {}

        T getValue() const { return mValue; }

        T mValue;
    };

    boost::shared_ptr<AbstractVariantImpl> mImpl;
    std::string mClassName;
};

int main()
{
    // Store int
    Variant v(10);
    int a = 0;
    a = v.getValue<int>();
    std::cout << "a = " << a << std::endl;

    // Store float
    v.setValue<float>(12.34);
    float d = v.getValue<float>();
    std::cout << "d = " << d << std::endl;

    // Store map<string, string>
    typedef std::map<std::string, std::string> Mapping;
    Mapping m;
    m["one"] = "uno";
    m["two"] = "due";
    m["three"] = "tre";
    v.setValue<Mapping>(m);
    Mapping m2 = v.getValue<Mapping>();
    std::cout << "m2[\"one\"] = " << m2["one"] << std::endl;
    return 0;
}

Output is correct:

a = 10
d = 12.34
m2["one"] = uno

My SO questions are:

  • Is this implementation correct?
  • Will the dynamic cast in getValue() work as expected (I’m not certain)
  • Should I return T as a const reference instead? Or can I count on return-value-optimization to kick in?
  • Any other problems or suggestions?

Update

Thanks to @templatetypedef for his suggestions. This updated version only uses dynamic_cast to check if the types match. Type mismatches caused by differences in constness are now avoided thanks to the TypeWrapper classes (which I have shamelessly stolen from the Poco C++ project).

So this is the current version. It’s likely to contain a few errors though, as I’m not familiar with the idea of modifying const/ref on template templates. I’ll have a fresh look tomorrow.

template <typename T>
struct TypeWrapper
{
    typedef T TYPE;
    typedef const T CONSTTYPE;
    typedef T& REFTYPE;
    typedef const T& CONSTREFTYPE;
};

template <typename T>
struct TypeWrapper<const T>
{
    typedef T TYPE;
    typedef const T CONSTTYPE;
    typedef T& REFTYPE;
    typedef const T& CONSTREFTYPE;
};

template <typename T>
struct TypeWrapper<const T&>
{
    typedef T TYPE;
    typedef const T CONSTTYPE;
    typedef T& REFTYPE;
    typedef const T& CONSTREFTYPE;
};

template <typename T>
struct TypeWrapper<T&>
{
    typedef T TYPE;
    typedef const T CONSTTYPE;
    typedef T& REFTYPE;
    typedef const T& CONSTREFTYPE;
};

class Variant
{
public:
    Variant() { }

    template<class T>
    Variant(T inValue) :
        mImpl(new VariantImpl<typename TypeWrapper<T>::TYPE>(inValue))
    {
    }

    template<class T>
    typename TypeWrapper<T>::REFTYPE getValue()
    {
        return dynamic_cast<VariantImpl<typename TypeWrapper<T>::TYPE>&>(*mImpl.get()).mValue;
    }

    template<class T>
    typename TypeWrapper<T>::CONSTREFTYPE getValue() const
    {
        return dynamic_cast<VariantImpl<typename TypeWrapper<T>::TYPE>&>(*mImpl.get()).mValue;
    }

    template<class T>
    void setValue(typename TypeWrapper<T>::CONSTREFTYPE inValue)
    {
        mImpl.reset(new VariantImpl<typename TypeWrapper<T>::TYPE>(inValue));
    }

private:
    struct AbstractVariantImpl
    {
        virtual ~AbstractVariantImpl() {}
    };

    template<class T>
    struct VariantImpl : public AbstractVariantImpl
    {
        VariantImpl(T inValue) : mValue(inValue) { }

        ~VariantImpl() {}

        T mValue;
    };

    boost::shared_ptr<AbstractVariantImpl> mImpl;
};
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T16:39:40+00:00Added an answer on May 20, 2026 at 4:39 pm

    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!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Note: To answer this question, you shouldn't have to know anything about Selenium or
note: I'm working on wordpress but this isn't a wordpress question. I have a
Note: This might seem like a Super User question at first, but please read
Note bene: I realize this is an immensely complicated question with about a million
Note this question was originally posted in 2009, before C++11 was ratified and before
Note: This question has broadened in scope from previous revisions. I have tried to
NOTE: I have solved the majority of this problem but have run into a
NOTE: This question is only loosely related to tinyxml, however including details like that
note: this question is related to PostGIS and Postgresql and is implemented with PHP
Note: This question is similar to How to prevent the copy of XML documentation

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.