使用模板的部分专业化我想创建一个函数/方法:
A)仅处理形式参数的一种特定原始类型(int,double,float,...),对于其他类型抛出异常
template <class T>
T min ( Point <T> p )
{
/*if (T == int) continue;
else throw exception*/
}
B)处理形式参数的更多非原始类型(用户定义类型)以及抛出异常的其他类型...
一些代码示例会很有帮助(没有 c++ boost 库)。感谢您的帮助。
这就是您的问题的解决方案(A 部分)。
template<bool b> struct compile_time_assert;
template<>
struct compile_time_assert<true>
{};
template<class T>
struct is_int
{
static const bool value = false;
};
template<>
struct is_int<int>
{
static const bool value = true;
};
template <class T>
T min ( Point <T> p )
{
/*
since you can check error at compile time, there is no reason to
raise exception (which is at runtime) if T is not int!
the following assert will not compile if T is not int.
not only that, you can even see the error message "_error_T_is_not_int"
if T is not int;
*/
compile_time_assert<is_int<T>::value> _error_T_is_not_int;
//your code
}
请参阅这些示例代码。
-
样本
代码1 http://www.ideone.com/KmBaP当 T 为 int 时。没有错误。请忽略
不过警告!
-
样本
代码2 http://www.ideone.com/XE4rR当 T 为双倍时。现在,查看错误
留言也。请忽略
不过警告!
同样,您可以为其他类型(双精度型、字符型等)编写模板。或者,更好的是,您可以简单地将所有这些合并为一个struct
,并且可以定义many单个模板中的布尔值(对于每种类型),例如static const bool is_T_int = true;
。等等,做实验,你就会学到东西!
但是,我想知道你是否希望你的函数只处理一种类型,那么为什么要定义模板呢?
对于(B)部分,您可以从上面得到这个想法。正确的?做实验!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)