未使用模板专用化 [英] Template specialization not used

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

问题描述

我有以下函数定义:

template <typename T> buffer_t &operator<<(buffer_t &buffer, T data);
template <> buffer_t &operator<<(buffer_t &buffer, const char *data);
template <> buffer_t &operator<<(buffer_t &buffer, const Glib::ustring &data);

当我调用:

buffer << Glib::ustring("hello");

编译器使用通用模板定义,而不是Glib :: ustring。

The compiler uses the general template definition instead of the specialization with Glib::ustring.

我在这里做错了什么?

推荐答案

模板,并且您要执行模板参数扣除。为此,您的函数调用与模板函数参数 T data 相匹配。我相信14.8.2.4适用于您的专业化的部分排序,其中 P 是模板参数, A 是实际参数的类型;重点是我的):

You have a function template, and you want to perform template argument deduction. For this purpose, your function call is matched against the templated function argument T data. I believe that 14.8.2.4 applies to the partial ordering for your specialization where P is the template argument and A is the type of the actual argument; emphasis is mine):


在部分排序完成之前,对用于部分
排序的类型执行某些转换:

Before the partial ordering is done, certain transformations are performed on the types used for partial ordering:

- 如果 P 是引用类型, P

— If P is a reference type, P is replaced by the type referred to.

- 如果 A 是引用类型,

If A is a reference type, A is replaced by the type referred to.

因此,由于你的参数的类型是 A = Glib :: ustring ,那么这不是一个良好的特殊化匹配 const Glib :: ustring& / code>作为主模板,并且即使你有一个实际的const引用,引用在部分排序期间被删除,并且你再次结束更糟的匹配。

Thus, since the type of your argument is A = Glib::ustring, then this is not as good a match for the specialization const Glib::ustring & as the primary template is, and even if you have an actual const-reference, the reference is stripped off during the partial ordering, and you again end up with a worse match.

解决这个问题的常见方法是使你的主模板成为const引用;这也可以绑定到临时对象,因此应该与值参数一样好:

The usual way to fix this is to make your primary template a const-reference; this can also bind to temporary objects and should thus be "as good as" a value argument:

template <typename T> buffer_t & operator<<(buffer_t & buffer, T const & data);
//                                                             ^^^^^^^^^

这篇关于未使用模板专用化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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