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 5944941
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T16:36:43+00:00 2026-05-22T16:36:43+00:00

I have a map which represents a configuration. It’s a map of std::string and

  • 0

I have a map which represents a configuration. It’s a map of std::string and boost::any.

This map is initialized at the start and I’d like the user to be able to override these options on the command line.

What I’d love to do is build the program options from this map using the options_description::add_option() method. However, it takes a template argument po::value<> whereas all I have is boost::any.

So far, I just have the shell of the code. m_Config represents my configuration class, and getTuples() returns a std::map<std::string, Tuple>. TuplePair is a typedef of std::pair<std::string, Tuple> and the Tuple contains the boost::any I am interested in.

    po::options_description desc;
    std::for_each(m_Config.getTuples().begin(),
                  m_Config.getTuples().end(),
                  [&desc](const TuplePair& _pair)
    {
            // what goes here? :)
            // desc.add_options() ( _pair.first, po::value<???>, "");
    });

Is there a way to build it this way, or do I need to resort to doing it myself?

Thanks in advance!

  • 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-22T16:36:43+00:00Added an answer on May 22, 2026 at 4:36 pm

    boost::any is not applicable to your problem. It performs the most basic form of type erasure: storage and (type-safe) retrieval, and that’s it. As you’ve seen, no other operations can be performed. As jhasse points out, you could just test every type you want to support, but this is a maintenance nightmare.

    Better would be to expand upon the idea boost::any uses. Unfortunately this requires a bit of boiler-plate code. If you’d like to try it, there’s a new Boost library being discussed right now on the mailing list (titled “[boost] RFC: type erasure”) that is essentially a generalized type erasure utility: you define the operations you’d like your erased type to support, and it generates the proper utility type. (It can simulate boost::any, for example, by requiring the erased type be copy-constructible and type-safe, and can simulate boost::function<> by additionally requiring the type be callable.)

    Aside from that, though, your best option is probably to write such a type yourself. I’ll do it for you:

    #include <boost/program_options.hpp>
    #include <typeinfo>
    #include <stdexcept>
    
    namespace po = boost::program_options;
    
    class any_option
    {
    public: 
        any_option() :
        mContent(0) // no content
        {}
    
        template <typename T>
        any_option(const T& value) :
        mContent(new holder<T>(value))
        {
            // above is where the erasure happens,
            // holder<T> inherits from our non-template
            // base class, which will make virtual calls
            // to the actual implementation; see below
        }
    
        any_option(const any_option& other) :
        mContent(other.empty() ? 0 : other.mContent->clone())
        {
            // note we need an explicit clone method to copy,
            // since with an erased type it's impossible
        }
    
        any_option& operator=(any_option other)
        {
            // copy-and-swap idiom is short and sweet
            swap(*this, other);
    
            return *this;
        }
    
        ~any_option()
        {
            // delete our content when we're done
            delete mContent;
        }
    
        bool empty() const
        {
            return !mContent;
        }
    
        friend void swap(any_option& first, any_option& second)
        {
            std::swap(first.mContent, second.mContent);
        }
    
        // now we define the interface we'd like to support through erasure:
    
        // getting the data out if we know the type will be useful,
        // just like boost::any. (defined as friend free-function)
        template <typename T>
        friend T* any_option_cast(any_option*);
    
        // and the ability to query the type
        const std::type_info& type() const
        {
            return mContent->type(); // call actual function
        }
    
        // we also want to be able to call options_description::add_option(),
        // so we add a function that will do so (through a virtual call)
        void add_option(po::options_description desc, const char* name)
        {
            mContent->add_option(desc, name); // call actual function
        }
    
    private:
        // done with the interface, now we define the non-template base class,
        // which has virtual functions where we need type-erased functionality
        class placeholder
        {
        public:
            virtual ~placeholder()
            {
                // allow deletion through base with virtual destructor
            }
    
            // the interface needed to support any_option operations:
    
            // need to be able to clone the stored value
            virtual placeholder* clone() const = 0;
    
            // need to be able to test the stored type, for safe casts
            virtual const std::type_info& type() const = 0;
    
            // and need to be able to perform add_option with type info
            virtual void add_option(po::options_description desc,
                                        const char* name) = 0;
        };
    
        // and the template derived class, which will support the interface
        template <typename T>
        class holder : public placeholder
        {
        public:
            holder(const T& value) :
            mValue(value)
            {}
    
            // implement the required interface:
            placeholder* clone() const
            {
                return new holder<T>(mValue);
            }
    
            const std::type_info& type() const
            {
                return typeid(mValue);
            }
    
            void add_option(po::options_description desc, const char* name)
            {
                desc.add_options()(name, po::value<T>(), "");
            }
    
            // finally, we have a direct value accessor
            T& value()
            {
                return mValue;
            }
    
        private:
            T mValue;
    
            // noncopyable, use cloning interface
            holder(const holder&);
            holder& operator=(const holder&);
        };
    
        // finally, we store a pointer to the base class
        placeholder* mContent;
    };
    
    class bad_any_option_cast :
        public std::bad_cast
    {
    public:
        const char* what() const throw()
        {
            return "bad_any_option_cast: failed conversion";
        }
    };
    
    template <typename T>
    T* any_option_cast(any_option* anyOption)
    {
        typedef any_option::holder<T> holder;
    
        return anyOption.type() == typeid(T) ? 
                &static_cast<holder*>(anyOption.mContent)->value() : 0; 
    }
    
    template <typename T>
    const T* any_option_cast(const any_option* anyOption)
    {
        // none of the operations in non-const any_option_cast
        // are mutating, so this is safe and simple (constness
        // is restored to the return value automatically)
        return any_option_cast<T>(const_cast<any_option*>(anyOption));
    }
    
    template <typename T>
    T& any_option_cast(any_option& anyOption)
    {
        T* result = any_option_cast(&anyOption);
        if (!result)
            throw bad_any_option_cast();
    
        return *result;
    }
    
    template <typename T>
    const T& any_option_cast(const any_option& anyOption)
    {
        return any_option_cast<T>(const_cast<any_option&>(anyOption));
    }
    
    // NOTE: My casting operator has slightly different use than
    // that of boost::any. Namely, it automatically returns a reference
    // to the stored value, so you don't need to (and cannot) specify it.
    // If you liked the old way, feel free to peek into their source.
    
    #include <boost/foreach.hpp>
    #include <map>
    
    int main()
    {
        // (it's a good exercise to step through this with
        //  a debugger to see how it all comes together)
        typedef std::map<std::string, any_option> map_type;
        typedef map_type::value_type pair_type;
    
        map_type m;
    
        m.insert(std::make_pair("int", any_option(5)));
        m.insert(std::make_pair("double", any_option(3.14)));
    
        po::options_description desc;
    
        BOOST_FOREACH(pair_type& pair, m)
        {
            pair.second.add_option(desc, pair.first.c_str());
        }
    
        // etc.
    }
    

    Let me know if something is unclear. 🙂

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

Sidebar

Related Questions

i have a scroll view which represents a map, it has pins on it,
I have some opaque bytes which I want to use in an std::map ,
I have a List<HashMap<String,Object>> which represents a database where each list record is a
I have a Map which is to be modified by several threads concurrently. There
I have made a map with jQuery which is split up in many regions,
I have a Map model, which defines the details for an ASCII-art map for
Is it preferred to have one depot with multiple folders which map to different
I have a bean which I map to the database using Hibernate. I'm using
I have the following hsqldb table, in which I map UUIDs to auto incremented
I have an App which launches the google Map App. The code is: UIApplication

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.