特定类型的部分模板专业化,C ++ [英] Partial template specialization for specific type, c++

查看:87
本文介绍了特定类型的部分模板专业化,C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用模板的部分专业化,我想创建一个函数/方法:

Using partial specialization of templates I would like to create a function/method:

A)仅处理形式参数的一种特定原始类型(int,double,float等),对于其他类型则抛出异常

A) processing only one specific primitive type (int, double, float,...) of the formal parameter and for other types throwing exception

template <class T>
T min ( Point <T> p )
{
    /*if (T == int) continue;
    else throw exception*/
}

B)处理形式参数的更多非原始类型(用户定义类型),而其他类型则抛出异常...

B) processing more non-primitive types (user defined types) of the formal parameter and for other types throwing exception...

一些代码示例会很有帮助(没有c ++ boost库).谢谢你的帮助.

Some code examples would be helpful (without c++ boost library). Thanks for your help.

推荐答案

这是您的问题的解决方案(A部分).

This is the solution of your problem (part 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. 示例 代码1 当T为int时.没错请忽略 但是警告!
  2. 示例 代码2 当T为两倍时.现在,看到错误 留言也.请忽略 但是警告!
  1. sample code1 when T is int. No error. Please ignore the warning though!
  2. sample code2 when T is double. Now, see the error message also. Please ignore the warning though!

类似地,您可以编写其他类型的模板(双精度型,字符型等).或者,甚至更好的是,您可以将所有这些仅合并为一个struct,而可以在单个模板(如static const bool is_T_int = true;)中定义许多布尔值(针对每种类型).等等,做实验,你会学到的!

Similarly, you can write templates for other types, (double, char, whatever). Or, even better, you can simply merge all those into just one struct, and instead can define many booleans (for each type) in a single template, like static const bool is_T_int = true;. Etc. Do experiments, you'll learn!

但是,我想知道您是否希望函数只处理一种类型,那么为什么要定义模板呢?

But then, I wonder if you want your function to handle just one type, then why define template to start with?

对于(B)部分,您从上面理解了.正确的?做实验!

For part(B), you get the idea from the above. Right? Do experiments!

这篇关于特定类型的部分模板专业化,C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆