加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 未调用模板化函数

发布时间:2020-12-16 03:27:27 所属栏目:百科 来源:网络整理
导读:我在我的字符串类中重载了一个函数,然而,它永远不会被调用.为什么? template class Tclass StringT {public: void assign(const T* ptr); template size_t N void assign(const T(ptr)[N]);};int main() { StringTchar str; str.assign("Hello World"); //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”);为了那个原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读