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

c – 具有模板功能的模板类

发布时间:2020-12-16 05:34:30 所属栏目:百科 来源:网络整理
导读:任何人都可以告诉这段代码有什么问题吗? templateclass Xclass C {public: templateclass Y void f(Y); // line 4};templateclass X,class Yvoid CX::f(Y y) { // line 8 // Something.}int main() { Cint c; char a = 'a'; c.f(a); return 0;} 汇编: $g++
任何人都可以告诉这段代码有什么问题吗?
template<class X>
class C {
public:
    template<class Y> void f(Y); // line 4
};

template<class X,class Y>
void C<X>::f(Y y) { // line 8
    // Something.
}

int main() {
    C<int> c;
    char a = 'a';
    c.f(a);
    return 0;
}

汇编:

$g++ source.cpp 
source.cpp:8: error: prototype for ‘void C<X>::f(Y)’ does not match any in class ‘C<X>’
source.cpp:4: error: candidate is: template<class X> template<class Y> void C::f(Y)

我现在可以通过在第4行声明和定义函数来完成任务,但与单独执行相比,同时声明和定义函数的后果是什么? (这不是关于在头文件和源文件中声明函数的讨论)

注意:我看过this question,但似乎唯一感兴趣的部分是分开=(

解决方法

编译器已经告诉你答案了. C类是带有一个参数的模板,成员函数f是模板成员函数,您必须以相同的方式定义它:
template <class X>
template <class Y>
void C<X>::f(Y y)
{
    // Something.
}

如果在声明站点定义函数,则会隐式声明它为内联函数;这实际上是唯一的区别.当然,可能存在风格上的考虑因素,例如:永远不要把函数定义放在类定义中.

正如您正确观察到的那样,您仍然需要在头文件中提供定义,因为您需要在使用它时实例化模板,因此您需要访问所有定义.

(编辑:李大同)

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

    推荐文章
      热点阅读