1 Star 0 Fork 2

c++通用 / TmplArgs

forked from 梁欢 / TmplArgs 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

TmplArgs

我们可以通过函数重载为同名函数实现不同参数个数的版本,如:

int max(int a, int b) { return a>b?a:b; }
int max(int a, int b, int c)
{ return max(a,b)>max(b,c)?max(a,b):max(b,c); }

我们还可以通过使用函数模板来扩展函数对参数类型的定制,如:

template<typename _T>
void debug(_T a, std::string b) { cout<<a<<b<<endl; }
template<typename _T, typename _T1>
void debug(_T a, _T1 b, std::string c) { cout<<a<<b<<c<<endl; }

然而这种规则对于类模板却并不是(至少现在不是)奏效的。如:

template<typename _T> struct Debug {
	_T _a;
	Debug(_T a) : _a(a) {}
	void debug(std::string s) { cout<<_a<<s; }
};
template<typename _T, typename _T1> struct Debug {
	_T _a;
	_T1 _b;
	Debug(_T a, _T1 b) : _a(a), _b(b) {}
	void debug(std::string s) { cout<<_a<<_b<<s; }
};

上面的代码是不符合编译器(VS2010)规则的。也就是说我们没有办法为同名的类模板实现不同参数的版本。 那么我们有没有办法突破这个限制呢?是的,通过 TmplArgs 库,我们便获得了这种能力。

虽然 TmplArgs 的使用难度已经降到了最低,但是它仍然不完美:
首先,我们需要实现类模板的宏定义式,如 DebugBase.h。
然后,我们需要实现类模板的通用形式,如 Debug.h。
最后,我们还需要将参数规则写成函数指针的形式。

下面这段代码就是使用 TmplArgs 后对上面的 Debug 模板的改写:

Debug<void(int)> a;
a.debug(3,"0");
Debug<void(int,string)> b;
b.debug(3, "4", "0");
The MIT License (MIT) Copyright (c) 2015 lvan100 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

TmplArgs,使用模板技术分析函数参数,从而在编译期得到更多信息和条件。 展开 收起
C++
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
C++
1
https://gitee.com/ctongyong/TmplArgs.git
git@gitee.com:ctongyong/TmplArgs.git
ctongyong
TmplArgs
TmplArgs
master

搜索帮助