存储任意类型

code

/*
* c++17 std::any
*/

#include 
#include 
#include 
#include 
#include 
#include 

namespace lxz {

// T不为指针时
template
struct Data {
    Data()
        : data_(nullptr)
        , cnt_(1)
    { }

    Data(const T data) {
        data_ = new T(data);
    }

    ~Data()
    {
        if (data_) {
            delete data_;
            data_ = nullptr;
        }
    }

    T& Get(void) {
        return *data_;
    }

    T* data_;
    uint32_t cnt_;
};
// T为char*时
template<>
struct Data {
    Data()
        : data_(nullptr)
        , cnt_(1)
    { }

    Data(const char* data) {
        cnt_ = strlen(data);
        data_ = (char*)(malloc(cnt_));
        (void)memcpy(data_, data, cnt_);
    }

    ~Data()
    {
        if (data_) {
            free(data_);
            data_ = nullptr;
        }
        
    }

    char* Get(void) const {
        return data_;
    }

    char* data_;
    uint32_t cnt_;
};
// T为int*时
template<>
struct Data {
    Data()
        : data_(nullptr)
        , cnt_(1)
    { }

    Data(const int* data) {
        cnt_ = strlen((const char*)data) / 4;
        data_ = (int*)malloc(cnt_ * 4);
        (void)memcpy(data_, data, cnt_ * 4);
    }

    ~Data()
    {
        if (data_) {
            free(data_);
            data_ = nullptr;
        }
    }

    int* Get(void) const {
        return data_;
    }

    int* data_;
    uint32_t cnt_;
};

class any
{
public:
    any() 
        :data_(nullptr)
    {}
    ~any() 
    {
        if (data_) {
            delete data_;
            data_ = nullptr;
        }
    }

    template
    any& operator=(const T data) {
        if (data_) {
            delete data_;
        }
        data_ = new Data(data);

        return *this;
    }

    void* Get(void) const {
        return data_;
    }
private:
    void* data_;
};

template
T& any_cast(any& obj)
{
    return ((Data*)(obj.Get()))->Get();
}

}

void lxz_any_test(void) {
    lxz::any x;

    char c = 'c';
    int val = 100;
    const char* str = "hello world!";

    while (1) {
        x = c;
        std::cout << lxz::any_cast(x) << std::endl;

        x = val;
        std::cout << lxz::any_cast(x) << std::endl;

        x = str;
        std::cout << lxz::any_cast(x) << std::endl;

        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

}

performance

存储任意类型_第1张图片

你可能感兴趣的:(cpp,c++)