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

编程入门 行业动态 更新时间:2024-10-13 14:27:56
本文介绍了显式模板函数和方法专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:03:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   模板   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!