C ++函数模板部分专门化? [英] C++ function template partial specialization?

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

问题描述

我知道下面的代码是一个类的部分特化:

I know that the below code is a partial specialization of a class:

template <typename T1, typename T2> 
class MyClass { 
  … 
}; 


// partial specialization: both template parameters have same type 
template <typename T> 
class MyClass<T,T> { 
  … 
}; 

此外,我知道C ++不允许函数模板部分专门化但是我的代码是否意味着我已经部分专用我的功能模板一个/相同类型的参数?因为它适用于Microsoft Visual Studio 2010 Express!如果没有,那么你能解释一下部分专业化的概念吗?

Also I know that C++ does not allow function template partial specialization (only full is allowed). But does my code means that I have partially specialized my function template for one/same type arguments? Because it works for Microsoft Visual Studio 2010 Express! If no, then could you please explain the partial specialization concept?

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

template <typename T1, typename T2> 
inline T1 max (T1 const& a, T2 const& b) 
{ 
    return a < b ? b : a; 
} 

template <typename T> 
inline T const& max (T const& a, T const& b)
{
    return 10;
}


int main ()
{
    cout << max(4,4.2) << endl;;
    cout << max(5,5) << endl;
    int z;
    cin>>z;
}


推荐答案

实际上重载(不专门化) max< T1,T2> 函数。部分专业化 应该像下面一样看起来像

In the example, you are actually overloading (not specializing) the max<T1,T2> function. Partial specialization syntax should have looked somewhat like below (had it been allowed):

//Partial specialization is not allowed by the spec, though!
template <typename T> 
inline T const& max<T,T> (T const& a, T const& b)
{                  ^^^^^ <--- specializing here
    return 10;
}

[注意:在函数模板的情况下, ]

[Note: in the case of a function template, only full specialization is allowed by the C++ standard (excluding the compiler extensions).]

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

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