How to build this c++ typelist into a variant?

前端 未结 2 519
南笙
南笙 2021-01-26 04:53

Here,

how do I fix this c++ typelist template compile error?

we built a typelist, using the code from modern c++ design.

Question is now -- how do I take

2条回答
  •  感情败类
    2021-01-26 05:35

    The proper, but more advanced, approach would be actually store the values in a holder type that knows how to manage the actual type it contains.

    A simpler approach, for learning purposes, would be to map types to numbers (i.e. their position in the typelist). With that you can remember what type you are currently storing in the variant.

    To get that a working version you'll probably want to have templated constructors and setters and also an accessor function that use that type-number mapping.

    Quite simplified it could look something like this:

    template
    class variant {
        unsigned type;
        void* value;
    public:
    
        // ...
    
        template
        void set_to(const T& t) {
            STATIC_ASSERT(contains::value);
            // ... clean up previous value
            type  = index_of::value;
            value = static_cast(new T(t));
        }
    
        template
        const T& get_as() {
            STATIC_ASSERT(contains::value);
            if(type == index_of::value)
                return *static_cast(value);
            else
                throw type_error();
        }
    };
    

提交回复
热议问题