显式模板函数和方法专用化

Explicit Template Function and Method Specialization

本文关键字:方法 专用 函数      更新时间:2023-10-16

我一直在寻找一个明确的答案,我只是从网上捕捉零碎的东西。

我有一个函数,它需要根据类型变量采取不同的行动。 该函数不带参数,因此重载不起作用,从而导致模板专用化。 例如:

//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 */;
}