显式模板函数和方法专业化 [英] Explicit Template Function and Method Specialization

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

问题描述

我一直在寻找一个明确的答案,而我只是从网络上收集到一些零碎的东西.

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. E.g.:

//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>(){ ... }

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

这篇关于显式模板函数和方法专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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