下面展示一些 联合体万能类型
。
#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;}