template <class T> class StringT { public: void assign(const T* ptr); template <size_t N> void assign(const T(&ptr)[N]); }; int main() { StringT<char> str; str.assign("Hello World"); //calls "void assign(const T* ptr)" although type is (const char[12]) }
解决方法
13.3.3 Best viable function
Given these deFinitions,a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i,ICSi(F1) is not a worse conversion sequence than ICSi(F2),and then…
- F1 is not a function template specialization and F2 is a function template specialization…
在这种情况下,非模板化函数(显然)不是函数模板特化,并且根据表中定义的排序规则,“Hello World”到char const *的转换并不比const char [N]更差. “标准转换序列”部分.根据该表,在重载分辨率的上下文中,无需转换和数组到指针转换被认为是完全匹配.同样,如果模板化的重载被更改为非模板重载(即,作为void assign(const T(& ptr)[12]);),则编译str.assign(“Hello World”);由于电话模糊不清将失败.
为了确保不考虑非模板函数的重载,在“显式模板参数规范”部分下面有以下注释:
Note: An empty template argument list can be used to indicate that a given use refers to a specialization of a function template even when a non-template function (8.3.5) is visible that would otherwise be used.
所以,你可以使用str.assign<>(“Hello World”);为了那个原因.
原文地址:https://www.jb51.cc/c/111258.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。