any类型

c++是一种强类型的语言。对变量赋值时,如果类型不匹配,也不能隐式转换,编译就会报错。

在很多动态语言里,js,lua等,变量都是无类型的:

如:

var a = 3;

a = 3.1415;

a = “Hello”;

这样任意类型赋值都可以,这个a其实只是对它保存内容的一个引用。

c++要实现这样的类型有几种方式:

1. 定义一个巨大的union,把所有的类型都包含进去。

2. 把所有类型都转换成void*这种万能类型来保存,要用时由程序员来自己转换类型,这样效率看起来不错,但是类型不安全。

3. 区别对待各种类型,自己内部也知道保存的是什么类型的数据,嗯,类型安全。

boost::any就是第3种实现,挺强大的,有兴趣的同学可以看看源码。

不过我试试用第二种方式写了写一个any类,不过对原生类型int,char,float都需要写一个特殊方法才行,应该能用,不过比boost::any的实现要ugly多了。

 

 

#include <stdio.h>
#include <string>

using namespace std;

class any
{
private:
	void* _ptr;

public:
	template<typename T>
	any& operator = (T& t)
	{
		_ptr = (void*)&t;
		return *this;
	}

	any& operator = (int i)
	{
		_ptr = (void*)i;
		return *this;
	}

	template<typename T>
	friend T any_cost(any& a);
};


template<typename T>
T any_cost(any& a)
{	
	return *(static_cast<T*>(a._ptr));
}

template<>
int any_cost<int>(any& a)
{
	return (int)a._ptr;
}


void main(void)
{
	string s = "Hello";
	int i = 9;
	any a;
	
	a = 10;
	a = i;

	printf("%d\n", any_cost<int>(a));
	a = s;
	
	string str = any_cost<string>(a);
	printf(str.c_str());	
}

原文链接: https://www.cnblogs.com/hj046/archive/2010/11/24/1887092.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    any类型

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/17851

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午6:30
下一篇 2023年2月7日 下午6:30

相关推荐