posts - 311, comments - 0, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

(地基工)TOLUA_TEMPLATE_BIND

Posted on 2012-08-21 15:27 点点滴滴 阅读(832) 评论(0)  编辑 收藏 引用 所属分类: 02 编程语言
One of the additional features of tolua++ is the support for class templates, by using the TOLUA_TEMPLATE_BIND directive. For example:
class vector {

	TOLUA_TEMPLATE_BIND(T, int, string, Vector3D, double)

	void clear();
	int size() const;

	const T& operator[](int index) const;
	T& operator[](int index);
	void push_back(T val);

	vector();
	~vector();
};
The TOLUA_TEMPLATE_BIND directive has to be the first thing on the class declaration, otherwise it will be ignored. This code will create 4 versions of the class vector, one for each type specified on the TOLUA_TEMPLATE_BIND parameters, each replacing the macro T (specified as the first argument of TOLUA_TEMPLATE_BIND). Thus, the functions operator[], &operator[] and push_back will have different signatures on each version of the object. The objects will be recognized as vector<type> on further declarations, and the name of the table on Lua will be vector_type_. Thus, the following Lua code could be used:
string_vector = vector_string_:new_local()
string_vector:push_back("hello")
string_vector:push_back("world")
print(string_vector[0].." "..string_vector[1])
Similarily, a template with more than 1 macro could be bound, and it could also inherit from another template:
class hash_map : public map<K,V> {

	TOLUA_TEMPLATE_BIND(K V, int string, string vector<double>)

	V get_element(K key);
	void set_element(K key, V value);

	hash_map();
	~hash_map();
};
结论:tolua++可以进行简单的模板导出。