c – 未调用模板化函数

我在我的字符串类中重载了一个函数,然而,它永远不会被调用.为什么?
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”);为了那个原因.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...