variable return type in c++ class

前端 未结 7 1733
花落未央
花落未央 2021-01-25 08:33

i have a class with the following structure:

class myClass
{
    private:
        int type;
        classOne objectOne;
        classTwo objectTwo;
    public:
          


        
7条回答
  •  野的像风
    2021-01-25 09:00

    You can use Boost.Variant to do this. A variant can be constructed directly from any value convertible to one of its bounded types. Similarly, a variant can be assigned any value convertible to one of its bounded types. Heres how you could use it in your class:

    class myClass
    {
        private:
            boost::variant obj;
        public:
            myClass(classOne object) : obj(object)
            {
            }
            myClass(classTwo object) : obj(object)
            {
            }
    };
    

    It also provides a very convenient boost::get to retrieve the value from the variant. You can use that to supply code for each bounded type you have(ie classOne and classTwo). Here is an example:

    if (classOne * x = boost::get(&obj))
    {
        //Code for classOne
    }
    else if (classTwo * x = boost::get(&obj)
    {
        //Code for classTwo
    }
    

    However, such code is quite brittle, and without careful attention will likely lead to the introduction of subtle logical errors detectable only at runtime. Thus, real-world use of variant typically demands an access mechanism more robust than get. For this reason, variant supports compile-time checked visitation via apply_visitor. Visitation requires that the programmer explicitly handle (or ignore) each bounded type. Failure to do so results in a compile-time error.

    Visitation of a variant requires a visitor object. Like this:

    class object_visitor
    : public boost::static_visitor<>
    {
    public:
    
        void operator()(classOne & x) const
        {
            //Code for classOne
        }
    
        void operator()(classTwo & x) const
        {
            //Code for classTwo
        }
    
    };
    

    With the implementation of the above visitor, we can then apply it to obj, as seen in the following:

    boost::apply_visitor( object_visitor(), obj );
    

提交回复
热议问题