存储任意类型

发布时间:2024年01月18日

code

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

#include <cstdint>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <thread>
#include <chrono>

namespace lxz {

// T不为指针时
template<typename T>
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<char*> {
    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<int*> {
    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<typename T>
    any& operator=(const T data) {
        if (data_) {
            delete data_;
        }
        data_ = new Data<T>(data);

        return *this;
    }

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

template<typename T>
T& any_cast(any& obj)
{
    return ((Data<T>*)(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<char>(x) << std::endl;

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

        x = str;
        std::cout << lxz::any_cast<const char*>(x) << std::endl;

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

}

performance

文章来源:https://blog.csdn.net/weixin_45050132/article/details/135680826
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。