C++ function template partial specialization?(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 mean 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
函数.
如果允许,它的语法应该看起来有点像下面这样:
Function partial specialization is not yet allowed as per the standard. In the example, you are actually overloading & not specializing the max<T1,T2>
function.
Its 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)
{ ^^^^^ <--- [supposed] specializing here
return 10;
}
在函数模板的情况下,C++ 标准只允许完全特化, -- 不包括编译器扩展!
In the case of a function templates, only full specialization is allowed by the C++ standard, -- excluding the compiler extensions!
这篇关于C++ 函数模板偏特化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 函数模板偏特化?


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01