关于union产生的万能类型

下面展示一些 联合体万能类型

#include <iostream>
#include <typeinfo>
#include <string>
#include <string.h>



namespace myvar {

struct var
{
    std::string type;
    union {
        bool b;
        char c;
        int i;
        float f;
        double d;
        std::string s;
    } ;

    var() {}
    ~var() { if(type ==  typeid (std::string).name()) {s.~basic_string(); std::cout<<"string is delete\n";}}
    var(const int& v) :i{v} { type = typeid (v).name();}
    var(const float& v):f{v} {type = typeid (v).name();}
    var(const double& v):d{v} {type = typeid (v).name();}
    var(const std::string& v) :s {v} {type = typeid (v).name();}
    var(const char& v):c {v} {type = typeid (v).name();}
    var(const bool& v):b {v} {type = typeid (v).name();}

    var& operator=(const int& v)  { type = typeid (v).name(); i = v; return *this;}
    var& operator=(const float& v)  { type = typeid (v).name(); f = v; return *this;}
    var& operator=(const double& v)  { type = typeid (v).name(); d = v; return *this;}
    var& operator=(const std::string& v)  { type = typeid (v).name(); s = v; return *this;}
    var& operator=(const char* const& v)  { type = typeid (std::string).name(); s = v; return *this;}
    var& operator=(const char& v)  { type = typeid (v).name(); c = v; return *this;}
    var& operator=(const bool& v)  { type = typeid (v).name(); b = v; return *this;}

    operator bool() const { return b; }
    operator char() const { return c; }
    operator int() const { return i; }
    operator float() const { return f; }
    operator double() const { return d; }
    operator std::string() const { return s; }


    template<typename T>
    T getv()
    {
        T t;
        return t;
    }


};

template<>
std::string var::getv()
{
    return s;
}
}


int main() {

    using namespace myvar;

    var v(std::string("hello world"));

    v = std::string("kkkkkkk");
     v ="hhhh";
    std::cout << v.getv<std::string>()<<std::endl;

    std::string s = v;

    return 0;}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值