当前位置:文档之家› 模板函数写法

模板函数写法

template<const char*>
static const char* invoke(lua_Staห้องสมุดไป่ตู้e *L, int index) { return (const char*)lua_tostring(L, index); }
};
但是,由于 g++不支持将 void,float,double 三种类型作为模板参数, 所以 template<void>,template<float>,template<double>在 g++中编译会出 错!
第一种:类内定义
// 类内定义写法
template<typename T>
class CA { template<typename RET> static RET f() { RET t; return t; } }; 第二种:类外定义 // 类外定义的写法 template<typename T> class CA { template<typename RET> static RET f() { RET t; return t; } }; template<typename T>
template<typename RET>
RET CA<T>::f()
{
RET t;
return t;
}
以上两中写法在 VC 中和 g++中都可以顺利地编译!关于文章开头的第一 段代码,如何写才能在 g++中顺利编译呢?由于 g++不支持类模板中函数模板全 特化的 template<>写法,但支持 template<int>,template<char*>等等的全特化 写法,所以将文章第一段代码写为如下形式即可在 g++中编译通过:
template<>
static const char* invoke(lua_State *L, int index) { return (const char*)lua_tostring(L, index); }
};
在 VS2003 中就没有问题,但是在 Linux 中用 g++编译就会出现问题,g++ 不支持这种写法。因为 Lua_Tinker 全是模板,而且有很多这种模板与全特化同 在一个类或者结构中的模板,而至今(到笔者写稿时为止)也没有找到一种解决 方案可以将上面所示代码正确移植到 Linux,所以 Lua_Tinker 向 Linux 的移植到 现在为止还并没有成功!虽然,这次移植并没有成功,但是我还是在这次移植中 得到了许多关于模板的写法的经验。下面就介绍一下类模板中的函数模板在类内 定义与类外定义的两种写法:
struct pop_
{
template<typename T>
static T invoke(lua_State *L, int index) { return lua2type<T>::invoke(L, index); }
template<>
static char* invoke(lua_State *L, int index) { return (char*) lua_tostring(L, index); }
C++类模板的成员函数模板写法
中国 IT 实验室收集整理 佚名 2012-6-28 7:39:00 保存本 文 推荐给好友 收藏本页 欢迎进入 C/C++编程社区论坛,与 300 万技术人员互动交流 >>进入
这几天本来想将 Lua_Tinker 移植到 Linux 上去的,但是由于 VC 中的模 板写法与 gcc 中的模板写法有些不同之处,比如下面一段代码:
struct pop_
{
template<typename T>
static T invoke(lua_State *L, int index) { return lua2type<T>::invoke(L, index); }
template<char*>
static char* invoke(lua_State *L, int index) { return (char*) lua_tostring(L, index); }
相关主题