Ian*_*Ian 2 c++ templates partial-specialization specialization
使用模板的部分特化我想创建一个函数/方法:
A)只处理形式参数的一个特定基本类型(int,double,float,...)以及其他类型抛出异常
template <class T>
T min ( Point <T> p )
{
/*if (T == int) continue;
else throw exception*/
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
请参阅这些示例代码.
同样,您可以为其他类型编写模板,(double,char,等等).或者,更好的是,您可以简单地将所有这些合并为一个struct,而是可以在单个模板中定义许多布尔值(对于每种类型),例如static const bool is_T_int = true;.等等做实验,你会学到的!
但是,我想知道你是否希望你的函数只处理一种类型,那么为什么要定义模板呢?
对于(B)部分,您可以从上面得到这个想法.对?做实验!
| 归档时间: |
|
| 查看次数: |
5865 次 |
| 最近记录: |