gpt4 book ai didi

c++ - 具有模板功能的模板类

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:14 24 4
gpt4 key购买 nike

谁能告诉我这段代码有什么问题?

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.
}

如果您在声明处定义函数,您将隐式声明它inline;这实际上是唯一的区别。当然,可能会有风格上的考虑,例如永远不要将函数定义放在类定义中。

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

关于c++ - 具有模板功能的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7015209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com