简体   繁体   English

显式模板函数和方法特化

[英]Explicit Template Function and Method Specialization

I've been looking for a clear answer, and I'm just catching bits and pieces from the web.我一直在寻找一个明确的答案,我只是从网络上捕捉点点滴滴。

I've got a function, and it needs to act differently based on a type variable.我有一个函数,它需要根据类型变量采取不同的行动。 The function takes no arguments, so overloading doesn't work, leading to template specialization.该函数不接受任何参数,因此重载不起作用,导致模板特化。 Eg:例如:

//Calls to this function would work like this:
int a = f();
int b = f<int>();
int c = f<char>();
//...

First off, is that even syntactically possible?首先,这在语法上是否可行? I feel like it is.我觉得是的。 Continuing.继续。

I'm having problems defining this function, because I get hung up on the syntax for explicit specialization.我在定义这个函数时遇到了问题,因为我对显式专业化的语法很感兴趣。 I've tried a number of different approaches, but I have yet to get even a simple example to work.我尝试了许多不同的方法,但我什至还没有一个简单的例子可以工作。

Secondly, I'm trying to (eventually) make that template function into a template method of a (non-template) class.其次,我试图(最终)将该模板函数变成(非模板)类的模板方法。 I'll cross that bridge when I come to it.当我到达那里时,我会越过那座桥。

Well, it is possible but is not one of the nicer things to do.好吧,这是可能的,但不是更好的事情之一。 Explicit template function specializations are somewhat of a dark corner, but here is how you do it:显式模板函数特化有点暗角,但您可以这样做:

template< typename T > int f(){ ... }

template<> int f<int>(){ ... }
template<> int f<char>(){ ... }

Some related reading: http://www.gotw.ca/gotw/049.htm一些相关阅读: http ://www.gotw.ca/gotw/049.htm

First off, is that even syntactically possible?首先,这在语法上是否可行? I feel like it is.我觉得是的。

It is, but don't over-complicate things – this only needs simple overloading:是的,但不要使事情过于复杂——这只需要简单的重载:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM