显式模板函数和方法专用化
Explicit Template Function and Method Specialization
我一直在寻找一个明确的答案,我只是从网上捕捉零碎的东西。
我有一个函数,它需要根据类型变量采取不同的行动。 该函数不带参数,因此重载不起作用,从而导致模板专用化。 例如:
//Calls to this function would work like this:
int a = f();
int b = f<int>();
int c = f<char>();
//...
首先,这在语法上可能吗? 我觉得是这样。 继续。
我在定义这个函数时遇到了问题,因为我挂断了显式专业化的语法。 我已经尝试了许多不同的方法,但我还没有一个简单的例子来工作。
其次,我正在尝试(最终(将该模板函数变成(非模板(类的模板方法。 当我来到那座桥时,我会过那座桥。
嗯,这是可能的,但不是更好的事情之一。 显式模板函数专用化在某种程度上是一个黑暗的角落,但这是您如何做到的:
template< typename T > int f(){ ... }
template<> int f<int>(){ ... }
template<> int f<char>(){ ... }
一些相关阅读: http://www.gotw.ca/gotw/049.htm
首先,这在语法上可能吗?我觉得是这样。
是的,但不要使事情过于复杂——这只需要简单的重载:
int f()
{
return /* default, typeless implementation */;
}
template<typename T>
int f()
{
return /* type-specific implementation */;
}
template<>
int f<char>()
{
return /* char implementation */;
}
template<>
int f<int>()
{
return /* int implementation */;
}
相关文章:
- 检查子类型时的专用方法模板
- 部分方法专用化
- 基于枚举参数调用专用模板方法
- 类中一种方法的部分专用化
- 从非模板类调用专用模板方法
- 使用类指针重载C++命名空间函数模板专用化替代方法?
- 没有针对完全专用模板类的外联虚拟方法定义
- 从部分专用模板方法调用模板非静态方法
- 添加具有模板专用化的方法
- 常量字符*的模板方法专用化
- C++隐式/显式模板方法专用化问题
- enable_if在类声明之外实现的方法专用化
- 类模板:为什么我不能将单一方法专用于空类型?
- 混合显式类专用化和类方法专用化
- 显式模板专用化不能具有存储类 - 成员方法专用化
- 不完整类型(类方法专用化)的使用无效
- 显式模板函数和方法专用化
- *nix 上的模板方法专用化
- "Faking" 具有enable_if的模板类方法专用化
- 用于多种类型的模板方法专用化