自学内容网 自学内容网

c++11的动态类型

c++17引入了any 和 variant,可以将任意数据类型统一用any或variant类型表示,在开发中还是能够带来很多便利的。在c++11版本中,可以用下面这个例子,仿照实现一个Any类型。

#include <iostream>
#include <memory>

class Any
{
public:
template<typename T>
Any(const T& val) noexcept : content(new Holder<T>(val)) {}
Any(const Any& other) noexcept : content(other.content ? other.content->Copy() : nullptr) {}
Any(Any&& other) noexcept :content(std::move(other.content)) {}
Any& operator=(const Any& other)
{
if (this == &other)
return *this;
content.reset(other.content ? other.content->Copy() : nullptr);
return *this;
}
template<typename T>
T& get() const
{
if (typeid(T).hash_code() != content->TypeID())
throw std::bad_cast();
return static_cast<Holder<T>*>(content.get())->value;
}
private:
struct Base {
virtual ~Base() {}
virtual Base* Copy() const = 0;
virtual size_t TypeID() const = 0;
};
template<typename T>
struct Holder :public Base
{
Holder<T>() = delete;
Holder<T>(const T& val) : value(val), typid(typeid(T).hash_code()) {}
~Holder<T>() {}
Base* Copy() const override { return new Holder<T>(value); }
size_t TypeID() const override { return typid; }
T value;
size_t typid;
};
std::unique_ptr<Base> content;
};


int main()
{
    int iVal = 10;
    Any param = iVal;
    std::cout<<"int val="<<param.get<int>()<<std::endl;
    std::string sVal="hello";
    param = sVal;
    std::cout<<"string val="<<param.get<std::string>()<<std::endl;
    double dVal = 101.21;
    Any paramd = dVal;
    param = paramd;
    std::cout<<"double val="<<param.get<double>()<<std::endl;
    return 0;
}


原文地址:https://blog.csdn.net/yuanshenqiang/article/details/143984861

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!